package com.engine.salary.action;

import com.engine.salary.encrypt.EncryptUtil;
import com.engine.salary.entity.sicategory.po.ICategoryPO;
import com.engine.salary.entity.sischeme.po.InsuranceSchemeDetailPO;
import com.engine.salary.entity.sischeme.po.InsuranceSchemePO;
import com.engine.salary.enums.sicategory.IsUseEnum;
import com.engine.salary.mapper.sicategory.ICategoryMapper;
import com.engine.salary.mapper.sischeme.InsuranceSchemeDetailMapper;
import com.engine.salary.mapper.sischeme.InsuranceSchemeMapper;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.db.MapperProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;
import weaver.workflow.request.RequestManager;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: sy
 * @Description: 更新福利方案明细信息action
 * @Date: 2023/9/18
 **/
@Slf4j
public class UpdateSISchemeDetailAction implements Action {

    private EncryptUtil encryptUtil = new EncryptUtil();

    private InsuranceSchemeMapper getInsuranceSchemeMapper() {
        return MapperProxyFactory.getProxy(InsuranceSchemeMapper.class);
    }

    private InsuranceSchemeDetailMapper getInsuranceSchemeDetailMapper() {
        return MapperProxyFactory.getProxy(InsuranceSchemeDetailMapper.class);
    }

    private ICategoryMapper getICategoryMapper() {
        return MapperProxyFactory.getProxy(ICategoryMapper.class);
    }

    private String tableName;


    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            RequestManager requestManager = requestInfo.getRequestManager();
            User user = requestManager.getUser();

            DetailTable[] detailTables = requestInfo.getDetailTableInfo().getDetailTable();
            List<Map<String, String>> detailList = new ArrayList<>();
            if (detailTables.length > 0) {
                for(DetailTable dt : detailTables) {
                    Row[] s = dt.getRow();
                    for (Row r : s) {
                        Cell[] c = r.getCell();
                        Map<String, String> detailMap = Arrays.stream(c).collect(Collectors.toMap(Cell::getName,
                                property -> Util.null2String(property.getValue())));
                        detailList.add(detailMap);
                    }

                }
            }
            RecordSet rs = new RecordSet();

            String queryImageId = "select salaryname,processfield from " + tableName + " where workflowid = ?";
            rs.executeQuery(queryImageId, requestInfo.getWorkflowid());

