package com.inspect.metadata.prodevmnt.controller;

import com.inspect.metadata.prodevmnt.domain.BasedataDevice;
import com.inspect.metadata.prodevmnt.domain.BasedataDeviceType;
import com.inspect.metadata.prodevmnt.domain.BasedataDeviceTypeEx;
import com.inspect.metadata.prodevmnt.domain.vo.ProDeviceTypeTreeSelectVO;
import com.inspect.metadata.prodevmnt.service.IBasedataDeviceService;
import com.inspect.metadata.prodevmnt.service.IBasedataDeviceTypeService;
import com.inspect.metadata.prodevmnt.util.ExportExcelUtil;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.common.security.annotation.RequiresPermissions;
import com.inspect.common.security.utils.SecurityUtils;

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

import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping({"/devicetype"})
public class BasedataDeviceTypeController extends BaseController {
    private final IBasedataDeviceTypeService basedataDeviceTypeService;
    private final IBasedataDeviceService basedataDeviceService;
    private String ancestorsAddr = "";

    public BasedataDeviceTypeController(IBasedataDeviceTypeService basedataDeviceTypeService, IBasedataDeviceService basedataDeviceService) {
        this.basedataDeviceTypeService = basedataDeviceTypeService;
        this.basedataDeviceService = basedataDeviceService;
    }

    //@RequiresPermissions({"basedata:devicetype:list"})
    @GetMapping({"/list"})
    public AjaxResult list(BasedataDeviceType basedataDevicetype) {
        List<BasedataDeviceType> list = this.basedataDeviceTypeService.selectBasedataDeviceTypeList(basedataDevicetype);
        List<BasedataDeviceTypeEx> listEx = new ArrayList<>();
        for(int i = 0; i < list.size(); i++) {
            BasedataDeviceType basedataDeviceType = list.get(i);
            BasedataDeviceTypeEx basedataDeviceTypeEx = new BasedataDeviceTypeEx();
            basedataDeviceTypeEx.setParentName(basedataDeviceType.getParentName());
            basedataDeviceTypeEx.setParentId(basedataDeviceType.getParentId());
            basedataDeviceTypeEx.setOrderNum(basedataDeviceType.getOrderNum());
            basedataDeviceTypeEx.setAncestors(basedataDeviceType.getAncestors());
            basedataDeviceTypeEx.setChildren(basedataDeviceType.getChildren());
            basedataDeviceTypeEx.setDevicetypeId(basedataDeviceType.getDeviceTypeId());
            basedataDeviceTypeEx.setAncestorsAddr(basedataDeviceType.getAncestorsAddr());
            basedataDeviceTypeEx.setPowerMainEquFlag(basedataDeviceType.getPowerMainEquFlag());
            basedataDeviceTypeEx.setDevicetypeName(basedataDeviceType.getDeviceTypeName());
            basedataDeviceTypeEx.setDevicetypeCode(basedataDeviceType.getDeviceTypeCode());
            basedataDeviceTypeEx.setPhaseNum(basedataDeviceType.getPhaseNum());
            basedataDeviceTypeEx.setPhase(basedataDeviceType.getPhase());
            basedataDeviceTypeEx.setStatus(basedataDeviceType.getStatus());
            basedataDeviceTypeEx.setDelFlag(basedataDeviceType.getDelFlag());
            basedataDeviceTypeEx.setProfessionType(basedataDeviceType.getProfessionType());
            basedataDeviceTypeEx.setLevel(basedataDeviceType.getLevel());
            listEx.add(basedataDeviceTypeEx);
        }
        return AjaxResult.success(listEx);
    }

    @RequiresPermissions({"basedata:devicetype:export"})
    @Log(
            title = "设备类别",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, BasedataDeviceType basedataDevicetype) {
        List<BasedataDeviceType> list = this.basedataDeviceTypeService.selectBasedataDeviceTypeList(basedataDevicetype);
        Map map = this.basedataDeviceTypeService.getDeviceTypeAllPatchIdName();

        for (BasedataDeviceType basedataDeviceList : list) {
            Long ss = basedataDeviceList.getDeviceTypeId();
            String str = map.get(ss).toString();
            basedataDeviceList.setAncestorsAddr(str);
        }

        ExcelUtil<BasedataDeviceType> util = new ExcelUtil<>(BasedataDeviceType.class);
        util.exportExcel(response, list, "设备类别数据");
    }

    @RequiresPermissions({"basedata:devicetype:query"})
    @GetMapping({"/{devicetypeId}"})
    public AjaxResult getInfo(@PathVariable("devicetypeId") Long deviceTypeId) {
        return AjaxResult.success(this.basedataDeviceTypeService.selectBasedataDeviceTypeByDeviceTypeId(deviceTypeId));
    }

