package com.engine.salary.action;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.siarchives.param.SIArchiveImportParam;
import com.engine.salary.entity.siarchives.po.InsuranceArchivesBaseInfoPO;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.enums.siaccount.EmployeeStatusEnum;
import com.engine.salary.mapper.siarchives.InsuranceBaseInfoMapper;
import com.engine.salary.mapper.taxagent.TaxAgentMapper;
import com.engine.salary.service.SIArchivesService;
import com.engine.salary.service.SISchemeService;
import com.engine.salary.service.impl.SIArchivesServiceImpl;
import com.engine.salary.service.impl.SISchemeServiceImpl;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.db.MapperProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
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;

/**
 * @Author: sy
 * @Description: 编辑并减员福利档案
 * @Date: 2023/9/8
 **/
@Slf4j
public class EditToStopSIArchiveAction implements Action {
    private SISchemeService getSISchemeService(User user) {
        return ServiceUtil.getService(SISchemeServiceImpl.class,user);
    }

    private InsuranceBaseInfoMapper getInsuranceBaseInfoMapper() {
        return MapperProxyFactory.getProxy(InsuranceBaseInfoMapper.class);
    }

    private SIArchivesService getSIArchivesService(User user) {
        return ServiceUtil.getService(SIArchivesServiceImpl.class,user);
    }

    private TaxAgentMapper getTaxAgentMapper() {
        return MapperProxyFactory.getProxy(TaxAgentMapper.class);
    }

    private String tableName;


    public String getTableName() {
        return tableName;
    }

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

    @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())));

            RecordSet rs = new RecordSet();

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

            List<EditToStopSIArchiveAction.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 EditToStopSIArchiveAction.SalaryField(processField, salaryName, value));
            }
            List<Map<String, Object>> importData = new ArrayList<>();
            importData.add(SalaryEntityUtil.convert2Map(list, EditToStopSIArchiveAction.SalaryField::getSalaryName, EditToStopSIArchiveAction.SalaryField::getValue));
            //福利执行状态
            String runStatus = EmployeeStatusEnum.PAYING.getValue();

            SIArchiveImportParam build = SIArchiveImportParam.builder()
                    .importDatas(importData)
                    .runStatus(runStatus)
                    .build();

            //操作人
            String uid = list.stream().filter(f -> f.salaryName.equals("操作人")).findFirst().map(EditToStopSIArchiveAction.SalaryField::getValue).orElse("1");
            User user = new User(Integer.parseInt(uid));
            //更新/新建档案数据
            Map<String, Object> map = getSISchemeService(new User(Integer.parseInt(uid))).addSIArchive(build);

            List errorNotice = (List) map.get("errorData");
            if (CollectionUtils.isNotEmpty(errorNotice)) {
                log.error("福利档案编辑并减员存在异常 requestId:{} ,参数:{}, map:{}", requestInfo.getRequestid(), build, map);
                List<Map<String, String>> excelComments = (List<Map<String, String>>) map.get("errorData");
                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;
            }
            //刷新福利档案状态
            getSIArchivesService(user).handleStayDelData(Integer.parseInt(uid));
            //减员
            String taxAgentName = importData.get(0).get("个税扣缴义务人").toString();
            List<TaxAgentPO> taxAgentPOS = getTaxAgentMapper().listByName(taxAgentName);
            if(CollectionUtils.isEmpty(taxAgentPOS)){
                requestInfo.getRequestManager().setMessage("个税扣缴义务人不存在！");
                return FAILURE_AND_CONTINUE;
            }
            Long taxAgentId = Long.valueOf(taxAgentPOS.get(0).getId());
            Long employeeId = Long.valueOf(list.stream().filter(f -> f.salaryName.equals("员工id")).findFirst().map(EditToStopSIArchiveAction.SalaryField::getValue).orElse("-1"));

            // 获取福利档案
            InsuranceArchivesBaseInfoPO insuranceArchivesBaseInfoPO = getInsuranceBaseInfoMapper().getOneByEmployeeIdAndPayOrg(taxAgentId, employeeId);
            if(insuranceArchivesBaseInfoPO == null){
                requestInfo.getRequestManager().setMessage("该个税扣缴义务人下该员工不存在福利档案，请检查后重试！");
                return FAILURE_AND_CONTINUE;
            } else if(!insuranceArchivesBaseInfoPO.getRunStatus().equals(EmployeeStatusEnum.STAY_DEL.getValue())){
                requestInfo.getRequestManager().setMessage("该个税扣缴义务人下该员工的福利档案状态不是待减员，无法进行减员操作，请检查后重试！");
                return FAILURE_AND_CONTINUE;
            }
            //减员
            Map<String, Object> resultMap = getSIArchivesService(user).stayDelToStop(Collections.singletonList(insuranceArchivesBaseInfoPO.getId()));
            if (resultMap.get("type").toString().equals("fail")) {
                requestInfo.getRequestManager().setMessage(resultMap.get("msg").toString());
                return FAILURE_AND_CONTINUE;
            }


        } 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;
        }
    }
}
