console.log("户表失电嘉峪关进入自动派单==")
let a = JSON.parse(localStorage.getItem("markYXObj"))
let loginUserInfo = JSON.parse(a.sessionStorage.loginUserInfo)
let tokens = JSON.parse(localStorage["markYXObj"])?.sessionStorage?.token;
var HBSD = [];
var hbsdList = [];
var hbsdClassList = [];
var consName = null;
let tel = []
let ecssMgtOrgCode = ''
let objData = {
    time: mac.moment().format("YYYY-MM-DD HH:mm:ss"),
    type: "户表失电-嘉峪关",
    pending: 0,
    pendingList: "",
    audit: 0,
    processed: 0
};
let successList = [];
let flag = false;
let callbackName1 = "callBack_hubiaoshidianjiayuguanpaidan01";
//将同一个配变（eqPsrName）下的工单合并一块
obj.pendingList.filter((x) => HBSD.findIndex((y) => y.id == x.eventId) == -1).forEach((x) => {
    let index = hbsdList.findIndex((y) => y.eqPsrName == x.eqPsrName);
    if (index == -1) {
        hbsdList.push({
            eqPsrName: x.eqPsrName,
            eventId: x.eventId,
            obj: x,
            gdbh: "",
        });
    } else {
        hbsdList[index].eventId += "," + x.eventId;
        // hbsdList 是最后整合出来需要派发的工单
    }
    HBSD.push({ id: x.eventId });
});
// 查询大四区班组
if (hbsdList.length > 0) {
    mac.localHostAxjos({
        url: "http://localhost:13313/MonitorServices/getClassList",
        method: "POST",
        data: JSON.stringify({ type: objData.type }),
    }).then((res) => {
        //括号里的res是服务器返回的数据
        if (res.status == 200) {
            res.data.forEach((item) => {
                let arr = [];
                if (item.scope != "") {
                    item.scope = item.scope.replace(/\s*/g, "");
                    arr.push(item.scope.split("、"));
                    item.scope = [].concat.apply([], arr);
                } else {
                    item.scope = [];
                }
            });
            hbsdClassList = res.data;
            console.log(hbsdClassList);
            getTeamData(hbsdList)
        }
    });
}

// 拿着大四区工单中的用户编号去营销系统查询，查到哪个班组就给哪个班组派发
function getTeamData(hbsdList) {
    console.log(hbsdList)
    const requestParam1 = {
        mgtOrgCode: loginUserInfo.orgNo,
        mgtOrgCodeList: ['62411', '624110105', '624110106', '6241102', '624110101', '6241101', '624110102', '624110201'],
        mgtOrgName: "国网嘉峪关供电公司",
        orgFlag: true,
        pageNo: 1,
        pageSize: 10,
        searchMode: "all",
        someLink: hbsdList[0].obj.consNo
    }
    BrowserAction(
        'sgBrowerserJsAjax2',
        "window.callbackName_yx360_hbsd",
        "http://yx.gs.sgcc.com.cn",
        `http://yxgateway.gs.sgcc.com.cn/emss-custmgtf-custview-front//member/custElecEP/queryEleCust`,
        "POST",
        `Content-Type:application/json;auth_token:${tokens}`,
        window.encrypt_old(requestParam1)
    )
    window['callbackName_yx360_hbsd'] = (targeturl, actionurl, responseTxt) => {
        try {
            const resData = decodeURI(responseTxt).replace(/'/g, '"').replace("}/", "}");
            let jsonData = resData.slice(0, resData.lastIndexOf("]") + 1);
            jsonData += "}";
            let res = eval("(" + jsonData + ")");
            if (res.code == "00000") {
                let data = res.data;
                if (data.length > 0) {
                    //  624110102一班 624110106二班 624110105城郊
                    ecssMgtOrgCode = data[0].eccs[0].mgtOrgCode;
                    getgdbh();
                } else {
                    setTimeout(() => {
                        let audioText = `户号${hbsdList[0].obj.consNo}在营销系统中未查到相关信息，请手动派发相关工单！`;
                        audioFC(audioText);
                    }, 6000);
                }
            }
        } catch (err) {
        }
    };
}

