package com.engine.salary.action;

import cn.hutool.core.util.StrUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.mapper.taxagent.TaxAgentMapper;
import com.engine.salary.service.SIArchivesService;
import com.engine.salary.service.impl.SIArchivesServiceImpl;
import com.engine.salary.util.SalaryDateUtil;
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: 2024/1/29
 **/
@Slf4j
public class CopyToPaySIArchiveAction implements Action {

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

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

    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<CopyToPaySIArchiveAction.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 CopyToPaySIArchiveAction.SalaryField(processField, salaryName, value));
        }
        List<Map<String, Object>> importData = new ArrayList<>();
        importData.add(SalaryEntityUtil.convert2Map(list, CopyToPaySIArchiveAction.SalaryField::getSalaryName, CopyToPaySIArchiveAction.SalaryField::getValue));
        //操作人
        String uid = list.stream().filter(f -> f.salaryName.equals("操作人")).findFirst().map(CopyToPaySIArchiveAction.SalaryField::getValue).orElse("1");
        //增员
        String toCopyTaxAgentName = importData.get(0).get("待复制个税扣缴义务人").toString();
        String toUpdateTaxAgentName = importData.get(0).get("待更新个税扣缴义务人").toString();
        String payStartYearMonth = importData.get(0).getOrDefault("起始缴纳月", "").toString();
        if (StrUtil.isNotBlank(payStartYearMonth) && !SalaryDateUtil.checkYearMonth(payStartYearMonth)) {
            requestInfo.getRequestManager().setMessage("起始缴纳月格式有误，正确格式示例为'2021-01'");
            return FAILURE_AND_CONTINUE;
        }

        List<TaxAgentPO> toCopyTaxAgentPOS = getTaxAgentMapper().listByName(toCopyTaxAgentName);
        List<TaxAgentPO> toUpdateTaxAgentPOS = getTaxAgentMapper().listByName(toUpdateTaxAgentName);
        if(CollectionUtils.isEmpty(toCopyTaxAgentPOS)){
            requestInfo.getRequestManager().setMessage("待复制个税扣缴义务人不存在！");
            return FAILURE_AND_CONTINUE;
        }
        if(CollectionUtils.isEmpty(toUpdateTaxAgentPOS)){
            requestInfo.getRequestManager().setMessage("待更新个税扣缴义务人不存在！");
            return FAILURE_AND_CONTINUE;
        }
        Long toCopyTaxAgentId = toCopyTaxAgentPOS.get(0).getId();
        Long toUpdateTaxAgentId = toUpdateTaxAgentPOS.get(0).getId();
        Long employeeId = Long.valueOf(list.stream().filter(f -> "员工id".equals(f.salaryName)).findFirst().map(CopyToPaySIArchiveAction.SalaryField::getValue).orElse("-1"));
        User user = new User(Integer.parseInt(uid));
        user.setLanguage(7);
        //拷贝福利档案并置为在缴
        Map<String, Object> resultMap = getSIArchivesService(user).copyToPay(toCopyTaxAgentId, toUpdateTaxAgentId, employeeId, payStartYearMonth);
        if (!"success".equals(resultMap.get("type").toString())) {
            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;
        }
    }
}
