package com.engine.htsc.payment.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.payment.enums.Sequences;
import com.engine.htsc.payment.pojo.AutoRequestParam;
import com.engine.htsc.payment.service.StaffCodService;
import com.engine.htsc.payment.util.BizUtils;
import com.engine.htsc.payment.util.CoWfUtil;
import com.engine.htsc.payment.util.PayUtil;
import com.engine.htsc.payment.util.StaffCodUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.joda.time.DateTime;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.soa.workflow.request.*;

import javax.sound.midi.Sequence;
import java.util.*;
import java.util.stream.Collectors;

public class StaffCodServiceImpl extends Service implements StaffCodService {
  private static final String FAIL = "自动触发工会付款流程失败,error:";
  private static final String SUCCESS = "自动触发工会付款流程成功";

  @Override
  public AutoRequestParam generateAutoRequestParamByStaffCodRid(String rids) throws Exception {
    Assert.notBlank(rids, "触发流程的requestIds为空");
    List<String> ridsList = Arrays.stream(rids.split(",")).collect(Collectors.toList());
    PropBean propBean = new PropBean();
    String creatorUid = propBean.getPropName("StaffCodCreator"); //35201
    String workFlowId = propBean.getPropName("StaffCodWorkFlowId"); //	18523

    //关联流程主表数据,sql获取附件
    String ygwwsq = PayUtil.getTableNameByUnNumber("ygwwsq");
    String sql = "select WM_CONCAT_OLD(FJ) as fjs from "+ygwwsq+" where REQUESTID in ('" + rids.replace(",", "','") + "') order by FJ";
    Map<String, String> mainMap = BizUtils.select2Map(sql);
    String fjs = Util.null2String(mainMap.get("fjs"));

    //生成流程编号,工会付款
    String requestMark = CoWfUtil.getRequestMarkByUnNumber("zbghfk", Sequences.NET_REI_WORKFLOW_SEQ_ZB);

    //main
    Map<String, String> main = new HashMap<>();
    ResourceComInfo rc = new ResourceComInfo();
    DateTime today = new DateTime();
    String szbm = rc.getDepartmentID(creatorUid);
    main.put("NGR", creatorUid);
    main.put("LCBH", requestMark);
    main.put("SZBM", szbm);
    main.put("JJCD", "0");
    main.put("NGSJ", today.toString("yyyy-MM-dd HH:mm"));
    main.put("GLYGWWSQLC", rids);
    main.put("YWHT", "1");
    main.put("JSZFMX", "点我计算");
    main.put("LXFS", rc.getMobile(creatorUid));
    main.put("NGRGH", rc.getWorkcode(creatorUid));
    main.put("FJ", fjs);
    main.put("GGFYQTFY", "1");
    main.put("GLLC", rids);
    main.put("FKLX", "2"); //工会付款付款类型
    main.put("FZZD", "1");
    main.put("FZZD1", "0");

//    新添加bmjb字段
    RecordSet rsbm = new RecordSet();
    String getbmjbSql = "select deptdepth from hrmdepartmentdefined where deptid = '"+szbm+"'";
    rsbm.execute(getbmjbSql);
    if (rsbm.next()){
      main.put("bmjb".toUpperCase(),rsbm.getString("deptdepth"));
    }

    List<LinkedHashMap<String, String>> dt8rows = StaffCodUtil.getDt8s(rids); //明细8汇总一次
    List<LinkedHashMap<String, String>> dt13rows = StaffCodUtil.getDt13s(rids); //明细13汇总一次
    List<Map<String, String>> dt5rows = new ArrayList<>();
    List<Map<String, String>> dt6rows = new ArrayList<>();
    List<Map<String, String>> dt7rows = new ArrayList<>();
    for (String rid : ridsList) {
      dt5rows.addAll(StaffCodUtil.getDt5s(rid));
      dt6rows.addAll(StaffCodUtil.getDt6s(rid));
      dt7rows.addAll(StaffCodUtil.getDt7s(rid));
    }

    AutoRequestParam param = new AutoRequestParam();
    param.setRelateStaffRid(rids);
    param.setCreatorUid(creatorUid);
    param.setWorkflowId(workFlowId);
    param.setIsNextFlow("0");
    param.setRequestName("家庭变故和生病、生育、结婚员工慰问" + today.toString("yyyyMM"));

    main.put("DJZS", String.valueOf(dt5rows.size() + dt6rows.size()));
    param.setMain(main);
    param.setDt5(dt5rows);
    param.setDt6(dt6rows);
    param.setDt7(dt7rows);
    param.setDt8(dt8rows);
    param.setDt13(dt13rows);
    BaseBean baseBean = new BaseBean();
    baseBean.writeLog(String.format("自动触发工会流程, 构造慰问参数:%s", JSONObject.toJSONString(param)));
    return param;
  }

