import AddressService from '@/service/AddressService'
import xlsx from 'xlsx'

function findHeaderCell(Sheet: any, headerValue: any) {
  const positionName = Object.keys(Sheet).find((positionName) => {
    if (Sheet[positionName].v === headerValue) {
      return true
    }
  })
  if (positionName) {
    const matched = positionName.match(/([A-Z]+)([0-9]+)/i)
    if (matched) {
      const [_, first, second] = matched
      return {
        positionName,
        first,
        second: Number(second),
      }
    }
  } else {
    throw new Error(`表格中没有 '${headerValue}'`)
  }
}

function getAddressList(dataList: any[]) {
  const locationList = [] as any[]
  dataList.forEach((data: any) => {
    if (locationList.indexOf(data.location) === -1) {
      locationList.push(data.location)
    }
  })
  return locationList
}

async function getAddressLalonObj(locationList: string[]) {
  const rets = await AddressService.getInstance().getGpses2({
    addrs: locationList,
  })
  // let obj = {} as any
  // locationList.forEach((item, index) => {
  //   obj[item] = rets[index]
  // })
  return rets
}

function formatPositionToNumber(str: string) {
  switch (str) {
    case '一级分行':
      return 1
    case '二级分行':
      return 2
    case '一级支行':
      return 3
    case '二级支行':
      return 4
  }
}

function parseJSYHSheet(Sheet: any) {
  const nameCell = findHeaderCell(Sheet, '姓名')
  const positionCell = findHeaderCell(Sheet, '岗位角色')
  const phoneCell = findHeaderCell(Sheet, '手机号码')
  const levelCell = findHeaderCell(Sheet, '用户所在机构层级')
  const firstBranchCell = findHeaderCell(Sheet, '所属一级分行')
  const secondBranchCell = findHeaderCell(Sheet, '所属二级分行')
  const firstSubBranchCell = findHeaderCell(Sheet, '所属一级支行')
  const secondSubBranchCell = findHeaderCell(Sheet, '所属二级支行')
  const numberCell = findHeaderCell(Sheet, '机构号')
  const locationCell = findHeaderCell(Sheet, '详细地址')

  const satCell = findHeaderCell(Sheet, '8月14日起的周六')
  const sunCell = findHeaderCell(Sheet, '8月14日起的周日')
  const startCell = findHeaderCell(Sheet, '营业开始时间')
  const endCell = findHeaderCell(Sheet, '营业结束时间')

  if (nameCell && positionCell) {
    const dataList = []
    let temp_first_branch_v = undefined

    function getWorkStatus(sat = '', sun = '') {
      const config = [
        { value: 0, status: ['否', '否'] },
        { value: 1, status: ['是', '否'] },
        { value: 2, status: ['否', '是'] },
        { value: 3, status: ['是', '是'] },
      ]
      const the = config.find((item) => {
        return (
          item.status[0].trim() === sat.trim() &&
          item.status[1].trim() === sun.trim()
        )
      })
      if (!the) {
        console.log(sat, sun)
        console.log(the)
      }
      return the?.value
    }

    function getTime(start: any, end: any) {
      return `${start} ${end}`
    }

    for (
      let i = nameCell.second + 1;
      Sheet[`${nameCell.first}${i}`] !== undefined;
      ++i
    ) {
      const name = Sheet[`${nameCell.first}${i}`]
      const position = Sheet[`${positionCell.first}${i}`]
      const phone = Sheet[`${phoneCell?.first}${i}`]
      const level = Sheet[`${levelCell?.first}${i}`]
      const first_branch = Sheet[`${firstBranchCell?.first}${i}`]
      const second_branch = Sheet[`${secondBranchCell?.first}${i}`]
      const first_sub_branch = Sheet[`${firstSubBranchCell?.first}${i}`]
      const second_sub_branch = Sheet[`${secondSubBranchCell?.first}${i}`]
      const location = Sheet[`${locationCell?.first}${i}`]
      const number = Sheet[`${numberCell?.first}${i}`]

      const sat = Sheet[`${satCell?.first}${i}`]
      const sun = Sheet[`${sunCell?.first}${i}`]
      const start = Sheet[`${startCell?.first}${i}`]
      const end = Sheet[`${endCell?.first}${i}`]

      const first_branch_v = first_branch.v
      if (temp_first_branch_v) {
        if (temp_first_branch_v !== first_branch_v) {
          throw new Error('一次只能导入所属一级分行相同的用户信息')
        }
      } else {
        temp_first_branch_v = first_branch_v
      }

      dataList.push({
        name: name && name.v && name.v.toString(),
        role: position && position.v,
        phone:
          (phone &&
            phone.v &&
            String(phone.v).match(/\d+/) &&
            (<any>String(phone.v).match(/\d+/))[0]) ||
          '',
        level: formatPositionToNumber(level && level.v),
        first_branch: first_branch && first_branch.v,
        second_branch: second_branch && second_branch.v,
        first_sub_branch: first_sub_branch && first_sub_branch.v,
        second_sub_branch: second_sub_branch && second_sub_branch.v,
        location: location && location.v,
        number: number && String(number.v),
        work: getWorkStatus(sat.v, sun.v),
        time: getTime(start.v, end.v),
      })
    }
    return dataList
  }
}

/* 只能解析xlsx文件 accpet设置 .xlsx */
export const handle建设银行excelFileChange = (e: Event) => {
  return new Promise((resolve, reject) => {
    const files = (e.target as HTMLInputElement).files
    if (files && files.length !== 0) {
      const f = files[0]

      if (!f.name.match(/\.xlsx$/)) {
        reject('请选择xlsx文件')
        return
      }

      var reader = new FileReader()
      reader.onload = function (e) {
        var data = new Uint8Array(
          ((e.target as any).result as unknown) as ArrayBufferLike,
        )
        var workbook = xlsx.read(data, { type: 'array' })
        /* DO SOMETHING WITH workbook HERE */

        const Sheets = workbook.Sheets
        const SheetsKeys = Object.keys(Sheets)
        if (SheetsKeys.length !== 0) {
          const list = (parseJSYHSheet(
            Sheets[SheetsKeys[0]],
          ) as unknown) as any[]
          console.log(list, 'show list');
          const locationList = getAddressList((list as unknown) as any)
          console.log(JSON.stringify(locationList))
          getAddressLalonObj(locationList).then((addressLalonObj) => {
            console.log(addressLalonObj,' show addressLalonObj');
            list.forEach((data) => {
              data.la_lon = addressLalonObj[data.location]
            })
            console.log(list, 'show list')
            resolve(list)
          })
        } else {
          reject('excel文件无Sheet')
          return
        }
      }
      reader.readAsArrayBuffer(f)
    }
  })
}
