import { platformObj } from "../types";

let domEle = {
    inputOrderId: document.querySelector("#orderFilterPane > div > form > ul > li:nth-child(4) > input") as HTMLInputElement,
    btnSearch: document.querySelector("#searchOrderButton") as HTMLButtonElement,
    checkBoxSelectAll: document.querySelector("#orderTable > thead > tr > th:nth-child(1) > input[type=checkbox]") as HTMLInputElement,
    btnPrint: document.querySelector("#printWaybillButton") as HTMLButtonElement,
    selectWaybillTemplate: document.querySelector("#printWaybillDialog > div > div > div.modal-body > form > div:nth-child(2) > div > select") as HTMLSelectElement,
    radioGetNewWaybill: document.querySelector("#printWaybillDialog > div > div > div.modal-body > form > div.form-group.get-waybill-no-method-radios > div > label:nth-child(1) > input[type=radio]") as HTMLInputElement,
    inputWaybillNoOnly: document.querySelector("#printWaybillDialog > div > div > div.modal-body > form > div:nth-child(4) > div > div > label > input[type=checkbox]") as HTMLInputElement,
    btnDialogPrint: document.querySelector("#printWaybillDialog > div > div > div.modal-footer > button.btn.btn-primary.print-button") as HTMLButtonElement,
    btnDialogCancel:document.querySelector("#printWaybillDialog > div > div > div.modal-footer > button.btn.btn-default") as HTMLButtonElement,
    modalResult: document.querySelector("#printEwaybillResultDialog") as HTMLDivElement,
    tableResult: document.querySelector("#printEwaybillResultDialog > div > div > div.modal-body > div.result-table-container > table") as HTMLTableElement,
    btnClose: document.querySelector("#printEwaybillResultDialog > div > div > div.modal-footer > button.btn.btn-default") as HTMLButtonElement,
    btnDeliver: document.querySelector("#printEwaybillResultDialog > div > div > div.modal-footer > button.btn.ship-now-btn") as HTMLButtonElement,
    unReachModal:()=>document.querySelector(".bootbox-message") as HTMLDivElement,
    unReachAccept:()=>document.querySelector(".bootbox-accept") as HTMLButtonElement,
    printErrorModal:()=>document.querySelector(".bootbox-message") as HTMLDivElement,
    printErrorConfirm:()=>document.querySelector(".bootbox-accept") as HTMLButtonElement,
    reauthDialog: document.querySelector("#reauthDialog") as HTMLDivElement,//店铺授权
    reauthDialogTitle: document.querySelector("#reauthDialog .modal-title") as HTMLDivElement,//店铺授权
    shopName: document.querySelector("#reauthDialog .shopName") as HTMLDivElement,//店铺授权
    reauthDialogClose:document.querySelector("#reauthDialog .btn-default") as HTMLButtonElement,
    //   电子面单获取失败
    miandanbootBox:(): any => document.querySelector('.bootbox'),
    // 发货中弹窗
    sendProModal:()=>document.querySelector("div#shipDialog") as HTMLDivElement,
}
async function booking(wayCompanyId: string, orderNo: string,fhy_type:Number) {
    let checkOptionObj = platformObj
    chrome.storage.local.get({ checkOptionObj: platformObj }, function (res) {
      checkOptionObj = res.checkOptionObj
    })
    let result = {
        status: 0,
        msg: "",
        data: []
    }
    let printError: any = orderNo
    result = await waitreauthDialog();
    if (result.status > 0) {
        result.data=printError
        return result;
    }
    domEle.inputOrderId.value = orderNo;
    domEle.checkBoxSelectAll.checked = true;
    domEle.btnSearch.click();
    result = await waitOrder();
    if (result.status > 0) {
        result.data=printError
        return result;
    }

    domEle.checkBoxSelectAll.click();


    domEle.btnPrint.click();
    await delayDate(500);
    console.log(domEle.unReachModal);
    if(domEle.unReachModal() && domEle.unReachModal().innerText==' 所选订单中部分订单地址不可达，是否继续打印？'){
 
        domEle.unReachAccept().click();
    }

    result = await waitDialog();
    if (result.status > 0) {
        result.data=printError
        return result;
    }
    for (let i = 0; i < domEle.selectWaybillTemplate.options.length; i++) {
        if (domEle.selectWaybillTemplate.options[i].value == wayCompanyId) {
            domEle.selectWaybillTemplate.selectedIndex = i;
            domEle.radioGetNewWaybill.click();
            if (domEle.inputWaybillNoOnly.checked == false) domEle.inputWaybillNoOnly.click();


            domEle.btnDialogPrint.click();

            result = await waitPrintResult();


            if (result.status == 0) {
                let printReslut: any = {
                    success: 0,
                    count: domEle.tableResult.rows.length,
                    fail: 0,
                    list: []
                }
                let chooseIndex = 0
                let rowResultList:any = []
                for (let rowIter = 0; rowIter < domEle.tableResult.rows.length; rowIter++) {
                    let rowResult = domEle.tableResult.rows[rowIter].cells[2].innerText;
                    let rowInfo = domEle.tableResult.rows[rowIter].cells[1].innerText;
                    let rowObject = {
                        info: rowInfo,
                        msg: rowResult,
                        orderNo:'',
                        success: 1,
                    }
                    if(rowIter===0){
                        rowObject.orderNo = orderNo
                    }
                    rowResultList.push(rowResult)
                    if (rowResult.indexOf("打印失败") > -1) {
                        printReslut.fail++;
                        rowObject.success = 0;
                        if(domEle.tableResult.rows[rowIter].cells[2].innerText.includes('电子面单账户余额不足')){
                            result.msg = '电子面单余额不足'
                        }
                    } else {
                        printReslut.success++;
                    }
                    printReslut.list.push(rowObject)
                }
                result.data = printReslut;
                // 如果所有的订单都打印失败则，等会再发货，关闭弹窗
                if(rowResultList.every((item:any)=>item.includes('打印失败'))){
                    chooseIndex = -1
                }
                
                // 等会再发货
                if(chooseIndex===-1){
                    console.log('等会再发货');
                    domEle.btnClose.click();
                }else{
                    if((fhy_type===10&&checkOptionObj['jiu-taobao'])||(fhy_type===20&&checkOptionObj['jiu-pdd'])){
                      // 马上发货
                      console.log('马上发货');
                      domEle.btnDeliver.click()
                    }else{
                       console.log('等会再发货');
                       domEle.btnClose.click();
                    }
                }
                for (let i = 0; i < 20; i++) {
                    await delayDate(1000)
                    if(domEle.sendProModal().style.display==='none'){
                                                //发货中
                       return result
                    }
                }
                return result;
            }else{
                //取消打印
                await delayDate(1000);
                domEle.btnDialogCancel.click();
                result.data=printError
                return result;
            }


            break;

        }
    }

    result.msg = "未匹配快递单模板";
    result.status = 3;
    result.data=printError
    domEle.btnDialogCancel.click();
    return result;

}

