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

import com.baomidou.mybatisplus.plugins.Page;
import com.casic.missiles.modular.system.dto.BusConfigDTO;
import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.base.response.ResponseData;
import com.casic.missiles.core.base.response.SuccessResponseData;
import com.casic.missiles.core.common.annotion.BussinessLog;
import com.casic.missiles.core.common.constant.factory.PageFactory;
import com.casic.missiles.core.common.service.ICommonPermissionService;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.config.DeviceServerProperties;
import com.casic.missiles.modular.system.constant.DeviceConfigConst;
import com.casic.missiles.modular.system.dict.BusConfigDict;
import com.casic.missiles.modular.system.service.IBusConfigService;
import io.swagger.annotations.ApiOperation;
import org.hswebframework.expands.office.excel.ExcelIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author dev
 * @Date 2019-05-16 15:55:07
 */
@Controller
@RequestMapping("/liquidConfig")
public class BusConfigController extends BaseController {


    @Autowired
    private IBusConfigService busConfigService;

    @Autowired
    private ICommonPermissionService service;

    @Autowired
    private DeviceServerProperties deviceServerProperties;

    /**
     * 获取列表deptid
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String keywords,
                       @RequestParam(required = false) String deptid) {
        SuccessResponseData successResult = new SuccessResponseData();
        try {
            Page<BusConfigDTO> page = new PageFactory<BusConfigDTO>().defaultPage();//page使用
            DataScope dataScope = service.getCurrUserDataScope();
            List<Map<String, Object>> result = busConfigService.getConfigList(page, keywords, deptid, dataScope);
            List<BusConfigDTO> busConfigDTOList = BusConfigDTO.convert(result);
            page.setRecords(busConfigDTOList);
            successResult.setData(super.packForBT(page));
            successResult.setMessage("success");
        } catch (Exception e) {
            e.printStackTrace();
            successResult.setCode(500);
            successResult.setMessage("false");
        }
        return successResult;
    }

    /**
     * 获取分页列表
     */
//    @RequestMapping(value = "/listPage")
//    @ResponseBody
//    public Object listPage(String condition) {
//        Page<BusConfig> page = new PageFactory<BusConfig>().defaultPage();
//        EntityWrapper<BusConfig> query = new EntityWrapper<>();
//        page = busConfigService.selectPage(page, query);
//        return super.packForBT(page);
//    }

    /**
     * 新增
     */
    @RequestMapping(value = "/config")
    @ResponseBody
    @BussinessLog(value = "新增配置", key = "deviceId,percent,installHeight,retryTimes,attemptsMax,ip,port", dict = BusConfigDict.class)
    public Object add(BusConfigDTO busConfigDTO) {
        SuccessResponseData successResult = new SuccessResponseData();
        try {
            busConfigService.addConfig(busConfigDTO);
            successResult.setCode(200);
            successResult.setMessage("success");
        } catch (Exception e) {
            e.printStackTrace();
            successResult.setCode(500);
            successResult.setMessage("false");
        }
        return successResult;
    }

