

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

let domEle = {
    divNav:document.getElementsByClassName("nav-link") as HTMLCollection,
    inputOrderId: "#originalIds",
    btnSearch: "#root > section > main > div > div > div > div.order-main > div.order-table-container > div.order-search-pane > div > div > div:nth-child(2) > button:nth-child(2)",
    checkBoxSelectAll: "div.bottom-operation-bar > span input.ant-checkbox-input",
    btnPrint: ".ec-print-waybill-button",
    modalTips:"ant-modal-confirm-title",
    btnTipsConfirm:"div.ant-modal-confirm-body-wrapper > div > button.ant-btn-primary",
    spanWaybillTemplate: ():any=>document.getElementsByClassName("ant-modal-body")[0].getElementsByClassName("ant-select-selector")[0] ,
    divWaybillTemplateList: ():any=>document.getElementsByClassName("rc-virtual-list-holder-inner")[0] ,
    radioGetNewWaybill: ():any=>document.querySelector(".ant-modal-body input.ant-radio-input") ,
    inputWaybillNoOnly: ():any=>document.querySelector("#isGenerateWaybillNoOnly")  ,
    btnDialogPrint: ():any=>document.querySelector("div.ant-modal-footer button"),
    modalResult: "#printEwaybillResultDialog",
    tableResult: ():any=>document.querySelector("#ewaybill-result-table > div > div.ant-table-body > table"),
    btnClose: ():any=>document.querySelector("div.ant-modal-footer button:nth-child(3)") ,
    btnDeliver: ():any=>document.querySelector("div.ant-modal-footer button:nth-child(2)") ,
    deliverResult:():any=>document.querySelector(".ant-modal-body>div.ant-table-wrapper .ant-table-tbody"),
    deliverClose: ():any=>document.querySelector("div.ant-modal-footer button") ,
    reauthDialog: ():any=>document.querySelector("#reauthDialog") ,
    reauthDialogTitle: ():any=>document.querySelector("#reauthDialog modal-title") ,
    shopName: ():any=>document.querySelector("#reauthDialog shopName") ,
}  
async function booking(waybillTemplateTitle: string, orderNo: string,shopId:string,fhy_type:number) {
    let checkOptionObj = platformObj
    chrome.storage.local.get({ checkOptionObj: platformObj }, function (res) {
      console.log('新版V2',res.checkOptionObj);
      checkOptionObj = res.checkOptionObj
    })
    let result = {
        status: 4,
        msg: "未找到店铺",
        data: [],
    }
    let printError: any = orderNo
    result = await waitreauthDialog();
    if (result.status > 0) {
        result.data=printError
        return result;
    }
    for(let navIter=0;navIter<domEle.divNav.length;navIter++){
        let aNav = domEle.divNav[navIter] as HTMLLinkElement;
        
        if(aNav.href.indexOf(shopId)>-1){
            result.status=0;
            result.msg="";
            if(aNav.className.indexOf("active")==-1){
                aNav.click();
            }
            break;
        }
    }

    if (result.status > 0) {
        result.data=printError
        return result;
    }
    result = await waitOrder();
    if (result.status > 0) {
        result.data=printError
        return result;
    }
    changeReactInputValue(document.querySelector(domEle.inputOrderId),orderNo)
    

    simulateMouseClick(document.querySelector(domEle.btnSearch));
    result = await waitOrder();
    if (result.status > 0) {
        result.data=printError
        return result;
    }


    simulateMouseClick(document.querySelector(domEle.checkBoxSelectAll));
    simulateMouseClick(document.querySelector(domEle.btnPrint));
    await delayDate(500);

    if(document.getElementsByClassName(domEle.modalTips).length>0){
 
        simulateMouseClick(document.querySelector(domEle.btnTipsConfirm));
    }

    result = await waitDialog();
    if (result.status > 0) {
        result.data=printError
        return result;
    }


    simulateMouseClick(domEle.spanWaybillTemplate());
    let waybillTemplateList= domEle.divWaybillTemplateList();

    for (let i = 0; i < waybillTemplateList.childNodes.length; i++) {
        let divItem = waybillTemplateList.childNodes[i] as any;
        if (divItem.innerText.includes(waybillTemplateTitle) ) {

            simulateMouseClick(divItem);
            
            simulateMouseClick(domEle.radioGetNewWaybill());
            
            if (domEle.inputWaybillNoOnly().checked == false) simulateMouseClick(domEle.inputWaybillNoOnly());
            
            if(!domEle.inputWaybillNoOnly().checked ){
                result.status=5;
                result.msg="未选择仅获取电子面单";
                result.data=printError
                return result;
            }

            simulateMouseClick(domEle.btnDialogPrint());
            result = await waitPrintResult();


            if (result.status == 0) {
                let printReslut: any = {
                    success: 0,
                    count: domEle.tableResult().rows.length-1,
                    fail: 0,
                    list: []
                }
                let chooseIndex = 0
                let rowResultList:any = []
                for (let rowIter = 1; rowIter < domEle.tableResult().rows.length; rowIter++) {
                    let rowResult = domEle.tableResult().rows[rowIter].cells[2].innerText;
                    let rowResultHTML = domEle.tableResult().rows[rowIter].cells[2].innerHTML
                    let rowInfo = domEle.tableResult().rows[rowIter].cells[1].childNodes[0].childNodes[0].childNodes[1].textContent;
                    let rowObject = {
                        info: rowInfo,
                        msg: rowResult,
                        orderNo,
                        success: 1,
                    }
                    rowResultList.push(rowResultHTML)
                    if (domEle.tableResult().rows[rowIter].cells[2].innerHTML.indexOf('class="text-error"') > -1) {
                        printReslut.fail++;
                        rowObject.success = 0;
                        if(domEle.tableResult().rows[rowIter].cells[2].innerHTML.includes('电子面单余额不足')){
                            result.msg = '电子面单余额不足'
                        }
                    } else {
                        printReslut.success++;
                    }
                    printReslut.list.push(rowObject)
                }
                result.data = printReslut;
                // console.log(result,rowResultList);
                  // 如果所有的订单都打印失败则，等会再发货，关闭弹窗
                if(rowResultList.every((item:any)=>item.includes('class="text-error"'))){
                   chooseIndex = -1
                }
                // 等会再发货
                if(chooseIndex===-1){
                    console.log('等会再发货1');
                    simulateMouseClick(domEle.btnClose());
                }else{
                    console.log('发货',fhy_type,checkOptionObj);
                    if((fhy_type===30&&checkOptionObj['xin-taobao'])||(fhy_type===40&&checkOptionObj['xin-pdd'])||(fhy_type===50&&checkOptionObj['xin-dy']||(fhy_type===60&&checkOptionObj['xin-other']))){
                        // 马上发货
                        console.log('马上发货');
                        simulateMouseClick(domEle.btnDeliver());
                      }else{
                         console.log('等会再发货2');
                         simulateMouseClick(domEle.btnClose());
                      }
                }
                await delayDate(1000);
                // console.log('xxxx',domEle.deliverResult(),domEle.deliverClose());
                if(domEle.deliverResult()){
                    // 关闭
                    simulateMouseClick(domEle.deliverClose());
                }
                // for (let rowIter = 1; rowIter < domEle.deliverResult().rows.length; rowIter++) {
                //     let rowDeliverHTML = domEle.tableResult().rows[rowIter].cells[3].innerHTML
                //     rowDeliverList.push(rowDeliverHTML)
                // }
                return result;
            }


            break;

        }
    }

    result.msg = "未匹配快递单模板";
    result.status = 3;
    result.data=printError
    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.reauthDialogTitle().innerText=='店铺授权') {
            console.log('店铺授权',domEle.shopName().innerText);
            result.msg=`获取${domEle.shopName().innerText}店铺授权失败`;
            return result;
        }
    }
    return result;
}
async function waitOrder() {
    let result = {
        status: 4,
        msg: "获取订单超时",
        data: [],
    }
    for (let i = 0; i < 30; i++) {
        await delayDate(1000);

        let loadingMask = document.querySelector("#root > section > main > div > div > div > div.order-main > div.order-table-container > div.loading-mark-container > div") as any;
        if (loadingMask.style.display=="none" ) {

            if (document.querySelector("#root > section > main > div > div > div > div.order-main > div.order-table-container > div.loading-mark-container > table > tbody > tr > td > div > div.mb10 > p")) {
                //无订单
                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 (document.getElementsByClassName("ant-modal-content").length) {

            result.status = 0;
            result.msg = ""
            return result;
        }
    }
    return result;
}

async function waitPrintResult() {
    let result = {
        status: 4,
        msg: "获取打印结果超时",
        data: [],
    }
    for (let i = 0; i < 30; i++) {
        await delayDate(1000);
        if (domEle.tableResult()) {
            result.status = 0;
            result.msg = ""
            return result;
        }
        if (domEle.reauthDialog()&&domEle.reauthDialogTitle().innerText=='店铺授权') {
            console.log('店铺授权',domEle.shopName().innerText)
            result.status = 5
            result.msg=`获取${domEle.shopName().innerText}店铺授权失败`
            return result
        }
    }
    return result;
}

function delayDate(time: number) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            //console.log(‘开始执行‘)
            resolve("success");
        }, time);
    });
}
function changeReactInputValue(inputDom:any,newText:string){
	let lastValue = inputDom.value;
	inputDom.value = newText;
	let event = new Event('input', { bubbles: true });
    // @ts-ignore
	event.simulated = true;
	let tracker = inputDom._valueTracker;
	if (tracker) {
  	tracker.setValue(lastValue);
	}
	inputDom.dispatchEvent(event);
}


const mouseClickEvents = ['mousedown', 'click', 'mouseup'];
function simulateMouseClick(element:any){
    console.log('element',element);
  if(!element) return
  mouseClickEvents.forEach(mouseEventType =>
    element.dispatchEvent(
      new MouseEvent(mouseEventType, {
          view: window,
          bubbles: true,
          cancelable: true,
          buttons: 1
      })
    )
  );
}

export default {
    booking
}