  @Override
  public Map<String, String> autoTriggerLaborUnionPayment(AutoRequestParam param) throws Exception {
    Assert.isTrue(param.isValid(), FAIL + "流程数据缺失," + JSONObject.toJSONString(param));
    RequestInfo requestInfo = new RequestInfo();
    requestInfo.setCreatorid(param.getCreatorUid());
    requestInfo.setWorkflowid(param.getWorkflowId());
    requestInfo.setDescription(param.getRequestName());
    requestInfo.setIsNextFlow(param.getIsNextFlow());

    Map<String, String> main = param.getMain();
    Assert.isTrue(MapUtils.isNotEmpty(main), FAIL + "主表数据为空");

    //主表数据
    MainTableInfo mainTableInfo = new MainTableInfo();
    Property[] propertyArray = new Property[main.size()];
    int p = 0;
    for (Map.Entry<String, String> entry : main.entrySet()) {
      propertyArray[p] = new Property();
      propertyArray[p].setName(Util.null2String(entry.getKey()));
      propertyArray[p].setValue(Util.null2String(entry.getValue()));
      p++;
    }
    mainTableInfo.setProperty(propertyArray);
    requestInfo.setMainTableInfo(mainTableInfo);

    //工会主表名
    String tableName = PayUtil.getTableNameByUnNumber("zbghfk");

    //从表字段
    DetailTableInfo detailTableInfo = new DetailTableInfo();
    //表5
    List<Map<String, String>> dt5 = param.getDt5();
    if (CollectionUtils.isNotEmpty(dt5)) {
      DetailTable detailTable5 = addDtRow(dt5);
      detailTable5.setId("5");
      detailTable5.setTableDBName(tableName + "_dt5");
      detailTableInfo.addDetailTable(detailTable5);
    }
    //表6
    List<Map<String, String>> dt6 = param.getDt6();
    if (CollectionUtils.isNotEmpty(dt6)) {
      DetailTable detailTable6 = addDtRow(dt6);
      detailTable6.setId("6");
      detailTable6.setTableDBName(tableName + "_dt6");
      detailTableInfo.addDetailTable(detailTable6);
    }
    //表7
    List<Map<String, String>> dt7 = param.getDt7();
    if (CollectionUtils.isNotEmpty(dt7)) {
      DetailTable detailTable7 = addDtRow(dt7);
      detailTable7.setId("7");
      detailTable7.setTableDBName(tableName + "_dt7");
      detailTableInfo.addDetailTable(detailTable7);
    }
    //表8
//    List<Map<String, String>> dt8 = param.getDt8();
//    if (CollectionUtils.isNotEmpty(dt8)) {
//      DetailTable detailTable8 = addDtRow(dt8);
//      detailTable8.setId("8");
//      detailTable8.setTableDBName(tableName + "_dt8");
//      detailTableInfo.addDetailTable(detailTable8);
//    }
    //表13
//    List<Map<String, String>> dt13 = param.getDt13();
//    if (CollectionUtils.isNotEmpty(dt13)) {
//      DetailTable detailTable13 = addDtRow(dt13);
//      detailTable13.setId("13");
//      detailTable13.setTableDBName(tableName + "_dt13");
//      detailTableInfo.addDetailTable(detailTable13);
//    }

    requestInfo.setDetailTableInfo(detailTableInfo);
    RequestService service = new RequestService();
    String requestId = service.createRequest(requestInfo);

    //生成requestId后单独插入明细8和明细13的数据
    boolean flag = batchInsertDetails(requestId, tableName, param);

    Map<String, String> map = new HashMap<>();
    if (flag) {
      RecordSet rs = new RecordSet();
      String ridss = param.getMain().getOrDefault("GLLC","");
      String[] ridsList = ridss.split(",");
      String whereSql = "";
      for (int i = 0; i < ridsList.length; i++) {
        if (i!=ridsList.length-1){
          whereSql += "requid = '"+ridsList[i]+"' or ";
        }else {
          whereSql += "requid = '"+ridsList[i]+"'";
        }
      }
      String updateSql = "UPDATE uf_wwsqhz SET FKZT = 1 where " +whereSql;
      new BaseBean().writeLog("即将执行的update代码是："+updateSql);
      System.out.println("---即将执行的update代码是："+updateSql);
      boolean updateResult = rs.executeUpdate(updateSql);
      if (updateResult){
        map.put(param.getRelateStaffRid(), SUCCESS + ", 新建流程id:" + requestId);
      }else {
        throw new Exception(FAIL + ", 付款状态更新失败");
      }
    } else {
      throw new Exception(FAIL + ", 更新明细表失败");
    }
    return map;
  }

