package com.ho.business.service.impl;

import cn.hutool.core.date.DateUtil;
import com.ho.business.entity.DropDownVo;
import com.ho.business.entity.PlanningCurveTemplate;
import com.ho.business.entity.PlanningPolicy;
import com.ho.business.mapper.PlanningPolicyMapper;
import com.ho.business.service.PlanningPolicyService;
import com.ho.common.tools.constant.DefineConstant;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PlanningPolicyServiceImpl implements PlanningPolicyService {


    @Autowired
    private PlanningPolicyMapper policyMapper;

    @Override
    public List<PlanningPolicy> getPlanningPolicys(PlanningPolicy policy) {
        return policyMapper.getPlanningPolicys(policy);
    }

    @Override
    public List<PlanningPolicy> getPlanningPolicyDetail4Modify(PlanningPolicy policy) {
        return policyMapper.getPlanningPolicyDetail4Modify(policy);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> addPlanningPolicy(PlanningPolicy policy) {
        Map<String,Object> result = new HashMap<>(0);
        if( policy == null ){
            result.put("code","201");
            result.put("msg",DefineConstant.PlanningPolicy.DATA_NOT_EMPTY);
        }

        // 校验策略名称和自定义策略名称是否有重复，如果重复则不允许新增
        int i = policyMapper.checkName(null,policy.getPolicyName(), 1);
        if( i > 0 ){
            result.put("code","202");
            result.put("msg",DefineConstant.PlanningPolicy.POLICY_NAME_NOT_REPEAT);
            return result;
        }

        if ( policy.getPolicyTypeId() == 9 ) {
            i = policyMapper.checkName(null,policy.getPolicyName(), 2);
            if( i > 0 ){
                result.put("code","202");
                result.put("msg",DefineConstant.PlanningPolicy.CUSTOM_POLICY_NAME_NOT_REPEAT);
                return result;
            }
        }

        try {
            int line = policyMapper.addPlanningPolicy(policy);
            result.put("code",line>0?"200":"204");
            result.put("msg",line>0?DefineConstant.PlanningPolicy.SAVE_SUCCESS:DefineConstant.PlanningPolicy.SAVE_FAIL);
        } catch (Exception e) {
            result.put("code","205");
            result.put("msg",DefineConstant.PlanningPolicy.SAVE_ERROR);
            e.printStackTrace();
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> modifyPlanningPolicy(PlanningPolicy policy) {
        Map<String,Object> result = new HashMap<>(0);
        if( policy == null ){
            result.put("code","201");
            result.put("msg",DefineConstant.PlanningPolicy.DATA_NOT_EMPTY);
        }

        // 校验策略名称和自定义策略名称是否有重复，如果重复则不允许新增
        int i = policyMapper.checkName(policy.getPolicyId(),policy.getPolicyName(), 1);
        if( i > 0 ){
            result.put("code","202");
            result.put("msg",DefineConstant.PlanningPolicy.POLICY_NAME_NOT_REPEAT);
            return result;
        }

        if ( policy.getPolicyTypeId() == 9 ) {
            i = policyMapper.checkName(policy.getPolicyId(),policy.getPolicyName(), 2);
            if( i > 0 ){
                result.put("code","202");
                result.put("msg",DefineConstant.PlanningPolicy.CUSTOM_POLICY_NAME_NOT_REPEAT);
                return result;
            }
        }

        try {
            int line = policyMapper.modifyPlanningPolicy(policy);
            result.put("code",line>0?"200":"204");
            result.put("msg",line>0?DefineConstant.PlanningPolicy.MODIFY_SUCCESS:DefineConstant.PlanningPolicy.MODIFY_FAIL);
        } catch (Exception e) {
            result.put("code","205");
            result.put("msg",DefineConstant.PlanningPolicy.MODIFY_ERROR);
            e.printStackTrace();
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> deletePlanningPolicy(List<Integer> ids) {
        Map<String,Object> result = new HashMap<>(0);
        if( ids.size() <= 0 ){
            result.put("code","201");
            result.put("msg",DefineConstant.PlanningPolicy.DATA_NOT_EMPTY);
        }
        try {
            int line = policyMapper.deletePlanningPolicy(ids);
            result.put("code",line>0?"200":"204");
            result.put("msg",line>0?DefineConstant.PlanningPolicy.DELETE_SUCCESS:DefineConstant.PlanningPolicy.DELETE_FAIL);
        } catch (Exception e) {
            result.put("code","205");
            result.put("msg",DefineConstant.PlanningPolicy.DELETE_ERROR);
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public List<DropDownVo> queryPolicyTypes() {
        return policyMapper.queryPolicyTypes();
    }

    @Override
    public List<DropDownVo> queryPolicyPriority() {
        return policyMapper.queryPolicyPriority();
    }

    @Override
    public Map<String, Object> batchImport(String fileName, MultipartFile file,Integer stationId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(0);
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            result.put("code", 500);
            result.put("msg", DefineConstant.PlanningPolicy.FILE_FORMAT_ONLY);
            return result;
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            result.put("code", 200);
            result.put("msg", DefineConstant.PlanningCurve.FILE_UPLOAD_SUCCESS);
        } else {
            result.put("code", 500);
            result.put("msg", DefineConstant.PlanningCurve.FILE_UPLOAD_ERROR_EMPTY_SHEET);
            return result;
        }

        List<PlanningPolicy> policys = new ArrayList<PlanningPolicy>(0);
        PlanningPolicy policy = null;

        // 查询类型、级别和计划曲线模板备用
        List<DropDownVo> types = policyMapper.queryPolicyTypes();
        List<DropDownVo> prioritys = policyMapper.queryPolicyPriority();
        List<PlanningCurveTemplate> tems = policyMapper.getPlanningCurveTemplates(stationId);

        try {
            int sheetLine = sheet.getLastRowNum();
            for (int r = 1; r <= sheetLine; r++) {
                policy = new PlanningPolicy();
                policy.setStationId(stationId);
                Row row = sheet.getRow(r);
                // 策略类型
                if (row.getCell(0) != null) {
                    row.getCell(0).setCellType(CellType.STRING);
                    String policyType = row.getCell(0).getStringCellValue();
                    if (!policyType.equals("") && null != policyType) {
                        for (DropDownVo type : types) {
                            if( type.getName().equals(policyType) ){
                                policy.setPolicyTypeId(type.getId());
                                break;
                            } else {
                                policy.setPolicyTypeId(null);
                            }
                        }
                    }
                }
                // 策略名称
                if (row.getCell(1) != null) {
                    row.getCell(1).setCellType(CellType.STRING);
                    String policyName = row.getCell(1).getStringCellValue();
                    if (!policyName.equals("") && null != policyName) {
                        policy.setPolicyName(policyName);
                    } else {
                        policy.setPolicyName(null);
                    }
                }
                // 自定义策略名称
                if (row.getCell(2) != null) {
                    row.getCell(2).setCellType(CellType.STRING);
                    String customPolicyName = row.getCell(2).getStringCellValue();
                    if (!customPolicyName.equals("") && null != customPolicyName) {
                        policy.setCustomPolicyName(customPolicyName);
                    } else {
                        policy.setCustomPolicyName(null);
                    }
                }
                // 自定义策略开始时间
                if (row.getCell(3) != null) {
                    row.getCell(3).setCellType(CellType.STRING);
                    String customPolicyStartDate = row.getCell(3).getStringCellValue();
                    if (!customPolicyStartDate.equals("") && null != customPolicyStartDate) {
                        policy.setCustomPolicyStartDate(DateUtil.parse(customPolicyStartDate));
                    } else {
                        policy.setCustomPolicyStartDate(null);
                    }
                }
                // 自定义策略结束时间
                if (row.getCell(4) != null) {
                    row.getCell(4).setCellType(CellType.STRING);
                    String customPolicyEndDate = row.getCell(4).getStringCellValue();
                    if (!customPolicyEndDate.equals("") && null != customPolicyEndDate) {
                        policy.setCustomPolicyEndDate(DateUtil.parse(customPolicyEndDate));
                    } else {
                        policy.setCustomPolicyEndDate(null);
                    }
                }
                // 计划曲线模板
                if (row.getCell(5) != null) {
                    row.getCell(5).setCellType(CellType.STRING);
                    String planningTemplateName = row.getCell(5).getStringCellValue();
                    if (!planningTemplateName.equals("") && null != planningTemplateName) {
                        for (PlanningCurveTemplate tem : tems) {
                            if ( tem.getTemplateName().equals(planningTemplateName) ) {
                                policy.setTemId(tem.getTemId());
                                break;
                            } else {
                                policy.setTemId(null);
                            }
                        }
                    }
                }
                // 策略优先级
                if (row.getCell(6) != null) {
                    row.getCell(6).setCellType(CellType.STRING);
                    String policyPriorityName = row.getCell(6).getStringCellValue();
                    if (!policyPriorityName.equals("") && null != policyPriorityName) {
                        for (DropDownVo priority : prioritys) {
                            if ( priority.getName().equals(policyPriorityName) ) {
                                policy.setPolicyPriorityId(priority.getId());
                                break;
                            } else {
                                policy.setPolicyPriorityId(null);
                            }
                        }
                    }
                }
                // 生效类型
                if (row.getCell(7) != null) {
                    row.getCell(7).setCellType(CellType.STRING);
                    String effectiveType = row.getCell(7).getStringCellValue();
                    if (!effectiveType.equals("") && null != effectiveType) {
                        policy.setEffectiveType("永久生效".equals(effectiveType)?0:1);
                    } else {
                        policy.setEffectiveType(null);
                    }
                }
                // 生效开始时间
                if (row.getCell(8) != null) {
                    row.getCell(8).setCellType(CellType.STRING);
                    String effectiveStartDate = row.getCell(8).getStringCellValue();
                    if (!effectiveStartDate.equals("") && null != effectiveStartDate) {
                        policy.setEffectiveStartDate(DateUtil.parse(effectiveStartDate));
                    } else {
                        policy.setEffectiveStartDate(null);
                    }
                }
                // 生效结束时间
                if (row.getCell(9) != null) {
                    row.getCell(9).setCellType(CellType.STRING);
                    String effectiveEndDate = row.getCell(9).getStringCellValue();
                    if (!effectiveEndDate.equals("") && null != effectiveEndDate) {
                        policy.setEffectiveEndDate(DateUtil.parse(effectiveEndDate));
                    } else {
                        policy.setEffectiveEndDate(null);
                    }
                }
                // 生效结束时间
                if (row.getCell(10) != null) {
                    row.getCell(10).setCellType(CellType.STRING);
                    String status = row.getCell(10).getStringCellValue();
                    if (!status.equals("") && null != status) {
                        policy.setStatus("启用".equals(status)?1:0);
                    } else {
                        policy.setStatus(null);
                    }
                }
                // 备注
                if (row.getCell(11) != null) {
                    row.getCell(11).setCellType(CellType.STRING);
                    String context = row.getCell(11).getStringCellValue();
                    if (!context.equals("") && null != context) {
                        policy.setContext(context);
                    } else {
                        policy.setContext(null);
                    }
                }
                policys.add(policy);
            }
            // 组织好的数据入库
            int line = 0;
            if ( null != policys && policys.size() > 0 ) {
                line = policyMapper.batchPlanningPolicy(policys);
            }
            result.put("code",line>0?"200":"204");
            result.put("msg",line>0?DefineConstant.PlanningPolicy.SAVE_SUCCESS:DefineConstant.PlanningPolicy.SAVE_FAIL);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", DefineConstant.PlanningCurve.OPERATION_FAILED);
        }
        return result;
    }

    private boolean isEmptyCell(Cell cell) {
        if (cell == null || cell.getCellType().equals(CellType.BLANK)) {
            return true;
        }
        return false;
    }

    @Override
    public List<PlanningCurveTemplate> getPlanningCurveTemplates(Integer stationId) {
        return policyMapper.getPlanningCurveTemplates(stationId);
    }
}
