package com.engine.attendance.workflow.action;

import com.engine.attendance.enums.AccountingUnitEnum;
import com.engine.attendance.workflow.service.MakeUpClockInService;
import com.engine.attendance.workflow.service.impl.MakeUpClockInServiceImpl;
import com.engine.common.util.CommonUtil;
import com.engine.common.util.DateUtil;
import com.engine.common.util.DbTools;
import com.engine.common.util.ServiceUtil;
import com.google.common.collect.Maps;
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;

/**
 * 撤销出差
 */
@Slf4j
public class RevokeEliminationsAskForLeaveAction implements Action {

    private MakeUpClockInService makeUpClockInService = ServiceUtil.getService(MakeUpClockInServiceImpl.class);

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

            // 流程表单主表数据
            HashMap<String, String> mainTableData = CommonUtil.getMainTableInfo(requestInfo);
            String qjlx = mainTableData.get("qjlx");

            String queryItemsql = "select hsdw,hsl from uf_jcl_kq_kqxm  where id=?";
            Map<String, Object> holidayItem = DbTools.getSqlToMap(queryItemsql, qjlx);

            DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();
            log.info("RevokeLeaveAction 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.info("RevokeLeaveAction key : {}, value : {}",c.getName(), c.getValue());
                            if ("cxsm".equals(name)) {
                                itemMap.put("cxsm", Util.null2String(c.getValue()));
                            }
                            if ("cxlyid".equals(name)) {
                                itemMap.put("cxlyid", Util.null2String(c.getValue()));
                            }
                            if ("cx".equals(name)) {
                                itemMap.put("cx", Util.null2String(c.getValue()));
                            }
                        }
                        log.info("RevokeEliminationsAskForLeaveAction itemMap : [{}]",itemMap);
                        if (Util.null2String(itemMap.get("cx")).equals("1")) {
                            updateList.add(itemMap);
                        }
                    }
                }
            }
            log.info("RevokeLeaveAction updateList : [{}]",updateList);
            if (updateList.size() > 0) {
                updateList.forEach(f -> {
                    if (StringUtils.isNotBlank(f.get("cxlyid"))) {
                        String sql = "update uf_jcl_kq_qjjl_dt1" +" set "+"cxly=0,cxqj=1,cxsm=?,cxid=? where id = ?";
                        log.info("RevokeEliminationsAskForLeaveAction sql : [{}]",sql);
                        DbTools.update(sql, Util.null2String(f.get("cxsm")), requestid, f.get("cxlyid"));
                        log.info("RevokeEliminationsAskForLeaveAction cxsm : {}, requestid : {}, cxlyid : {}",Util.null2String(f.get("cxsm")), requestid, f.get("cxlyid"));
                        updateHoliday(f.get("cxlyid"),holidayItem.get("hsdw").toString());
                    }
                });
            }

        } catch (Exception e) {
            log.info("流程数据报错:RevokeLeaveAction:");
            StringWriter errorsWriter = new StringWriter();
            e.printStackTrace(new PrintWriter(errorsWriter));
            log.info(errorsWriter.toString());
            requestInfo.getRequestManager().setMessageid("11111" + requestInfo.getRequestid() + "22222");
            requestInfo.getRequestManager().setMessagecontent("【更改请假撤销状态action】报错，请联系管理员！");
            return Action.FAILURE_AND_CONTINUE;
        }

        return SUCCESS;


    }

    /**
     * 更新假期余额
     * @param dt1Id
     * @param hsdw
     */
    public void updateHoliday(String dt1Id,String hsdw){
        String sql = "select a.glmxid,a.jqye,sysc,b.qjsc,b.qtj,b.btj from uf_jcl_kq_qjjl_dt2 a left join uf_jcl_kq_qjjl_dt1 b on a.mainid=b.mainid and a.glrq=b.ksrq  where b.id=?";
        List<Map<String,Object>> dataList = DbTools.getSqlToList(sql,dt1Id);
        log.info("updateHoliday dataList :[{}]",dataList);
        Map<String,List<Map<String,Object>>> datagroupbyId = dataList.stream().collect(Collectors.groupingBy(e->e.get("jqye").toString()));
        for(Map.Entry<String,List<Map<String,Object>>> entry: datagroupbyId.entrySet()){
            String jqyeId = entry.getKey();
            List<Map<String,Object>> list = entry.getValue();
            double qjscTotal = list.stream().mapToDouble(e->Double.valueOf(e.get("qjsc").toString())).sum();
            double qtjTotal = list.stream().mapToDouble(e->Double.valueOf(e.get("qtj").toString())).sum();
            double btjTotal = list.stream().mapToDouble(e->Double.valueOf(e.get("qtj").toString())).sum();
            double qjsc = 0;

            if (AccountingUnitEnum.DAY.getKey().equals(hsdw)){
                qjsc = qtjTotal+btjTotal;
            }else if (AccountingUnitEnum.HOUR.getKey().equals(hsdw)){
                qjsc = qjscTotal + (qtjTotal+btjTotal)*8;
            }
            sql = "update uf_jcl_kq_jqye set yxsc=yxsc-"+qjsc+",wxsc=wxsc+"+qjsc+" where id=?";
            log.info("updateHoliday sql : [{}]",sql);
            DbTools.update(sql,jqyeId);
        }

    }
}
