package com.casic.missiles.modular.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.casic.missiles.core.application.context.AbstractPermissionContext;
import com.casic.missiles.core.application.service.AbstractDictService;
import com.casic.missiles.core.base.controller.ExportController;
import com.casic.missiles.core.common.annotion.BussinessLog;
import com.casic.missiles.core.common.annotion.Permission;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.model.exception.ServiceException;
import com.casic.missiles.model.exception.enums.CoreExceptionEnum;
import com.casic.missiles.model.response.ErrorResponseData;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.modular.system.constant.ModularDictConst;
import com.casic.missiles.modular.system.dict.ConcentDict;
import com.casic.missiles.modular.system.enums.DeviceExportEnum;
import com.casic.missiles.modular.system.model.BusConcentrator;
import com.casic.missiles.modular.system.service.IBusConcentratorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/**
 * 控制器
 * 井深  井坐标 设备坐标问题
 *      负责部门  权属部门 责任人
 *  布防撤防
 * @author dev
 * @Date 2019-06-03 10:02:11
 */
@Controller
@RequestMapping("/concentrator")
public class BusConcentratorController extends ExportController {
    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);
    @Resource
    private IBusConcentratorService busConcentratorService;

    @Resource
    private AbstractPermissionContext permissionService;
    @Resource
    private AbstractDictService dictService;

    //    @ApiOperation("获取集中器列表")
    @GetMapping(value = "/list")
    @Permission
    @ResponseBody
    public Object list(String keywords, String status) {
        DataScope dataScope = permissionService.getAuthService().getLoginUserDataScope();
        Page<BusConcentrator> page = PageFactory.defaultPage();
        page.setRecords(busConcentratorService.selectConcentratorPage(page, dataScope, keywords, status));
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(busConcentrator -> {
                busConcentrator.setStatusName(dictService.getDictNameByCode(ModularDictConst.ONLINESTATUS, busConcentrator.getStatus()));
                busConcentrator.setDeptName(permissionService.getDeptService().getDeptName(busConcentrator.getDeptid()));
                busConcentrator.setLasttimeFormat(DateUtil.format(busConcentrator.getLasttime(), "yyyy-MM-dd HH:mm:ss"));
            });
        }
        return ResponseData.success(super.packForBT(page));
    }

    /**
     * 新增
     */
    @PostMapping(value = "/add")
    @BussinessLog(value = "新增集中器", key = "concencode,simid,position,lat,lng", dict = ConcentDict.class)
    @Permission
    @ResponseBody
    public Object add(@Valid BusConcentrator busConcentrator, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseData.error(result.getFieldErrors().get(0).getDefaultMessage());
        }
        if (busConcentrator.getDeptid() == null) {
            throw new ServiceException(CoreExceptionEnum.REQUEST_NULL);
        }
        try {
            if (busConcentrator.getSetupdate() == null) {
                busConcentrator.setSetupdate(new Date());
            }
            busConcentratorService.save(busConcentrator);
        } catch (Exception e) {
            ServiceException gunsException = new ServiceException(CoreExceptionEnum.REQUEST_NULL);
            String errorMsg = "集中器添加失败";
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                errorMsg = "集中器编号重复";
            } else if (e instanceof ServiceException) {
                ServiceException gunException = (ServiceException) e;
                errorMsg = gunException.getMessage();
            }
            gunsException.setErrorMessage(errorMsg);
            throw gunsException;
        }
        return ResponseData.success();
    }

    /**
     * 删除
     */
    @PostMapping(value = "/delete")
    @Permission
    @ResponseBody
    @BussinessLog("删除集中器")
    public Object delete(@RequestParam List<Long> ids) {
        busConcentratorService.deleteByIds(ids);
        return ResponseData.success();
    }


    //    @ApiOperation("修改集中器")
    @RequestMapping(value = "/update")
    @BussinessLog(value = "修改集中器", key = "concencode,simid,position,lat,lng", dict = ConcentDict.class)
    @Permission
    @ResponseBody
    public Object update(@Valid BusConcentrator busConcentrator, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseData.error(result.getFieldErrors().get(0).getDefaultMessage());
        }
        if (ObjectUtil.isEmpty(busConcentrator.getId())) {
            throw new ServiceException(CoreExceptionEnum.REQUEST_NULL);
        }
        try {
            busConcentratorService.updateById(busConcentrator);
        } catch (Exception e) {
            ServiceException gunsException = new ServiceException(CoreExceptionEnum.REQUEST_NULL);
            String errorMsg = "集中器修改失败";
            if (e instanceof ServiceException) {
                ServiceException gunException = (ServiceException) e;
                errorMsg = gunException.getMessage();
            } else if (e instanceof DuplicateKeyException) {
                errorMsg = "集中器编号重复";
            }
            gunsException.setErrorMessage(errorMsg);
            throw gunsException;
        }
        return ResponseData.success();
    }

    //    @ApiOperation("集中器列表导出")
    @RequestMapping(value = "/batchExport")
    @Permission
    @ResponseBody
    public void batchExport(HttpServletResponse response, String keywords, String status) throws IOException {
        DataScope dataScope = permissionService.getAuthService().getLoginUserDataScope();
        Page<BusConcentrator> page = PageFactory.defaultPage();
        page.setCurrent(1);
        page.setSize(Integer.MAX_VALUE);
        page.setRecords(busConcentratorService.selectConcentratorPage(page, dataScope, keywords, status));
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(busConcentrator -> {
                busConcentrator.setStatusName(dictService.getDictNameByCode(ModularDictConst.ONLINESTATUS, busConcentrator.getStatus()));
                busConcentrator.setDeptName(permissionService.getDeptService().getDeptName(busConcentrator.getDeptid()));
                busConcentrator.setLasttimeFormat(DateUtil.format(busConcentrator.getLasttime(), "yyyy-MM-dd HH:mm:ss"));
                busConcentrator.setSetupdateFormat(DateUtil.format(busConcentrator.getSetupdate(), "yyyy-MM-dd"));
            });
        }
        //忽略导出属性
        Set<String> excludeColumnFiledNames = new HashSet<>();
        excludeColumnFiledNames.add("deptid");
        super.exportExcelExcludeColumns(BusConcentrator.class, page.getRecords(), DeviceExportEnum.BUSCONCENTRATOR_EXPORT.getFileName(),excludeColumnFiledNames);

    }

    //@ApiOperation("批量导入集中器")
    @RequestMapping(value = "/batchImport", method = RequestMethod.POST)
    @Permission
    @ResponseBody
    public Object batchImport(@RequestParam("file") MultipartFile file) {
        List<BusConcentrator> results = new ArrayList<>();
        try {
            results = this.importExcel(BusConcentrator.class, file, null, (data) -> {
                if (StrUtil.isEmpty(data.getConcencode()) || StrUtil.isEmpty(data.getSimid())) {
                    return false;
                }
                return true;
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> list = busConcentratorService.addDeviceBatch(results);
        if (CollectionUtil.isNotEmpty(list)) {
            //获取第校验报错信息
            return new ErrorResponseData(list.get(0));
        }
        return ResponseData.success();
    }

    private ResponseData catchMybatisPlusException(Exception e, String errorMsg) {
        if (e instanceof MybatisPlusException) {
            MybatisPlusException mybatisPlusException = (MybatisPlusException) e;
            String message = mybatisPlusException.getCause().getCause().getCause().getMessage();
            if (message.contains("Duplicate entry '")) {
                return new ErrorResponseData("集中器编号重复:" + message.replaceAll("Duplicate entry '", "").replaceAll("' for key 'CONCENCODE'", ""));
            }
        }
        logger.error(errorMsg, e);
        return new ErrorResponseData(errorMsg);
    }

}