  public DetailTable addDtRow(List<Map<String, String>> dt) {
    DetailTable dtRows = new DetailTable();
    if (CollectionUtils.isNotEmpty(dt)) {
      for (Map<String, String> map : dt) {
        Row row = new Row();
        for (String key : map.keySet()) {
          Cell cell = new Cell();
          cell.setName(key);
          cell.setValue(map.get(key));
          row.addCell(cell);
        }
        dtRows.addRow(row);
      }
    }
    return dtRows;
  }

  /**
   * 批量插入流程的明细数据
   *
   * @param requestId 流程rid
   */
  public boolean batchInsertDetails(String requestId, String tableName, AutoRequestParam param) throws Exception {
    RecordSet rs = new RecordSet();
    String sql = String.format("select ID from %s WHERE REQUESTID=?", tableName);
    rs.executeQuery(sql, requestId);
    rs.next();
    String mainId = Util.null2String(rs.getString("ID"));
    List<LinkedHashMap<String, String>> dt8s = param.getDt8();
    if (CollectionUtils.isNotEmpty(dt8s)) {
      List<List> paramList = new ArrayList();
      String insertDt8 = String.format("insert into %s " +
              "(mainid, bhsje, sj, jshjje, sy, fysjcdbm, sl, slz, htbh, fycdbmfzr, cys, mxfzzd, yskm, yskmid, yskz) " +
              "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", tableName + "_dt8");
      for (LinkedHashMap<String, String> dt8 : dt8s) {
        List valueList = new ArrayList();
        valueList.add(mainId);
        for (Map.Entry<String, String> entry : dt8.entrySet()) {
          valueList.add(entry.getValue());
        }
        paramList.add(valueList);
      }
      rs.executeBatchSql(insertDt8, paramList);
    }

    List<LinkedHashMap<String, String>> dt13s = param.getDt13();
    if (CollectionUtil.isNotEmpty(dt13s)) {
      List<List> paramList = new ArrayList();
      String insertDt13 = String.format("insert into %s " +
              "( mainid, ygxm, bm, ss, yxzh, yxzfje, khx, lsxx, bz, khxmc, fycdbm, szjg, yggh) " +
              "values(?,?,?,?,?,?,?,?,?,?,?,?,?)", tableName + "_dt13");
      for (LinkedHashMap<String, String> dt13 : dt13s) {
        List valueList = new ArrayList();
        valueList.add(mainId);
        for (Map.Entry<String, String> entry : dt13.entrySet()) {
          valueList.add(entry.getValue());
        }
        paramList.add(valueList);
      }
      rs.executeBatchSql(insertDt13, paramList);
    }


    return true;

  }

//  public
}
