package com.engine.salary.action;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.salaryarchive.po.SalaryArchivePO;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.mapper.taxagent.TaxAgentMapper;
import com.engine.salary.service.SalaryArchiveService;
import com.engine.salary.service.impl.SalaryArchiveServiceImpl;
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 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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Harryxzy
 * @ClassName stopSalaryAction
 * @date 2023/06/15 9:17
 * @description 校验停薪参数
 */
@Slf4j
public class CheckStopSalaryAction implements Action {

    private SalaryArchiveService getSalaryArchiveService(User user) {
        return ServiceUtil.getService(SalaryArchiveServiceImpl.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<CheckStopSalaryAction.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 CheckStopSalaryAction.SalaryField(processField, salaryName, value));
            }
            // 流程数据
            Map<String, Object> importDataMap = SalaryEntityUtil.convert2Map(list, CheckStopSalaryAction.SalaryField::getSalaryName, CheckStopSalaryAction.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());
            if( importDataMap.get("最后发薪日期") == null || StringUtils.isBlank(importDataMap.get("最后发薪日期").toString())){
                requestInfo.getRequestManager().setMessage("缺少最后发薪日期字段！");
                return FAILURE_AND_CONTINUE;
            }else if(SalaryDateUtil.stringToDate(importDataMap.get("最后发薪日期").toString()) == null){
                requestInfo.getRequestManager().setMessage("最后发薪日期格式错误，格式为yyyy-MM-dd");
                return FAILURE_AND_CONTINUE;
            }

            //操作人
            String uid = importDataMap.getOrDefault("操作人","1").toString();
            User user = new User(Integer.parseInt(uid));
            // 获取薪资档案
            List<SalaryArchivePO> salaryArchiveList = getSalaryArchiveService(user).listSome(SalaryArchivePO.builder().taxAgentId(taxAgentId).employeeId(employeeId).deleteType(NumberUtils.INTEGER_ZERO).build());
            if(CollectionUtils.isEmpty(salaryArchiveList)){
                requestInfo.getRequestManager().setMessage("该个税扣缴义务人下该员工不存在薪资档案，请检查后重试！");
                return FAILURE_AND_CONTINUE;
            }
            if(salaryArchiveList.size() > 1){
                requestInfo.getRequestManager().setMessage("该个税扣缴义务人下该员工存在多条薪资档案记录，请检查后重试！");
                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;
        }
    }
}