async function waitreauthDialog() {
    let result = {
        status: 5,
        msg: "获取店铺授权",
        data: [],
    }
    for (let i = 0; i < 10; i++) {
        await delayDate(1000);
        if (domEle.reauthDialog&&domEle.reauthDialog.style.display==='block') {
            await delayDate(1000)
            result.msg=`获取${domEle.shopName.innerText}店铺授权失败`
            domEle.reauthDialogClose.click()
            return result
        }else {
            result.status = 0;
            result.msg = ""
            return result;
        }
    }
    return result;
}
async function waitOrder() {
    let result = {
        status: 4,
        msg: "获取订单超时",
        data: [],
    }
    for (let i = 0; i < 30; i++) {
        await delayDate(1000);
        if (domEle.checkBoxSelectAll.checked != true) {

            if (document.getElementsByClassName("not-order-found").length > 0) {
                //无订单
                result.status = 2;
                result.msg = "无相关订单"
                return result;
            } else {
                result.status = 0;
                result.msg = ""
                return result;
            }
        }
    }
    return result;
}
async function waitDialog() {
    let result = {
        status: 4,
        msg: "获取打印按钮超时",
        data: [],
    }
    for (let i = 0; i < 30; i++) {
        await delayDate(1000);
        if (domEle.btnDialogPrint.disabled == false) {
            result.status = 0;
            result.msg = ""
            return result;
        }
    }
    return result;
}

async function waitPrintResult() {
    let result = {
        status: 4,
        msg: "获取打印结果超时",
        data: [],
    }
    for (let i = 0; i < 100; i++) {
        await delayDate(1000);
        if (domEle.reauthDialog&&domEle.reauthDialog.style.display==='block') {
            console.log('店铺授权',domEle.shopName.innerText);
            result.status = 5;
            result.msg=`获取${domEle.shopName.innerText}店铺授权失败`;
            domEle.reauthDialogClose.click()
            return result;
        }
        if (domEle.modalResult.className == 'modal fade sui-modal none in') {
            result.status = 0;
            result.msg = ""
            return result;
        }
        if (domEle.miandanbootBox()&&domEle.miandanbootBox().style.display === 'block') {
            domEle.printErrorConfirm().click();
            result.msg = '获取电子面单失败'
            return result
        }
        if(domEle.printErrorModal() && domEle.printErrorModal().innerText==' 获取电子面单失败，从9月1日起淘宝平台开启付费解密虚拟号方案（查看详情），因此不支持非菜鸟电子面单打印，请尽量使用菜鸟电子面单打印，如需付费解密虚拟号打印非菜鸟电子面单请联系发货易客服咨询'){
            result.msg="获取电子面单失败";
            console.log('获取电子面单失败',domEle.printErrorModal());
            domEle.printErrorConfirm().click();
            return result;
        }
        
    }
    return result;
}

function delayDate(time: number) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            //console.log(‘开始执行‘)
            resolve("success");
        }, time);
    });
}
export default {
    booking
}