package com.engine.tjbankSocket.impl;

import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.engine.tjbankSocket.SocketExecute;
import com.engine.util.XMLUtils;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.general.StringUtil;
import weaver.general.Util;
import weaver.soa.workflow.request.RequestService;

import java.io.IOException;
import java.util.*;

/**
 * @author 13
 */
public class CWGLSocketExecute extends BaseBean implements SocketExecute {
    @Override
    public String execute(Map<String, String> param) {
        Map<String, String> paramMap = param;
        writeLog("paramMap==="+paramMap);
        String oaTrvlBnsExpnsAcctNo =  Util.null2String(paramMap.get("oaTrvlBnsExpnsAcctNo"));
        String apprvrNo = Util.null2String(paramMap.get("apprvrNo"));
        String apprvrName = Util.null2String(paramMap.get("apprvrName"));
        String flowStatus = Util.null2String(paramMap.get("flowStatus"));
        String sgntrOpn = Util.null2String(paramMap.get("sgntrOpn"));
        sgntrOpn = apprvrName + "(" + apprvrNo + "):" + sgntrOpn;
        Map<String, String> resultMap = null;
        String tableName = "";
        int userid = 0;
        try {
            if(oaTrvlBnsExpnsAcctNo.startsWith("BTSQD")){
                tableName = "formtable_main_295";
                // resultMap = getBeanByOAnum(oaTrvlBnsExpnsAcctNo, "formtable_main_281");
            }else if(oaTrvlBnsExpnsAcctNo.startsWith("FHBTSQD")) {
                tableName = "formtable_main_398";
                // resultMap = getBeanByOAnum(oaTrvlBnsExpnsAcctNo, "");
            }else {
                throw new Exception("未找到编号 '"+oaTrvlBnsExpnsAcctNo+"' 对应的表单");
            };
            resultMap = getBeanByOAnum(oaTrvlBnsExpnsAcctNo, tableName);
        } catch (Exception e) {
            e.printStackTrace();
            return XMLUtils.CW2XML(paramMap, "1", e.getMessage());
        }
        try {
            userid = getHrmidByWorkCode(apprvrNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String id = resultMap.get("id");
        int requestid = Util.getIntValue(resultMap.get("requestid"));
        writeLog("requestid==="+requestid);
        if (requestid == 0) {
            return XMLUtils.CW2XML(paramMap, "1", "流程未找到");
        }
        // if (userid == 0) {
        //     return XMLUtils.CW2XML(paramMap, "1", "人员未找到");
        // }
        RequestService requestService = new RequestService();
        boolean istrue = false;
        if ("0".equals(flowStatus)) {
            sgntrOpn = sgntrOpn + "(驳回)";
            istrue = requestService.nextNodeByReject(requestid, 1, sgntrOpn);
        } else if ("1".equals(flowStatus)) {
            sgntrOpn = sgntrOpn + "(记账前退单)";
            istrue = requestService.nextNodeByReject(requestid, 1, sgntrOpn);
        } else if ("2".equals(flowStatus)) {
            sgntrOpn = sgntrOpn + "(记账后退单)";
            istrue = requestService.nextNodeByReject(requestid, 1, sgntrOpn);
        } else {
            istrue = requestService.nextNodeBySubmit(null, requestid, 1, sgntrOpn);
        }
        writeLog("istrue==="+istrue);
        if (istrue) {
            try {
                updateStatus(requestid, flowStatus,tableName);
                String sqr = getsqrbyBH(oaTrvlBnsExpnsAcctNo, tableName);
                if("3".equals(flowStatus)){
                    sendMsgForSuccess(sqr,oaTrvlBnsExpnsAcctNo,requestid);
                }

            } catch (Exception e) {
                e.printStackTrace();
                return XMLUtils.CW2XML(paramMap, "1", e.getMessage());
            }
            return XMLUtils.CW2XML(paramMap, "0", "");
        } else {
            return XMLUtils.CW2XML(paramMap, "1", "流程提交失败");
        }
    }

    private void sendMsgForSuccess(String userid, String oaTrvlBnsExpnsAcctNo, int requestid) {
        MessageType messageType = MessageType.newInstance(1674); // 消息来源（见文档第四点补充 必填）
        Set<String> userIdList = new HashSet<>(); // 接收人id 必填
        String[] useridArr =  userid.split(",");
        String proplinkUrl = Prop.getPropValue("subsidy_reminder", "linkUrl");
        String proplinkMobileUrl = Prop.getPropValue("subsidy_reminder", "linkMobileUrl");
        for (String s : useridArr) {
            userIdList.add(s);
        }
        String title = "您有新的差旅补助到账,请您查收"; // 标题
        String context = "差补报销("+oaTrvlBnsExpnsAcctNo+")";
        String linkUrl = StringUtil.isEmpty(proplinkUrl) ? "" : proplinkUrl+requestid; // PC端链接
        String linkMobileUrl = StringUtil.isEmpty(proplinkMobileUrl) ? "" :proplinkMobileUrl+requestid; // 移动端链接
        try {
            MessageBean messageBean = Util_Message.createMessage(messageType, userIdList, title, context, linkUrl, linkMobileUrl);
            messageBean.setCreater(1);// 创建人id
            //message.setBizState("0");// 需要修改消息为已处理等状态时传入,表示消息最初状态为待处理
            //messageBean.setTargetId("121|22"); //消息来源code +“|”+业务id需要修改消息为已处理等状态时传入
            Util_Message.store(messageBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateStatus(int requestid, String flowStatus ,String tableName) throws Exception {
        try {
            RecordSet recordSet = new RecordSet();
            recordSet.executeUpdate("update "+tableName+" set cwxtzt = ? where requestId = ?", flowStatus, requestid);
        } catch (Exception e) {
            throw new Exception("更新状态失败");
        }
    }


    public Map<String, String> getBeanByOAnum(String oaTrvlBnsExpnsAcctNo, String tableName) throws Exception {
        RecordSet recordSet = new RecordSet();
        HashMap<String, String> resultMap = new HashMap<>();
        String sql = "select * from " + tableName + " where djbh = ?";
        writeLog("getBeanByOAnumSql"+sql);
        recordSet.executeQuery(sql, oaTrvlBnsExpnsAcctNo);
        if (recordSet.next()) {
            resultMap.put("id", Util.null2String(recordSet.getString("id")));
            resultMap.put("requestid", Util.null2String(recordSet.getString("requestid")));
            return resultMap;
        } else {
            throw new Exception("编号对应单据不存在");
        }
    }

    /**
     * 获取单据的
     * @param oaTrvlBnsExpnsAcctNo
     * @param tableName
     * @return
     * @throws Exception
     */
    public String getsqrbyBH(String oaTrvlBnsExpnsAcctNo, String tableName) throws Exception {
        RecordSet recordSet = new RecordSet();
        HashMap<String, String> resultMap = new HashMap<>();
        String sql = "select jbrxm from " + tableName + " where djbh = ?";
        recordSet.executeQuery(sql, oaTrvlBnsExpnsAcctNo);
        if (recordSet.next()) {

            return Util.null2String(recordSet.getString("jbrxm"));
        } else {
            throw new Exception("编号对应单据不存在");
        }
    }

    public int getHrmidByWorkCode(String workcode) throws Exception {
        RecordSet recordSet = new RecordSet();
        String sql = "select id from HRMRESOURCE where workcode = ?";
        recordSet.executeQuery(sql, workcode);
        if (recordSet.next()) {
            return Util.getIntValue(recordSet.getString("id"));
        } else {
            throw new Exception("审批人不存在");
        }
    }


}
