package com.engine.salary.action;

import com.engine.common.util.ServiceUtil;
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.impl.SIArchivesServiceImpl;
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: 福利档案增员action
 * @Date: 2023/8/22
 **/
@Slf4j
public class StayAddToPaySIArchiveAction implements Action {

    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<StayAddToPaySIArchiveAction.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 StayAddToPaySIArchiveAction.SalaryField(processField, salaryName, value));
            }
            // 流程数据
            Map<String, Object> importDataMap = SalaryEntityUtil.convert2Map(list, StayAddToPaySIArchiveAction.SalaryField::getSalaryName, StayAddToPaySIArchiveAction.SalaryField::getValue);
            String taxAgentName = importDataMap.getOrDefault("个税扣缴义务人", "").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(importDataMap.getOrDefault("员工id", "-1").toString());

            //操作人
            String uid = importDataMap.getOrDefault("操作人","1").toString();
            User user = new User(Integer.parseInt(uid));
            // 获取福利档案基础信息
            InsuranceArchivesBaseInfoPO insuranceArchivesBaseInfoPO = getInsuranceBaseInfoMapper().getOneByEmployeeIdAndPayOrg(taxAgentId, employeeId);
            if(insuranceArchivesBaseInfoPO == null){
                requestInfo.getRequestManager().setMessage("该个税扣缴义务人下该员工不存在福利档案，请检查后重试！");
                return FAILURE_AND_CONTINUE;
            } else if(!insuranceArchivesBaseInfoPO.getRunStatus().equals(EmployeeStatusEnum.STAY_ADD.getValue())){
                requestInfo.getRequestManager().setMessage("该个税扣缴义务人下该员工的福利档案状态不是待增员，无法进行增员操作，请检查后重试！");
                return FAILURE_AND_CONTINUE;
            }
            //增员
            Map<String, Object> resultMap = getSIArchivesService(user).stayAddToPay(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;
        }
    }
}