    /**
     * 删除
     */
    @ApiOperation("删除配置")
    @RequestMapping(value = "/delete")
    @BussinessLog(value = "删除配置", key = "busConfigId", dict = BusConfigDict.class)
    @ResponseBody
    public Object delete(@RequestParam String busConfigId) {
        SuccessResponseData successResult = new SuccessResponseData();
        try {
            busConfigService.deleteById(busConfigId);
            successResult.setCode(200);
            successResult.setMessage("success");
        } catch (Exception e) {
            e.printStackTrace();
            successResult.setCode(500);
            successResult.setMessage("false");
        }
        return successResult;
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/batchDelete")
    @ResponseBody
    public Object delete(@RequestParam("busConfigIds") List<String> busConfigIds) {
        busConfigService.deleteBatchIds(busConfigIds);
        return ResponseData.success();
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @BussinessLog(value = "更新配置", key = "deviceId,percent,installHeight,retryTimes,attemptsMax,ip,port", dict = BusConfigDict.class)
    @ResponseBody
    public Object update(BusConfigDTO busConfigDTO) {
        SuccessResponseData successResult = new SuccessResponseData();
        try {
            busConfigService.updateConfig(busConfigDTO);
            successResult.setCode(200);
            successResult.setMessage("success");
        } catch (Exception e) {
            e.printStackTrace();
            successResult.setCode(500);
            successResult.setMessage("false");
        }
        return successResult;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{busConfigId}")
    @ResponseBody
    public Object detail(@PathVariable("busConfigId") String busConfigId) {
        SuccessResponseData resultData = new SuccessResponseData();
        resultData.setCode(200);
        resultData.setMessage("查询详情成功");
        resultData.setData(busConfigService.selectById(busConfigId));
        return resultData;
    }


    @RequestMapping(value = "/batchImport", method = RequestMethod.POST)
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile uploadFile) throws Exception {
        SuccessResponseData resultData = new SuccessResponseData();
        if (null == uploadFile) {
            resultData.setCode(400);
            resultData.setMessage("上传失败，无法找到文件！");
        }

//        StoreDTO storeDto = storeConnector.save("deviceConfig", new MultipartFileResource(uploadFile), uploadFile.getOriginalFilename());
        //设置表头与字段映射,可通过反射获取
        Map<String, String> mapper = new HashMap<>();
        mapper.put("设备编号", "devcode");
        mapper.put("报警阈值（%）", "percent");
        mapper.put("安装高度（M）", "installHeight");
        mapper.put("重传次数", "retryTimes");
        mapper.put("IP地址", "ip");
        mapper.put("端口号", "port");
        mapper.put("最大尝试次数", "attemptsMax");
        List<BusConfigDTO> busConfigDTOList = new ArrayList<>();
        try {
//            try (InputStream in = FileUtils.getResourceAsStream(storeDto.getResource().getFile().getPath())) {
            try (InputStream in = uploadFile.getInputStream()) {
                try {
                    ExcelIO.read(in, mapper, BusConfigDTO.class, (row) -> {
                        if (row.getSheet() == 0) {
                            busConfigDTOList.add(row.getResult());
                        } else {
                            //其他sheet停止读取
                            row.shutdown();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    resultData.setCode(400);
                    resultData.setMessage("导入失败");
                }
            }
            Map<String, Object> objectMap = busConfigService.validate(busConfigDTOList);
            if ((Boolean) objectMap.get("success")) {//检验通过后写入
                busConfigService.addBatchConfig(busConfigDTOList);
                resultData.setCode(200);
                resultData.setMessage(objectMap.get("msg").toString());
            } else {//校验失败，返回
                resultData.setCode(400);
                resultData.setMessage(objectMap.get("msg").toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
            resultData.setCode(400);
            resultData.setMessage("导入失败");
        }
        return resultData;
    }


    @ApiOperation("配置列表导出")
    @RequestMapping(value = "/batchExport")
    @ResponseBody
    public void export(@RequestParam(required = false) String keywords,
                                         @RequestParam(required = false) String deptid,
                                         HttpServletResponse response) throws IOException {
        FileInputStream fis = null;
        try {
            Page<BusConfigDTO> page = new PageFactory<BusConfigDTO>().defaultPage();//page使用
            page.setCurrent(1);
            page.setSearchCount(false);
            page.setSize(Integer.MAX_VALUE);
            DataScope dataScope = service.getCurrUserDataScope();
            List<Map<String, Object>> result = busConfigService.getConfigList(page, keywords, deptid, dataScope);
            List<BusConfigDTO> busConfigDTOList = BusConfigDTO.convert(result);
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", " attachment;filename=".concat(DeviceConfigConst.CONFIG_EXPORT_TEMP));
            if (ToolUtil.isEmpty(busConfigDTOList))
            {
                fis =  new FileInputStream(deviceServerProperties.getExportPath().concat(DeviceConfigConst.CONFIG_EXPORT_EMPTY_TEMP));
            }else {
                fis = new FileInputStream(deviceServerProperties.getExportPath().concat(DeviceConfigConst.CONFIG_EXPORT_TEMP));
            }
            Map<String, Object> var = new HashMap<>();
            var.put("list", new ArrayList<Object>() {
                {
                    for (int i = 0; i < busConfigDTOList.size(); i++) {
                        BusConfigDTO busConfigDTO = busConfigDTOList.get(i);
                        add(new HashMap<String, Object>() {
                            {
//                                put("设备id", busConfigDTO.getDeviceId()+"");
                                put("设备编号", busConfigDTO.getDevcode());
//                                put("设备名称", busConfigDTO.getDeviceName());
//                                put("设备类型编号", busConfigDTO.getDeviceType());
//                                put("设备类型名称", busConfigDTO.getDeviceTypeName());
//                                put("权属单位id", busConfigDTO.getDeptid());
//                                put("权属单位名称", busConfigDTO.getDeptName());
//                                put("闸井编号", busConfigDTO.getWellCode());
                                put("报警阈值", busConfigDTO.getThreshold());
                                put("井深百分比", busConfigDTO.getPercent());
                                put("安装高度", busConfigDTO.getInstallHeight());
                                put("重传次数", busConfigDTO.getRetryTimes());
                                put("IP地址", busConfigDTO.getIp());
                                put("端口", busConfigDTO.getPort());
                                put("最大尝试次数", busConfigDTO.getAttemptsMax());
                                put("已尝试次数", busConfigDTO.getAttemptsCurrent());
                                put("下发状态", "1".equals(busConfigDTO.getStatus())?"已下发":"未下发");
                            }
                        });
                    }
                }
            });
            //输出模板
            ExcelIO.writeTemplate(fis, response.getOutputStream(), var);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.getOutputStream().flush();
            response.getOutputStream().close();
            fis.close();
        }
    }
}
