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'),
  btnDialogPrintClose: (): any =>
    document.querySelector('div.ant-modal-footer button:nth-child(2)'),
  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)") ,
  btnClose: (): any => {
    let targetBtn = null
    document.querySelectorAll('div.ant-modal-footer button').forEach((btn) => {
      if (btn.textContent === '等会再发货') targetBtn = btn
    })
    return targetBtn
  },
  btnDeliver: (): any => {
    let targetBtn = null
    document.querySelectorAll('div.ant-modal-footer button').forEach((btn) => {
      console.log('马上发货',btn);
      if (btn.textContent === '马上发货') targetBtn = btn
    })
    return targetBtn
  },
  deliverResult: (): any =>
    document.querySelector(
      '.ant-modal-body>div.ant-table-wrapper .ant-table-tbody'
    ),
  deliverResultTable: (): any =>
    document.querySelector(
      '.ant-modal-body>div.ant-table-wrapper .ant-table-tbody>table'
    ),
  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'),
  rcDialogTitle49:(): any => document.querySelector('.rcDialogTitle49'),
  rcDialogClose:(): any => document.querySelector('.ant-modal-close'),
//   电子面单获取失败
  miandanbootBox:(): any => document.querySelector('.bootbox'),
  miandanbootBoxClose:(): any => document.querySelector('.bootbox-close-button'),
   // 发货中弹窗
   sendProModal:():any =>document.querySelector(".shipping-processing"),
}
async function booking(
  waybillTemplateTitle: string,
  orderNo: string,
  shopId: string,
  fhy_type: number
) {
  let checkOptionObj = platformObj
  chrome.storage.local.get({ checkOptionObj: platformObj }, function (res) {
    checkOptionObj = res.checkOptionObj
  })
  let result = {
    status: 4,
    msg: '未找到店铺',
    data: [],
    action:''
  }
  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
  }
  await delayDate(2000)
  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))
  if(!document.querySelector(".ant-modal-body")){
    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: [],
          deliverList:[]
        }
        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 rowInfo =
          domEle.tableResult().rows[rowIter].cells[2].childNodes[0].childNodes[0].innerText
          console.log('rowInfo',rowInfo);
          
          rowInfo = rowInfo.replace('订单编号:','')
          let rowObject = {
            info: rowInfo,
            msg: rowResult,
            orderNo: '',
            success: 1,
          }
          if (rowIter === 0) {
            rowObject.orderNo = orderNo
          }
          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('余额不足')&& 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())
          }
        }
        for (let i = 0; i < 30; i++) {
          await delayDate(1000)
          if(!domEle.sendProModal()){
                                      //发货中
              if (domEle.deliverResult()) {
                for (
                  let rowIter = 1;
                  rowIter < domEle.deliverResultTable().rows.length;
                  rowIter++
                ) {
                  let rowResult = domEle.deliverResultTable().rows[rowIter].cells[3].innerText
                  let rowResultHTML =
                    domEle.deliverResultTable().rows[rowIter].cells[3].innerHTML
                  let rowInfo =
                    domEle.deliverResultTable().rows[rowIter].cells[1].innerText
                  let shopInfo =
                    domEle.deliverResultTable().rows[rowIter].cells[0].innerText
                  let rowRes = {
                    info: rowInfo,
                    msg: rowResult,
                    orderNo: '',
                  }
                  if (domEle.deliverResultTable().rows[rowIter].cells[3].innerHTML.indexOf('class="text-error"') > -1) {
                    if (domEle.deliverResultTable().rows[rowIter].cells[3].innerHTML.includes('店铺授权过期')) {
                      rowRes.msg = `${shopInfo}店铺授权过期，发货失败`
                      rowRes.orderNo = rowRes.orderNo?rowRes.orderNo+','+rowInfo:rowInfo
                    }
                    printReslut.deliverList.push(rowRes)
                  }
                }
                result.data = printReslut
                // 关闭
                simulateMouseClick(domEle.deliverClose())
              }
              if(domEle.rcDialogTitle49()){
                  console.log('49',domEle.rcDialogTitle49());
                  // domEle.rcDialogTitle49().innerText==='备注打印失败订单'
                simulateMouseClick(domEle.rcDialogClose())
              }
             return result
          }
        }
        
        return result
                            
        // for (let rowIter = 1; rowIter < domEle.deliverResult().rows.length; rowIter++) {
        //     let rowDeliverHTML = domEle.tableResult().rows[rowIter].cells[3].innerHTML
        //     rowDeliverList.push(rowDeliverHTML)
        // }
      }

      break
    }
  }

  result.msg = '未匹配快递单模板'
  result.status = 3
  result.data = printError
  simulateMouseClick(domEle.btnDialogPrintClose())
  return result
}

async function waitreauthDialog() {
  let result = {
    status: 5,
    msg: '获取店铺授权',
    data: [],
    action:''
  }
  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}店铺授权失败`
      return result
    } else {
      result.status = 0
      result.msg = ''
      return result
    }
  }
  return result
}
async function waitOrder() {
  let result = {
    status: 4,
    msg: '获取订单超时',
    data: [],
    action:''
  }
  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: [],
    action:''

  }
  for (let i = 0; i < 30; i++) {
    await delayDate(1000)
    if ( document.querySelector(".ant-modal-body") &&  document.querySelector(".ant-modal-body")?.querySelector(".ant-select-selector") && (document.querySelector(".ant-modal-body")?.querySelector(".ant-select-selector") as HTMLElement)?.innerText.indexOf("【")>-1) {
      result.status = 0
      result.msg = ''
      return result
    }
  }
  return result
}
async function waitPrintResult() {
  let result = {
    status: 4,
    msg: '获取打印结果超时',
    data: [],
    action:''

  }
  for (let i = 0; i < 100; i++) {
    await delayDate(1000)
    if (domEle.tableResult()) {
      result.status = 0
      result.msg = ''
      return result
    }
    if (
      domEle.reauthDialog() &&
      domEle.reauthDialog().style.display === 'block'
    ) {
      result.status = 5
      result.msg = `获取${domEle.shopName().innerText}店铺授权失败`
      return result
    }
    if (domEle.miandanbootBox()&&domEle.miandanbootBox().style.display === 'block') {
        simulateMouseClick(domEle.miandanbootBoxClose())
        result.status = 6
        result.msg = '获取电子面单失败'
        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) {
  if (!element) return
  mouseClickEvents.forEach((mouseEventType) =>
    element.dispatchEvent(
      new MouseEvent(mouseEventType, {
        view: window,
        bubbles: true,
        cancelable: true,
        buttons: 1,
      })
    )
  )
}

export default {
  booking,
}
