package com.inspect.metadata.patrolpointmnt.controller;

import com.inspect.metadata.alg.domain.BasedataAlgSubtype;
import com.inspect.metadata.alg.service.IBasedataAlgSubtypeService;
import com.inspect.metadata.patrolpointmnt.domain.BasedataPatrolPoint;
import com.inspect.metadata.patrolpointmnt.domain.BasedataStdPatrolPoint;
import com.inspect.metadata.patrolpointmnt.domain.model.InsertStdModel;
import com.inspect.metadata.patrolpointmnt.service.IBasedataPatrolPointService;
import com.inspect.metadata.patrolpointmnt.service.IBasedataStdPatrolPointService;
import com.inspect.metadata.prodevmnt.domain.BasedataDeviceType;
import com.inspect.metadata.prodevmnt.service.IBasedataDeviceTypeService;
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.base.core.web.page.TableDataInfo;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.common.security.annotation.RequiresPermissions;

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({"/patrolpointmnt/stdpatrolpoint"})
public class BasedataStdPatrolPointController extends BaseController {
    private final IBasedataStdPatrolPointService basedataStdPatrolPointService;
    private final IBasedataDeviceTypeService basedataDeviceTypeService;
    private final IBasedataAlgSubtypeService basedataAlgSubtypeService;
    private final IBasedataPatrolPointService basedataPatrolPointService;

    public BasedataStdPatrolPointController(IBasedataStdPatrolPointService basedataStdPatrolPointService, IBasedataDeviceTypeService basedataDeviceTypeService, IBasedataAlgSubtypeService basedataAlgSubtypeService, IBasedataPatrolPointService basedataPatrolPointService) {
        this.basedataStdPatrolPointService = basedataStdPatrolPointService;
        this.basedataDeviceTypeService = basedataDeviceTypeService;
        this.basedataAlgSubtypeService = basedataAlgSubtypeService;
        this.basedataPatrolPointService = basedataPatrolPointService;
    }

    @RequiresPermissions({"basedata/patrolpointmnt:stdpatrolpoint:list"})
    @GetMapping({"/list"})
    public TableDataInfo list(BasedataStdPatrolPoint basedataStdpatrolPoint) {
        this.startPage();
        List<BasedataStdPatrolPoint> list = this.basedataStdPatrolPointService.selectBasedataStdpPatrolPointList(basedataStdpatrolPoint);
        return this.getDataTable(list);
    }

    @RequiresPermissions({"basedata/patrolpointmnt:stdpatrolpoint:export"})
    @Log(
            title = "标准巡检点位库",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, BasedataStdPatrolPoint basedataStdpatrolPoint) {
        List<BasedataStdPatrolPoint> list = this.basedataStdPatrolPointService.selectBasedataStdpPatrolPointList(basedataStdpatrolPoint);
        Map<Long, String> map = this.basedataDeviceTypeService.getDeviceTypeAllPatchIdName();

        for (BasedataStdPatrolPoint basedataStdPatrolPointList : list) {
            Long ssMain = basedataStdPatrolPointList.getMainDeviceTypeId();
            Long ss = basedataStdPatrolPointList.getComponentDeviceTypeId();
            String strMain = map.get(ssMain);
            String str = map.get(ss);
            basedataStdPatrolPointList.setMainDeviceTypeName(strMain);
            basedataStdPatrolPointList.setDeviceTypeName(str.replace(strMain, StringUtils.EMPTY));
        }

        ExcelUtil<BasedataStdPatrolPoint> util = new ExcelUtil<>(BasedataStdPatrolPoint.class);
        util.exportExcel(response, list, "标准巡检点位库数据");
    }

    @GetMapping({"/{stdpatrolPointId}"})
    public AjaxResult getInfo(@PathVariable("stdpatrolPointId") Long stdPatrolPointId) {
        return AjaxResult.success(this.basedataStdPatrolPointService.selectBasedataStdPatrolPointByStdPatrolPointId(stdPatrolPointId));
    }

    @RequiresPermissions({"basedata/patrolpointmnt:stdpatrolpoint:add"})
    @Log(
            title = "标准巡检点位库",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody BasedataStdPatrolPoint basedataStdpatrolPoint) {
        basedataStdpatrolPoint.setStdPatrolPointName(basedataStdpatrolPoint.getComponentDeviceTypeName());
        return this.toAjax(this.basedataStdPatrolPointService.insertBasedataStdPatrolPoint(basedataStdpatrolPoint));
    }

    @RequiresPermissions({"basedata/patrolpointmnt:stdpatrolpoint:edit"})
    @Log(
            title = "标准巡检点位库",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody BasedataStdPatrolPoint basedataStdpatrolPoint) {
        basedataStdpatrolPoint.setStdPatrolPointName(basedataStdpatrolPoint.getComponentDeviceTypeName());
        return this.toAjax(this.basedataStdPatrolPointService.updateBasedataStdPatrolPoint(basedataStdpatrolPoint));
    }