    @RequiresPermissions({"basedata:devicetype:add"})
    @Log(
            title = "设备类别",
            businessType = BizType.INSERT
    )
    @PostMapping({"/add"})
    public AjaxResult add(@RequestBody BasedataDeviceType basedataDevicetype) {
        if ("1".equals(basedataDeviceTypeService.checkDeviceTypeNameUnique(basedataDevicetype))) {
            return AjaxResult.error("设备类别'" + basedataDevicetype.getDeviceTypeName() + "'类别名称已存在");
        } else if ("1".equals(basedataDeviceTypeService.checkDeviceTypeCodeUnique(basedataDevicetype))) {
            return AjaxResult.error("设备类别'" + basedataDevicetype.getDeviceTypeCode() + "'类别编码已存在");
        } else {
            basedataDevicetype.setCreateBy(SecurityUtils.getUsername());
            basedataDevicetype.setCreateTime(DateUtils.getNowDate());
            if ("无相别".equals(basedataDevicetype.getPhaseNum())) {
                basedataDevicetype.setPhase("O");
            }

            try {
                return toAjax(basedataDeviceTypeService.insertBasedataDeviceType(basedataDevicetype));
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("添加失败，设备类型编码重复!");
            }
        }
    }

    @RequiresPermissions({"basedata:devicetype:edit"})
    @Log(
            title = "设备类别",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/update"})
    public AjaxResult edit(@RequestBody BasedataDeviceType basedataDevicetype) {
        if ("1".equals(basedataDeviceTypeService.checkDeviceTypeNameUnique(basedataDevicetype))) {
            return AjaxResult.error("设备类别'" + basedataDevicetype.getDeviceTypeName() + "'修改失败，设备类别名称已存在");
        } else if ("1".equals(basedataDeviceTypeService.checkDeviceTypeCodeUnique(basedataDevicetype))) {
            return AjaxResult.error("设备类别'" + basedataDevicetype.getDeviceTypeCode() + "'修改失败，设备类别编码已存在");
        } else {
            if ("无相别".equals(basedataDevicetype.getPhaseNum())) {
                basedataDevicetype.setPhase("O");
            }

            return toAjax(basedataDeviceTypeService.updateBasedataDeviceType(basedataDevicetype));
        }
    }

    @RequiresPermissions({"basedata:devicetype:remove"})
    @Log(
            title = "设备类别",
            businessType = BizType.DELETE
    )
    @PostMapping({"/delete/{devicetypeIds}"})
    public AjaxResult remove(@PathVariable("devicetypeIds") Long[] deviceTypeIds) {
        BasedataDevice basedataDevice = new BasedataDevice();
        basedataDevice.setDeviceTypeId(deviceTypeIds[0]);
        List<BasedataDevice> deviceList = this.basedataDeviceService.selectBasedataDeviceList(basedataDevice);
        if (!deviceList.isEmpty()) {
            return AjaxResult.error("删除失败，设备类型已绑定，请先删除绑定设备！");
        } else {
            BasedataDeviceType basedataDevicetype = new BasedataDeviceType();
            basedataDevicetype.setParentId(deviceTypeIds[0]);
            List<BasedataDeviceType> basedataDeviceTypes = this.basedataDeviceTypeService.selectBasedataDeviceTypeList(basedataDevicetype);
            return !basedataDeviceTypes.isEmpty() ? AjaxResult.error("删除失败，存在子部件无法删除！") : this.toAjax(this.basedataDeviceTypeService.deleteBasedataDeviceTypeByDeviceTypeIds(deviceTypeIds));
        }
    }

    @PostMapping({"/exportTemplate"})
    public void downloadTemp(HttpServletResponse response) {
        ExportExcelUtil.exportTemplate(response, "设备类型导入模板.xlsx");
    }

    @PostMapping({"/importData"})
    public AjaxResult importData(MultipartFile file) throws Exception {
        if (file == null) {
            throw new NullArgumentException();
        } else {
            String filename = file.getOriginalFilename();
            if (filename == null) {
                throw new NullArgumentException();
            } else {
                String a = "";

                try {
                    a = this.parseRowCell(filename, file.getInputStream());
                } catch (IOException var5) {
                    AjaxResult.error(var5.getMessage());
                }

                return AjaxResult.success("导入结果", a);
            }
        }
    }

    private String parseRowCell(String filename, InputStream is) throws Exception {
        try {
            Workbook workbook = null;
            if (filename.endsWith(".xls")) {
                workbook = new HSSFWorkbook(is);
            }

            if (filename.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(is);
            }

            if (workbook == null) {
                throw new NullArgumentException();
            } else {
                Sheet sheet = workbook.getSheetAt(0);
                if (sheet == null) {
                    throw new NullArgumentException();
                } else {
                    for (int rowNum = 15; rowNum <= sheet.getLastRowNum(); ++rowNum) {
                        Row row = sheet.getRow(rowNum);
                        if (row != null) {
                            String devicetypeName = "";
                            if (row.getCell(0) != null) {
                                row.getCell(0).setCellType(CellType.STRING);
                                devicetypeName = row.getCell(0).getStringCellValue().trim();
                            }

                            String flag = "";
                            if (row.getCell(1) != null) {
                                row.getCell(1).setCellType(CellType.STRING);
                                flag = row.getCell(1).getStringCellValue().trim();
                            }

                            String devicetypeCode = "";
                            if (row.getCell(2) != null) {
                                row.getCell(2).setCellType(CellType.STRING);
                                devicetypeCode = row.getCell(2).getStringCellValue().trim();
                            }

                            String phaseNum = "";
                            if (row.getCell(3) != null) {
                                row.getCell(3).setCellType(CellType.STRING);
                                phaseNum = row.getCell(3).getStringCellValue().trim();
                            }

                            String phase = "";
                            if (row.getCell(4) != null) {
                                row.getCell(4).setCellType(CellType.STRING);
                                phase = row.getCell(4).getStringCellValue().trim();
                            }

                            if (StringUtils.isAllBlank(new CharSequence[]{devicetypeName, flag, devicetypeCode, phaseNum, phase})) {
                                throw new Exception("请检查必填项！");
                            }

                            this.ancestorsAddr = devicetypeName;
                            String parentId;
                            if (devicetypeName.indexOf("/") > 0) {
                                Map devicetypeId = this.getDeviceTypeIdByDeviceTypeName(devicetypeName, "100");
                                parentId = String.valueOf(devicetypeId.get("parent_id"));
                                devicetypeName = devicetypeId.get("devicetypeName").toString();
                            } else {
                                parentId = "100";
                            }

                            BasedataDeviceType basedataDevicetype = new BasedataDeviceType();
                            basedataDevicetype.setParentId(Long.valueOf(parentId));
                            basedataDevicetype.setPowerMainEquFlag(flag);
                            basedataDevicetype.setDeviceTypeName(devicetypeName);
                            basedataDevicetype.setDeviceTypeCode(devicetypeCode);
                            basedataDevicetype.setPhaseNum(phaseNum);
                            basedataDevicetype.setPhase(phase);
                            basedataDevicetype.setAncestorsAddr(this.ancestorsAddr);
                            this.basedataDeviceTypeService.insertBasedataDeviceType(basedataDevicetype);
                        }
                    }

                    return "成功！";
                }
            }
        } catch (IOException e) {
            e.getMessage();
            return "失败！";
        }
    }

    public Map getDeviceTypeIdByDeviceTypeName(String deviceTypeName, String parentId) {
        String[] strings = deviceTypeName.split(StringUtils.SLASH);
        Map devicetypeId = new HashMap<>();

        for (String string : strings) {
            BasedataDeviceType basedataDevicetype = new BasedataDeviceType();
            basedataDevicetype.setParentId(Long.valueOf(parentId));
            basedataDevicetype.setDeviceTypeName(string);
            devicetypeId = this.basedataDeviceTypeService.getDeviceTypeIdByDeviceTypeName(basedataDevicetype);
            if (devicetypeId == null) {
                this.ancestorsAddr = deviceTypeName.split(string)[0] + string;
                devicetypeId = new HashMap<>();
                devicetypeId.put("parent_id", basedataDevicetype.getParentId());
                devicetypeId.put("devicetypeName", basedataDevicetype.getDeviceTypeName());
                return devicetypeId;
            }

            parentId = ((Map<?, ?>) devicetypeId).get("devicetype_id").toString();
            devicetypeId.put("devicetypeName", string);
        }

        return devicetypeId;
    }

    @Log(
            title = "获得设备类型上级层级全路径名称",
            businessType = BizType.OTHER
    )
    @GetMapping({"/getDeviceTypeAllPatchIdName"})
    public AjaxResult getDeviceTypeAllPatchIdName() {
        Map<Long, String> map = this.basedataDeviceTypeService.getDeviceTypeAllPatchIdName();
        return AjaxResult.success(map);
    }

    @Log(
            title = "设备树查询",
            businessType = BizType.OTHER
    )
    @GetMapping({"/getProDeviceTypeTreeSelect"})
    public AjaxResult getProDeviceTypeTreeSelect(BasedataDeviceType basedataDevicetype) {
        List<ProDeviceTypeTreeSelectVO> list = this.basedataDeviceTypeService.getProDeviceTypeTreeSelect(basedataDevicetype);
        return AjaxResult.success(list);
    }

    @RequiresPermissions({"basedata:devicetype:list"})
    @GetMapping({"/getCommpTypeTreeSelectByMainDevicetypeId"})
    public AjaxResult getCompTypeTreeSelectByMainDeviceTypeId(BasedataDeviceType basedataDevicetype) {
        List<BasedataDeviceType> list = this.basedataDeviceTypeService.getCompTypeTreeSelectByMainDeviceTypeId(basedataDevicetype);
        return AjaxResult.success(list);
    }
}
