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.TaxAgentManageRangeSaveParam;
import com.engine.salary.entity.taxagent.param.TaxAgentQueryParam;
import com.engine.salary.entity.taxagent.param.TaxAgentRangeSaveParam;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.enums.salaryarchive.SalaryArchiveStatusEnum;
import com.engine.salary.enums.salarysob.TargetTypeEnum;
import com.engine.salary.mapper.archive.SalaryArchiveMapper;
import com.engine.salary.service.SalaryArchiveService;
import com.engine.salary.service.TaxAgentManageRangeService;
import com.engine.salary.service.TaxAgentService;
import com.engine.salary.service.impl.SalaryArchiveServiceImpl;
import com.engine.salary.service.impl.TaxAgentManageRangeServiceImpl;
import com.engine.salary.service.impl.TaxAgentServiceImpl;
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 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 RehireAction implements Action {


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

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

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

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

    private TaxAgentManageRangeService getTaxAgentManageRangeService(User user) {
        return ServiceUtil.getService(TaxAgentManageRangeServiceImpl.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 {
            User user = new User(1);
            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<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, String> salaryFieldMap = SalaryEntityUtil.convert2Map(list, SalaryField::getSalaryName, SalaryField::getValue);
            String taxAgentName = salaryFieldMap.get("个税扣缴义务人");
            String empIdStr = salaryFieldMap.get("员工id");
            if (StringUtils.isBlank(taxAgentName) || StringUtils.isBlank(empIdStr)) {
                requestInfo.getRequestManager().setMessage("个税扣缴义务人、或员工id不能为空");
                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();
            Long employeeId = Long.valueOf(empIdStr);
            List<SalaryArchivePO> salaryArchivePOS = getSalaryArchiveService(user).listSome(SalaryArchivePO.builder().taxAgentId(taxAgentId).employeeId(employeeId).build());
            if (CollectionUtils.isEmpty(salaryArchivePOS)){
                requestInfo.getRequestManager().setMessage("该个税扣缴义务人下，该员工不存在薪资档案！");
                return FAILURE_AND_CONTINUE;
            } else if (salaryArchivePOS.get(0).getRunStatus().equals(SalaryArchiveStatusEnum.STOP_FROM_PENDING.getValue())) {
                requestInfo.getRequestManager().setMessage("该个税扣缴义务人下，该员工没有发过薪。需取消停薪后，申请定薪流程！");
                return FAILURE_AND_CONTINUE;
            }

            if (salaryArchivePOS.get(0).getRunStatus().equals(SalaryArchiveStatusEnum.STOP_FROM_SUSPEND.getValue())) {
                // 停薪来自待停薪 1、取消停薪
                getSalaryArchiveWrapper(user).cancelStop(Collections.singletonList(salaryArchivePOS.get(0).getId()));
            }
            if (salaryArchivePOS.get(0).getRunStatus().equals(SalaryArchiveStatusEnum.STOP_FROM_SUSPEND.getValue()) || salaryArchivePOS.get(0).getRunStatus().equals(SalaryArchiveStatusEnum.SUSPEND.getValue())) {
                // 1、如果不在人员范围内则把他加入义务人的人员范围，2、删除待办
                addTaxAgentRangeIfNotExist(taxAgentId, employeeId, user);
                getSalaryArchiveWrapper(user).deleteSuspendTodo(Collections.singletonList(salaryArchivePOS.get(0).getId()));
            }

            // 调薪
            List<Map<String, Object>> importData = new ArrayList<>();
            importData.add(SalaryEntityUtil.convert2Map(list, SalaryField::getSalaryName, SalaryField::getValue));

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

            //操作人
            String uid = list.stream().filter(f -> f.salaryName.equals("操作人")).findFirst().map(RehireAction.SalaryField::getValue).orElse("1");
            Map<String, Object> map = getSalaryArchiveWrapper(new User(Integer.parseInt(uid))).adjustmentSalaryArchive(build);

            List errorNotice = (List) map.get("errorNotice");
            if (CollectionUtils.isNotEmpty(errorNotice)) {
                // 回滚档案状态
                getSalaryArchiveMapper().update(salaryArchivePOS.get(0));
                log.error("调薪存在异常 requestId:{}  map:{}", requestInfo.getRequestid(), 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;
            }
        } catch (Exception e) {
            log.error("返聘调薪异常", e);
            requestInfo.getRequestManager().setMessage(e.getMessage());
            return FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }




    private void addTaxAgentRangeIfNotExist(Long taxAgentId, Long employeeId, User user){
        // 获取该义务人下人员范围
        Collection<Long> empIds = getTaxAgentService(user).listEmployeeIdsInTaxAgent(taxAgentId);
        if (!empIds.contains(employeeId)) {
            //将人员添加进个税扣缴义务人中
            TaxAgentManageRangeSaveParam.TaxAgentSubAdminRangeTargetParam taxAgentSubAdminRangeTargetParam = new TaxAgentManageRangeSaveParam.TaxAgentSubAdminRangeTargetParam();
            taxAgentSubAdminRangeTargetParam.setTargetId(employeeId);
            taxAgentSubAdminRangeTargetParam.setTargetType(TargetTypeEnum.EMPLOYEE);

            TaxAgentRangeSaveParam taxAgentRangeSaveParam = new TaxAgentRangeSaveParam();
            taxAgentRangeSaveParam.setTaxAgentId(taxAgentId);
            taxAgentRangeSaveParam.setIncludeType(1);
            taxAgentRangeSaveParam.setEmployeeStatus(Arrays.asList("0", "1", "2", "3", "4", "5", "6"));
            taxAgentRangeSaveParam.setTargetParams(Collections.singletonList(taxAgentSubAdminRangeTargetParam));
            taxAgentRangeSaveParam.setSync(true);
            getTaxAgentManageRangeService(user).save(taxAgentRangeSaveParam);
        }
    }


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