    @RequiresPermissions({"basedata/patrolpointmnt:stdpatrolpoint:remove"})
    @Log(
            title = "标准巡检点位库",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{stdpatrolPointIds}"})
    public AjaxResult remove(@PathVariable("stdpatrolPointIds") Long[] stdPatrolPointIds) {
        return this.toAjax(this.basedataStdPatrolPointService.deleteBasedataStdPatrolPointByStdPatrolPointIds(stdPatrolPointIds));
    }

    @RequiresPermissions({"basedata/patrolpointmnt:stdpatrolpoint:remove"})
    @Log(
            title = "标准巡检点位库",
            businessType = BizType.DELETE
    )
    @PostMapping({"/removeById/{stdpatrolPointId}"})
    public AjaxResult remove(@PathVariable("stdpatrolPointId") Long stdPatrolPointId) {
        BasedataPatrolPoint basedataPatrolpoint = new BasedataPatrolPoint();
        basedataPatrolpoint.setStdParolPointId(stdPatrolPointId);
        List<BasedataPatrolPoint> basedataPatrolPoints = this.basedataPatrolPointService.selectBasedataPatrolPointList(basedataPatrolpoint);
        return !basedataPatrolPoints.isEmpty() ? AjaxResult.error("已绑定预置点，不能删除!") : this.toAjax(this.basedataStdPatrolPointService.deleteBasedataStdPatrolPointByStdPatrolPointIds(new Long[]{stdPatrolPointId}));
    }

    @PostMapping({"/exportTemplate"})
    public void exportTemplate(HttpServletResponse response) {
        ExcelUtil<BasedataStdPatrolPoint> util = new ExcelUtil<>(BasedataStdPatrolPoint.class);
        util.importTemplateExcel(response, "数据", StringUtils.EMPTY);
    }

    @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 e) {
                    throw new Exception(e.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 = 1; 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 componentDevicetypeName = "";
                            if (row.getCell(1) != null) {
                                row.getCell(1).setCellType(CellType.STRING);
                                componentDevicetypeName = row.getCell(1).getStringCellValue().trim();
                            }

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

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

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

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

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

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

                            Map devicetypeIdMain = this.getDeviceTypeIdByMainDeviceTypeName(devicetypeName, "Yes");
                            if (StringUtils.isEmpty(devicetypeIdMain)) {
                                return "失败,数据异常：第" + rowNum + "条";
                            }

                            Map devicetypeId = this.getDeviceTypeIdByDeviceTypeName(componentDevicetypeName, "No", devicetypeIdMain);
                            if (StringUtils.isEmpty(devicetypeId)) {
                                return "失败,数据异常：第" + rowNum + "条";
                            }

                            String algSubtypeId = this.getAlgSubtypeIdByAlgSubtypeName(algSubtypeName);
                            BasedataStdPatrolPoint basedataStdpatrolPoint = new BasedataStdPatrolPoint();
                            basedataStdpatrolPoint.setMainDeviceTypeId(Long.valueOf(devicetypeIdMain.get("devicetype_id").toString()));
                            basedataStdpatrolPoint.setDeviceTypeName(devicetypeName);
                            basedataStdpatrolPoint.setComponentDeviceTypeId(Long.valueOf(devicetypeId.get("devicetype_id").toString()));
                            basedataStdpatrolPoint.setComponentDeviceTypeName(componentDevicetypeName);
                            basedataStdpatrolPoint.setPatrolContent(patrolContent);
                            basedataStdpatrolPoint.setDataFormat(dataFormat);
                            basedataStdpatrolPoint.setAlgSubtypeId(Long.valueOf(algSubtypeId));
                            basedataStdpatrolPoint.setAlgSubtypeName(algSubtypeName);
                            basedataStdpatrolPoint.setUpperValue(upperValue);
                            basedataStdpatrolPoint.setLowerValue(lowerValue);
                            this.basedataStdPatrolPointService.insertBasedataStdPatrolPoint(basedataStdpatrolPoint);
                        }
                    }

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

    public Map getDeviceTypeIdByMainDeviceTypeName(String deviceTypeName, String powerMainEquFlag) {
        BasedataDeviceType basedataDevicetype = new BasedataDeviceType();
        basedataDevicetype.setDeviceTypeName(deviceTypeName);
        basedataDevicetype.setPowerMainEquFlag(powerMainEquFlag);
        return this.basedataDeviceTypeService.getDeviceTypeIdByDeviceTypeName(basedataDevicetype);
    }

    public Map getDeviceTypeIdByDeviceTypeName(String deviceTypeName, String powerMainEquFlag, Map deviceTypeIdMain) {
        String[] strings = deviceTypeName.split(StringUtils.SLASH);
        long parentId = Long.parseLong(deviceTypeIdMain.get("devicetype_id").toString());
        Map deviceTypeId = new HashMap<>();
        for (String string : strings) {
            BasedataDeviceType basedataDevicetype = new BasedataDeviceType();
            basedataDevicetype.setParentId(parentId);
            basedataDevicetype.setDeviceTypeName(string);
            basedataDevicetype.setPowerMainEquFlag(powerMainEquFlag);
            deviceTypeId = this.basedataDeviceTypeService.getDeviceTypeIdByDeviceTypeName(basedataDevicetype);
            parentId = Long.parseLong(((Map<?, ?>) deviceTypeId).get("devicetype_id").toString());
        }

        return deviceTypeId;
    }

    public String getAlgSubtypeIdByAlgSubtypeName(String algSubtypeName) {
        BasedataAlgSubtype basedataAlgSubtype = new BasedataAlgSubtype();
        basedataAlgSubtype.setAlgSubtypeName(algSubtypeName);
        List<BasedataAlgSubtype> list = this.basedataAlgSubtypeService.selectBasedataAlgSubtypeList(basedataAlgSubtype);
        return list.get(0).getAlgSubtypeId().toString();
    }

    @RequiresPermissions({"basedata/patrolpointmnt:stdpatrolpoint:add"})
    @PostMapping({"/addBatchList"})
    public AjaxResult addBatchList(@RequestBody ArrayList<InsertStdModel> list) {
        return this.toAjax(this.basedataStdPatrolPointService.addBasedataStdPatrolPointForList(list));
    }
}
