package com.engine.salary.action;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.salaryarchive.param.SalaryArchiveImportActionParam;
import com.engine.salary.entity.salaryarchive.po.SalaryArchivePO;
import com.engine.salary.entity.taxagent.param.TaxAgentQueryParam;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.enums.salaryarchive.SalaryArchiveStatusEnum;
import com.engine.salary.mapper.archive.SalaryArchiveMapper;
import com.engine.salary.service.SalaryArchiveService;
import com.engine.salary.service.TaxAgentService;
import com.engine.salary.service.impl.SalaryArchiveServiceImpl;
import com.engine.salary.service.impl.TaxAgentServiceImpl;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.db.MapperProxyFactory;
import com.engine.salary.wrapper.SalaryArchiveWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

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

@Slf4j
public class CheckInitSalaryAction implements Action {


    private SalaryArchiveWrapper getSalaryArchiveWrapper(User user) {
        return ServiceUtil.getService(SalaryArchiveWrapper.class, user);
    }

    private TaxAgentService getTaxAgentService(User user) {
        return ServiceUtil.getService(TaxAgentServiceImpl.class, user);
    }

    private SalaryArchiveService getSalaryArchiveService(User user) {
        return ServiceUtil.getService(SalaryArchiveServiceImpl.class, user);
    }

    private SalaryArchiveMapper getSalaryArchiveMapper() {
        return MapperProxyFactory.getProxy(SalaryArchiveMapper.class);
    }

    private String tableName;


    public String getTableName() {
        return tableName;
    }

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

    // 是否执行action的字段, 0代表不执行，其余代表执行
    private String enableField;

    public String getEnableField() {
        return enableField;
    }

    public void setEnableField(String enableField) {
        this.enableField = enableField;
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        try {

            Property[] properties = requestInfo.getMainTableInfo().getProperty();
            Map<String, String> fieldMap = Arrays.stream(properties).collect(Collectors.toMap(Property::getName,
                    property -> Util.null2String(property.getValue())));

            String enable = fieldMap.get(enableField);
            if (StringUtils.isNotBlank(enable) && enable.equals("0")) {
                // 不执行action
                return SUCCESS;
            }

            RecordSet rs = new RecordSet();

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

            List<SalaryField> list = new ArrayList<>();
            while (rs.next()) {
                String processField = rs.getString("processfield");
                String salaryName = rs.getString("salaryname");
                String value = fieldMap.get(processField);
                list.add(new SalaryField(processField, salaryName, value));
            }
            Map<String, Object> importDataMap = SalaryEntityUtil.convert2Map(list, SalaryField::getSalaryName, SalaryField::getValue);

            return doSalaryArchiveInit(requestInfo, importDataMap);
        } catch (Exception e) {
            log.error("定薪检查异常", e);
            requestInfo.getRequestManager().setMessage(e.getMessage());
            return FAILURE_AND_CONTINUE;
        }
    }
    
    public String doSalaryArchiveInit(RequestInfo requestInfo, Map<String, Object> importDataMap) {
        User user = new User();
        user.setLoginid("sysadmin");
        user.setUid(1);
        List<Map<String, Object>> importData = new ArrayList<>();
        if(!importDataMap.containsKey("生效日期")){
            importDataMap.put("生效日期", SalaryDateUtil.getFormatDate(new Date()));
        }
        if(!importDataMap.containsKey("最后发薪日期")){
            importDataMap.put("最后发薪日期", "");
        }
        importData.add(importDataMap);

        // 首先判断是否已经存在薪资档案，且薪资档案状态为待定薪
        String taxAgentName = importDataMap.getOrDefault("个税扣缴义务人", "").toString();
        String empIdStr = importDataMap.getOrDefault("员工id", "").toString();
        if (StringUtils.isBlank(taxAgentName)) {
            requestInfo.getRequestManager().setMessage("个税扣缴义务人不能为空");
            return FAILURE_AND_CONTINUE;
        }
        // 获取义务人信息
        List<TaxAgentPO> taxAgentPOS = getTaxAgentService(user).list(TaxAgentQueryParam.builder().name(taxAgentName).build());
        if (CollectionUtils.isEmpty(taxAgentPOS)) {
            requestInfo.getRequestManager().setMessage("个税扣缴义务人不存在");
            return FAILURE_AND_CONTINUE;
        }
        Long taxAgentId = taxAgentPOS.get(0).getId();
        // 获取员工id
        if (NumberUtils.isCreatable(empIdStr)) {
            List<SalaryArchivePO> salaryArchivePOList = getSalaryArchiveService(user).listSome(SalaryArchivePO.builder().taxAgentId(taxAgentId).employeeId(Long.valueOf(empIdStr)).build());
            if (CollectionUtils.isNotEmpty(salaryArchivePOList) && !salaryArchivePOList.get(0).getRunStatus().equals(SalaryArchiveStatusEnum.PENDING.getValue())) {
                // 存在薪资档案，且薪资档案状态不是待定薪，修改状态为待定薪
                salaryArchivePOList.get(0).setRunStatus(SalaryArchiveStatusEnum.PENDING.getValue());
                salaryArchivePOList.get(0).setPayEndDate(null);
                getSalaryArchiveMapper().update(salaryArchivePOList.get(0));
            }
        }

        SalaryArchiveImportActionParam build = SalaryArchiveImportActionParam.builder()
                .importDatas(importData)
                .build();

        //操作人
        Map<String, Object> map = getSalaryArchiveWrapper(user).checkSalaryArchiveInit(build);

        List errorNotice = (List) map.get("errorNotice");
        if (CollectionUtils.isNotEmpty(errorNotice)) {
            log.error("定薪检查存在异常 requestId:{} ,参数:{}, map:{}", requestInfo.getRequestid(), build, map);
            List<Map<String, String>> excelComments = (List<Map<String, String>>) map.get("errorNotice");
            StringBuilder message = new StringBuilder("");
            for (Map<String, String> comments : excelComments) {
                message.append(comments.get("message")).append("\n");
            }
            requestInfo.getRequestManager().setMessage(message.toString());
            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;
        }
    }
}