function getgdbh() {
    let callbackName = "callBack_hubiaoshidianjiayuguanpaidan";
    // 派单前获取工单编号，用来调接口时作为参数传递
    window[callbackName] = function (targeturl, actionurl, responseTxt) {
        try {
            const resData = JSON.parse(responseTxt
                .replace(/%7B/g, '{')
                .replace(/%27/g, "'")
                .replace(/%7D/g, "}")
                .replace(/'/g, '"')
                .replace("}/", "}")
            );
            if (resData.code == 0) {
                if (hbsdList.length > 0) {
                    hbsdList[0].gdbh = resData.gdbh;
                }
                // 自动派单接口
                zdpdFc();
            }
        } catch (x) {
            setTimeout(() => {
                let audioText = "户表失电工单编号获取异常，请手动派单";
                audioFC(audioText)
            }, 6000);
            let type = "户表失电-嘉峪关";
            let orderID = "";
            let time = mac.moment().format("YYYY-MM-DD HH:mm:ss");
            let name = "";
            let state = "工单编号获取异常" + x;
            mac.localHostAxjos({
                url: "http://localhost:13313/MonitorServices/setDisposeLog",
                method: "POST",
                data: JSON.stringify({ type, orderID, name, time, state }), //必须是字符串格式
            }).then(re => {
                if (re.status == 200) {
                    mac.exeTQueue();
                }
            })
        }
    };
    BrowserAction(
        'sgBrowerserJsAjax2',
        "window." + callbackName,
        `http://21.77.244.194:18890/#/webview/1543953229739896`,
        `http://21.77.244.194:18890/gdgl/zdfw/tgforderzdfw/gdbh`,
        "GET",
        `Content-Type:application/json;userId:${_this.userID};Access-Control-Allow-Credentials:true;Access-Control-Allow-Methods: GET, POST, OPTIONS,PUT,DELETE,OPTION;Access-Control-Allow-Origin:*`,
        ""
    )
}
// 派单接口
function zdpdFc() {
    window[callbackName1] = function (targeturl, actionurl, responseTxt) {
        try {
            const resData = JSON.parse(responseTxt.replace(/%7B/g, '{').replace(/%27/g, "'").replace(/%7D/g, "}").replace(/'/g, '"').replace("}/", "}"));
            if (resData.code == 0) {
                setTimeout(() => {
                    let audioText = "户表失电工单自动派单成功";
                    audioFC(audioText)
                }, 6000);
                // let type = "户表失电";
                // let orderID = JSON.stringify(HBSD);
                // let time = mac.moment().format("YYYY-MM-DD HH:mm:ss");
                // let name = consName;
                // let state = "成功";
                //   //  i国网
                //   const request = {
                //     phoneList: [].concat.apply([], tel),
                //     content: "【业数融合一平台】您有户表失电工单，请及时处理！", //短信内容
                //   };
                //   if (request.phoneList.length > 0) {
                //     msgFC(request)
                //   }
                //   // 呼叫接口
                //   setTimeout(() => {
                //     const params = {
                //       taskName: "户表失电",
                //       phone: [].concat.apply([], tel),
                //       content: "您有户表失电工单，请尽快接单处理",
                //       name: "户表失电",
                //     };
                //     if (params.phone.length > 0) {
                //       mac.callOutLogin(params);
                //     }
                //   }, 1000);
                let type = "户表失电-嘉峪关";
                let orderID = JSON.stringify(successList);
                let time = mac.moment().format("YYYY-MM-DD HH:mm:ss");
                let name = consName;
                let state = '成功';
                mac.localHostAxjos({
                    url: "http://localhost:13313/MonitorServices/setDisposeLog",
                    method: "POST",
                    data: JSON.stringify({ type, orderID, name, time, state, }), //必须是字符串格式
                }).then(re => {
                    if (re.status == 200) {
                        mac.exeTQueue();
                    }
                })
            } else {
                let type = "户表失电-嘉峪关";
                setTimeout(() => {
                    let audioText = "户表失电工单自动派单失败，请及时处理"
                    audioFC(audioText)
                }, 6000);
                let orderID = JSON.stringify(successList);
                let time = mac.moment().format("YYYY-MM-DD HH:mm:ss");
                let name = consName;
                let state = "失败";
                mac.localHostAxjos({
                    url: "http://localhost:13313/MonitorServices/setDisposeLog",
                    method: "POST",
                    data: JSON.stringify({ type, orderID, name, time, state, }), //必须是字符串格式
                }).then(re => {
                    if (re.status == 200) {
                        mac.exeTQueue();
                    }
                })
            }
        } catch (x) {
            setTimeout(() => {
                let audioText = "户表失电工单自动派单异常，请及时处理";
                audioFC(audioText)
            }, 6000);
            let type = "户表失电-嘉峪关";
            let orderID = JSON.stringify(successList);
            let time = mac.moment().format("YYYY-MM-DD HH:mm:ss");
            let name = consName;
            let state = "异常" + x;
            mac.localHostAxjos({
                url: "http://localhost:13313/MonitorServices/setDisposeLog",
                method: "POST",
                data: JSON.stringify({ type, orderID, name, time, state, }), //必须是字符串格式
            }).then(re => {
                if (re.status == 200) {
                    mac.exeTQueue();
                }
            })
        }
    };
    if (hbsdList.length > 0) {
        consName = hbsdList[0].obj.consName;
        let t = mac.moment().format("YYYY-MM-DD") + " " + "23:00:00";
        // 区县级参数
        var requestParam = {
            comment: "",
            processBusinessKey: hbsdList[0].gdbh, //工单编号id
            processDefKey: "gdfw_zdfwgd_202305", //固定
            starter: _this.userID, //登录账号
            variables: {
                data: {
                    address: hbsdList[0].obj.consAddr, //联系地址
                    content: "【自动派单】单户失电", //受理内容
                    eventId: hbsdList[0].eventId, //每一项的eventId，如有多项用，隔开
                    eventType: "01",
                    fdly: "05", //复电来源固定
                    flag: "01",
                    gdbh: hbsdList[0].gdbh, //工单编号
                    hfbz: "01", // 回复标志固定
                    mobile: hbsdList[0].obj.phoneNum, //联系电话
                    slyj: "请及时处理", //受理意见
                    yhbh: hbsdList[0].obj.consNo, //用户编号
                    yhmc: hbsdList[0].obj.consName, //用户名称
                    yqfksj: t, //要求反馈时间
                    ywlb: "07", //业务类别 大概率固定
                },
                maintGroup: "", //班组code
                maintGroupName: "", //班组名称
                maintOrg: "", //接单单位Code
                maintOrgName: "", //接单单位
                personType: "", //班组
                receivePerson: "", //接单人工号
                receivePersonName: "", //接单人
                receiveType: true, //是否班组接单
                sendType: "city",
            },
        };

        // var week = "日一二三四五六".charAt(new Date().getDay());
        function getTodayChineseWeekday() {
            const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            const today = new Date();
            return weekdays[today.getDay()]
        }
        function isTodayIn(weekdayStr) {
            const today = getTodayChineseWeekday();
            const allowerDays = weekdayStr.split(',').map(day => day.trim());
            return allowerDays.includes(today)
        }
        // 时间比对，范围：08:30 ~ 17:50 范围判断方法
        function isInTimeRange() {
            // 获取当前时间的HHmm格式（0830、1750）
            const currentTime = mac.moment().format("HHmm");
            // 定义边界范围
            const startTime = 830;
            const endTime = 1750;
            // 核心逻辑判断，当前时间在08:30 ~ 17:50 范围
            const currentNum = Number(currentTime);
            return currentNum >= startTime && currentNum <= endTime;
        }

        let assigned = false; // 标记是否已成功分配到班组
        for (const item of hbsdClassList) {
            // 判断是否满足派单条件：设置接单 + 今天在周期 + 时间在工作时段
            if (item.isSetcTime === '1' && isTodayIn(item.cTime) && isInTimeRange()) {
                if (ecssMgtOrgCode === '624110102' && item.orgId == "5c3512baaafd4d86b2683f49001b755d") {
                    // 一班
                    requestParam.variables.maintGroup = item.orgId;
                    requestParam.variables.maintGroupName = item.cName;
                    requestParam.variables.maintOrg = "77e0c17eac9a405492c393e70ffd8479";
                    requestParam.variables.maintOrgName = "市场部";
                    requestParam.variables.personType = "member";
                    requestParam.variables.receivePerson = item.pCode;
                    requestParam.variables.receivePersonName = item.pName;
                    console.log('进入一班===');
                } else if (ecssMgtOrgCode === '624110106' && item.orgId == "e69661b8bc7945df838d9690ea126e6f") {
                    // 二班
                    requestParam.variables.maintGroup = item.orgId;
                    requestParam.variables.maintGroupName = item.cName;
                    requestParam.variables.maintOrg = "77e0c17eac9a405492c393e70ffd8479";
                    requestParam.variables.maintOrgName = "市场部";
                    requestParam.variables.personType = "member";
                    requestParam.variables.receivePerson = item.pCode;
                    requestParam.variables.receivePersonName = item.pName;
                    console.log('进入二班===');
                } else if (ecssMgtOrgCode === '624110105' && item.orgId == "b9af53b58f594f4f9e8fc70bd4135833") {
                    // 城郊
                    requestParam.variables.maintGroup = item.orgId;
                    requestParam.variables.maintGroupName = item.cName;
                    requestParam.variables.maintOrg = "b57f5cb612864627807e7a603aa190c8";
                    requestParam.variables.maintOrgName = "配网管理部";
                    requestParam.variables.personType = "member";
                    requestParam.variables.receivePerson = item.pCode;
                    requestParam.variables.receivePersonName = item.pName;
                    console.log('进入城郊班===');
                } else {
                    continue;
                }
                successList.push({ id: hbsdList[0].eventId });
                autoTask_fun(requestParam);
                assigned = true;
                break;
            }
            //   else {
            // if (item.cName == '配网抢修班') {
            //     requestParam.variables.maintGroup = item.orgId;
            //     requestParam.variables.maintGroupName = item.cName;
            //     requestParam.variables.maintOrg = "b57f5cb612864627807e7a603aa190c8";
            //     requestParam.variables.maintOrgName = "配网管理部";
            //     requestParam.variables.personType = "bz";
            //     requestParam.variables.receivePerson = item.pCode || '';
            //     requestParam.variables.receivePersonName = item.pName || '';
            //     successList.push({ id: hbsdList[0].eventId });
            //     console.log('进入抢修班===');
            //     autoTask_fun(requestParam);
            //   }
            //}
        }
        // 派单配网抢修班
        if (!assigned) {
            for (const item of hbsdClassList) {
                if (item.cName == '配网抢修班') {
                    requestParam.variables.maintGroup = item.orgId;
                    requestParam.variables.maintGroupName = item.cName;
                    requestParam.variables.maintOrg = "b57f5cb612864627807e7a603aa190c8";
                    requestParam.variables.maintOrgName = "配网管理部";
                    requestParam.variables.personType = "bz";
                    requestParam.variables.receivePerson = item.pCode || '';
                    requestParam.variables.receivePersonName = item.pName || '';
                    successList.push({ id: hbsdList[0].eventId });
                    console.log('进入抢修班===');
                    autoTask_fun(requestParam);
                }
            }

            // let flag = true;
            // if (flag) {
            //     console.log('【日志】无班组满足派单条件，已派往抢修班');
            //   let type = "户表失电-嘉峪关";
            //   let orderID = JSON.stringify(successList);
            //   let time = mac.moment().format("YYYY-MM-DD HH:mm:ss");
            //   let name = "";
            //   let state = "被派到抢修班";
            //   mac.localHostAxjos({
            //     url: "http://localhost:13313/MonitorServices/setDisposeLog",
            //     method: "POST",
            //     data: JSON.stringify({
            //       type,
            //       orderID,
            //       name,
            //       time,
            //       state,
            //     }), //必须是字符串格式
            //   }).then(re => {
            //     if (re.status == 200) {
            //       mac.exeTQueue();
            //     }
            //   })
            // }
        }
    }
    // 自动播报
    function audioFC(text) {
        mac.audioPlay(text).then(response => {
            if (response.status == 200) {
                mac.localHostAxjos({
                    url: "http://localhost:13313/MonitorServices/setAudioPlayLog",
                    method: "POST",
                    data: JSON.stringify({ type: text, time: mac.moment().format("YYYY-MM-DD HH:mm:ss"), status: "成功" })
                })
            } else {
                mac.localHostAxjos({
                    url: "http://localhost:13313/MonitorServices/setAudioPlayLog",
                    method: "POST",
                    data: JSON.stringify({ type: text, time: mac.moment().format("YYYY-MM-DD HH:mm:ss"), status: "失败" })
                })
            }
        }).catch(err => {
            mac.localHostAxjos({
                url: "http://localhost:13313/MonitorServices/setAudioPlayLog",
                method: "POST",
                data: JSON.stringify({ type: text, time: mac.moment().format("YYYY-MM-DD HH:mm:ss"), status: "异常" })
            })
        })
    }
    function autoTask_fun(requestParam) {
        console.log('自动派单===========', requestParam)
        BrowserAction(
            'sgBrowerserJsAjax2',
            "window." + callbackName1,
            `http://21.77.244.194:18890/#/webview/1543953229739896`,
            `http://21.77.244.194:18890/gdgl/active/service/order/saveAndSend`,
            "POST",
            `Content-Type:application/json;userId:${_this.userID};Access-Control-Allow-Credentials:true;Access-Control-Allow-Methods: GET, POST, OPTIONS,PUT,DELETE,OPTION;Access-Control-Allow-Origin:*`,
            JSON.stringify(requestParam)
        )
    }
    function msgFC(request) {
        mac.sendMessages(request).then(res4 => {
            if (res4.status == 200) {
                mac.localHostAxjos({
                    url: "http://localhost:13313/MonitorServices/setSendMessageLog",
                    method: "POST",
                    data: JSON.stringify({ type: request.content, time: mac.moment().format("YYYY-MM-DD HH:mm:ss"), status: "成功" })
                })
            } else {
                mac.localHostAxjos({
                    url: "http://localhost:13313/MonitorServices/setSendMessageLog",
                    method: "POST",
                    data: JSON.stringify({ type: request.content, time: mac.moment().format("YYYY-MM-DD HH:mm:ss"), status: "失败" })
                })
            }
        }).catch(err => {
            mac.localHostAxjos({
                url: "http://localhost:13313/MonitorServices/setSendMessageLog",
                method: "POST",
                data: JSON.stringify({ type: request.content, time: mac.moment().format("YYYY-MM-DD HH:mm:ss"), status: "异常" })
            })
        })
    }
}