package com.engine.salary.action;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.siarchives.param.SIArchiveImportParam;
import com.engine.salary.service.SISchemeService;
import com.engine.salary.service.impl.SISchemeServiceImpl;
import com.engine.salary.util.SalaryEntityUtil;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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


    public String getTableName() {
        return tableName;
    }

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

    // 是否执行action的字段, 0代表不执行，其余代表执行
    private String enableField;

    public String getEnableField() {
        return enableField;
    }

    public void setEnableField(String enableField) {
        this.enableField = enableField;
    }

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

            String enable = fieldMap.get(enableField);
            if (StringUtils.isNotBlank(enable) && enable.equals("0")) {
                // 不执行action
                return SUCCESS;
            }
            RecordSet rs = new RecordSet();

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

            List<EditSIArchiveAction.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 EditSIArchiveAction.SalaryField(processField, salaryName, value));
            }
            List<Map<String, Object>> importData = new ArrayList<>();
            importData.add(SalaryEntityUtil.convert2Map(list, EditSIArchiveAction.SalaryField::getSalaryName, EditSIArchiveAction.SalaryField::getValue));
            //福利执行状态
            String runStatus = list.stream().filter(f -> f.salaryName.equals("档案状态")).findFirst().map(EditSIArchiveAction.SalaryField::getValue).orElse("1");

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

            //操作人
            String uid = list.stream().filter(f -> f.salaryName.equals("操作人")).findFirst().map(EditSIArchiveAction.SalaryField::getValue).orElse("1");
            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;
            }
        } 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;
        }
    }
}
