package com.engine.jucailinkq.attendance.workflow.action;

import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DbTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Cell;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: sy
 * @Description: 津贴确认流程，归档节点更新津贴状态
 * @Date: 2024/7/25
 **/
@Slf4j
public class AllowanceConfirmArchivingAction implements Action {

    @Override
    public String execute(RequestInfo requestInfo) {
        log.debug("AllowanceConfirmArchivingAction,do action on request:" + requestInfo.getRequestid());
        String requestid = requestInfo.getRequestid();
        try {

            // 流程表单主表数据
            HashMap<String, String> mainTableData = CommonUtil.getMainTableInfo(requestInfo);
            String qrr = mainTableData.get("xjr");
            List<String> jtIdList = new ArrayList<>();

            DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();
            log.debug("AllowanceConfirmArchivingAction detailTable : [{}], length : {}", Arrays.toString(detailTable), detailTable.length);
            List<Map<String, String>> updateList = new ArrayList<>();
            if (detailTable.length > 0) {
                for (DetailTable dt : detailTable) {
                    //明细表
                    Row[] s = dt.getRow();
                    for (Row r : s) {
                        //行
                        Cell[] h = r.getCell();
                        Map<String, String> itemMap = new HashMap<>();
                        for (Cell c : h) {
                            //列
                            String name = Util.null2String(c.getName());
                            log.debug("AllowanceConfirmArchivingAction key : {}, value : {}",c.getName(), c.getValue());
                            if ("zt".equals(name)) {
                                itemMap.put("zt", Util.null2String(c.getValue()));
                            }
                            if ("jtid".equals(name)) {
                                itemMap.put("jtid", Util.null2String(c.getValue()));
                                jtIdList.add(Util.null2String(c.getValue()));
                            }
                            if ("sm".equals(name)) {
                                itemMap.put("sm", Util.null2String(c.getValue()));
                            }
                            if ("rq".equals(name)) {
                                itemMap.put("rq", Util.null2String(c.getValue()));
                            }
                        }
                        log.debug("AllowanceConfirmAction itemMap : [{}]",itemMap);
                        updateList.add(itemMap);
                    }
                }
            }
            log.debug("AllowanceConfirmArchivingAction updateList : [{}]",updateList);

            //遍历比较哪些津贴数据的状态改变了，并将状态发生改变的津贴数据认定为要更新出勤结果数据状态的津贴数据
            String jtSql = "select id, zt from uf_jcl_kq_cqjt where id in (" + String.join(",", jtIdList) + ")";
            List<Map<String, Object>> jtDataList = DbTools.getSqlToList(jtSql);
            Map<String, String> jtStatusMap = jtDataList.stream().collect(Collectors.toMap(e->Util.null2String(e.get("id")), e->Util.null2String(e.get("zt"))));
            List<Map<String, String>> empDateList = new ArrayList<>();

            if (updateList.size() > 0) {
                updateList.forEach(f -> {
                    if (StringUtils.isNotBlank(f.get("jtid"))) {
                        String sql = "update uf_jcl_kq_cqjt" +" set "+"zt=?,bz=? where id = ?";
                        log.debug("AllowanceConfirmArchivingAction sql : [{}]",sql);
                        DbTools.update(sql, Util.null2String(f.get("zt")), Util.null2String(f.get("sm")), f.get("jtid"));
                        log.debug("AllowanceConfirmArchivingAction zt : {}, bz : {}, jtid : {}",Util.null2String(f.get("zt")), Util.null2String(f.get("sm")), f.get("jtid"));
                        //收集需要更改出勤结果数据状态的人员、日期信息
                        if (!jtStatusMap.getOrDefault(f.get("jtid"), "").equals(Util.null2String(f.get("zt")))) {
                            Map<String, String> empDateItem = new HashMap<>();
                            empDateItem.put("empId", qrr);
                            empDateItem.put("cqDate", Util.null2String(f.get("rq")));
                            empDateList.add(empDateItem);
                        }
                    }
                });
                //更新出勤结果中的数据状态
                String sjztUpdateResult = CommonUtil.updateAttendanceResultInfoStatus(empDateList, "0");
                if (!"".equals(sjztUpdateResult)) {
                    log.error("更新出勤结果中的数据状态失败:" + sjztUpdateResult);
                    requestInfo.getRequestManager().setMessageid("11111" + requestInfo.getRequestid() + "22222");
                    requestInfo.getRequestManager().setMessagecontent("更新出勤结果中的数据状态失败:" + sjztUpdateResult);
                    return Action.FAILURE_AND_CONTINUE;
                }

            }

        } catch (Exception e) {
            log.debug("流程数据报错:AllowanceConfirmArchivingAction:");
            StringWriter errorsWriter = new StringWriter();
            e.printStackTrace(new PrintWriter(errorsWriter));
            log.debug(errorsWriter.toString());
            requestInfo.getRequestManager().setMessageid("11111" + requestInfo.getRequestid() + "22222");
            requestInfo.getRequestManager().setMessagecontent("【津贴确认归档action】报错，请联系管理员！");
            return Action.FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }
}