            //遍历取出明细表中对应数据
            int detailNo = 0;
            List<ICategoryPO> listAll = getICategoryMapper().listAll().stream().filter(f -> f.getIsUse().equals(IsUseEnum.START.getValue())).collect(Collectors.toList());
            List<InsuranceSchemePO> schemeList = getInsuranceSchemeMapper().listAll();
            List<InsuranceSchemeDetailPO> updateSchemeDetails = new ArrayList<>();
            for (Map<String, String> map : detailList) {
                detailNo++;
                List<UpdateSISchemeDetailAction.SalaryField> list = new ArrayList<>();
                while (rs.next()) {
                    String processField = rs.getString("processfield");
                    String salaryName = rs.getString("salaryname");
                    String value = map.get(processField);
                    list.add(new UpdateSISchemeDetailAction.SalaryField(processField, salaryName, value));
                }
                rs.beforFirst();
                // 流程数据
                Map<String, Object> importDataMap = SalaryEntityUtil.convert2Map(list, UpdateSISchemeDetailAction.SalaryField::getSalaryName, UpdateSISchemeDetailAction.SalaryField::getValue);
                //设置更新对象元素
                String schemeId = importDataMap.getOrDefault("福利方案id", "").toString();
                String schemeName = importDataMap.getOrDefault("福利方案名称", "").toString();
                //查询福利方案
                InsuranceSchemePO targetSchemePO = new InsuranceSchemePO();
                if (StringUtils.isNotBlank(schemeId)) {
                    targetSchemePO = schemeList.stream().filter(f -> f.getId().equals(Long.valueOf(schemeId))).findFirst().orElse(null);
                } else if (StringUtils.isNotBlank(schemeName)) {
                    targetSchemePO = schemeList.stream().filter(f -> f.getSchemeName().equals(schemeName)).findFirst().orElse(null);
                } else {
                    requestInfo.getRequestManager().setMessage("错误行" + detailNo + ":" + "福利方案id和福利方案名称至少填写一个！");
                    return FAILURE_AND_CONTINUE;
                }

                if (targetSchemePO == null) {
                    requestInfo.getRequestManager().setMessage("错误行" + detailNo + ":" + "福利方案id和福利方案名称信息有误，无法匹配到已有福利方案！");
                    return FAILURE_AND_CONTINUE;
                }
                //查询福利方案下的福利项明细
                List<InsuranceSchemeDetailPO> insuranceSchemeDetailPOS = getInsuranceSchemeDetailMapper().queryListBySchemeId(targetSchemePO.getId());
                if (insuranceSchemeDetailPOS.size() > 0) {
                    encryptUtil.decryptList(insuranceSchemeDetailPOS, InsuranceSchemeDetailPO.class);
                } else {
                    requestInfo.getRequestManager().setMessage("错误行" + detailNo + ":" + "该福利方案不存在福利项明细，无法进行修改！");
                    return FAILURE_AND_CONTINUE;
                }

                String paymentScope = importDataMap.getOrDefault("缴纳对象", "").toString();
                if (StringUtils.isBlank(paymentScope)) {
                    requestInfo.getRequestManager().setMessage("错误行" + detailNo + ":" + "缴纳对象必填！");
                    return FAILURE_AND_CONTINUE;
                }

                String insuranceId = importDataMap.getOrDefault("福利项id", "").toString();
                String insuranceName = importDataMap.getOrDefault("福利项名称", "").toString();

                InsuranceSchemeDetailPO targetSchemeDetailPO = new InsuranceSchemeDetailPO();
                if (StringUtils.isNotBlank(insuranceId)) {
                    targetSchemeDetailPO = insuranceSchemeDetailPOS.stream()
                            .filter(f -> f.getInsuranceId().equals(Long.valueOf(insuranceId)) && f.getPaymentScope().equals(Integer.valueOf(paymentScope)))
                            .findFirst().orElse(null);
                } else if (StringUtils.isNotBlank(insuranceName)) {
                    List<ICategoryPO> targetCategoryPOs = listAll.stream().filter(f -> f.getInsuranceName().equals(insuranceName)).collect(Collectors.toList());
                    if (targetCategoryPOs .size() == 1) {
                        targetSchemeDetailPO = insuranceSchemeDetailPOS.stream()
                                .filter(f -> f.getInsuranceId().equals(targetCategoryPOs.get(0).getId()) && f.getPaymentScope().equals(Integer.valueOf(paymentScope)))
                                .findFirst().orElse(null);
                    } else if (targetCategoryPOs.size() > 1) {
                        requestInfo.getRequestManager().setMessage("错误行" + detailNo + ":" + "福利项名称匹配到多个福利项！");
                        return FAILURE_AND_CONTINUE;
                    }

                } else {
                    requestInfo.getRequestManager().setMessage("错误行" + detailNo + ":" + "福利项id和福利项名称至少填写一个！");
                    return FAILURE_AND_CONTINUE;
                }

                if (targetSchemeDetailPO == null) {
                    requestInfo.getRequestManager().setMessage("错误行" + detailNo + ":" + "福利项id和福利项名称信息有误，无法匹配到方案已有福利项！");
                    return FAILURE_AND_CONTINUE;
                }

                String isPayment = importDataMap.getOrDefault("是否缴费", "").toString();
                if (StringUtils.isNotBlank(isPayment)) {
                    targetSchemeDetailPO.setIsPayment(Integer.valueOf(isPayment));
                }

                String upperLimit = importDataMap.getOrDefault("基数上限", "").toString();
                if (StringUtils.isNotBlank(upperLimit)) {
                    targetSchemeDetailPO.setUpperLimit(upperLimit);
                }
                String lowerLimit = importDataMap.getOrDefault("基数下限", "").toString();
                if (StringUtils.isNotBlank(lowerLimit)) {
                    targetSchemeDetailPO.setLowerLimit(lowerLimit);
                }
                String paymentProportion = importDataMap.getOrDefault("缴纳比例", "").toString();
                if (StringUtils.isNotBlank(paymentProportion)) {
                    targetSchemeDetailPO.setPaymentProportion(paymentProportion);
                }
                String fixedCost = importDataMap.getOrDefault("固定费用", "").toString();
                if (StringUtils.isNotBlank(fixedCost)) {
                    targetSchemeDetailPO.setFixedCost(fixedCost);
                }
                String validNum = importDataMap.getOrDefault("有效小数位", "").toString();
                if (StringUtils.isNotBlank(validNum)) {
                    targetSchemeDetailPO.setValidNum(Integer.valueOf(validNum));
                }else {
                    targetSchemeDetailPO.setValidNum(2);
                }
                String rententionRule = importDataMap.getOrDefault("进位规则", "").toString();
                if (StringUtils.isNotBlank(rententionRule)) {
                    targetSchemeDetailPO.setRententionRule(Integer.valueOf(rententionRule));
                }
                targetSchemeDetailPO.setUpdateTime(new Date());

                updateSchemeDetails.add(targetSchemeDetailPO);

            }
            //更新方案明细
            if (updateSchemeDetails.size() > 0) {
                encryptUtil.encryptList(updateSchemeDetails, InsuranceSchemeDetailPO.class);
                updateSchemeDetails.forEach(getInsuranceSchemeDetailMapper()::updateAll);
            }


        } catch (Exception e) {
            log.error("福利方案更新异常", e);
            requestInfo.getRequestManager().setMessage(e.getMessage());
            return FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }


    class SalaryField {

        private String processField;

        private String salaryName;

        private String value;

        public String getProcessField() {
            return processField;
        }

        public void setProcessField(String processField) {
            this.processField = processField;
        }

        public String getSalaryName() {
            return salaryName;
        }

        public void setSalaryName(String salaryName) {
            this.salaryName = salaryName;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public SalaryField(String processField, String salaryName, String value) {
            this.processField = processField;
            this.salaryName = salaryName;
            this.value = value;
        }
    }
}
