import axios from 'axios'
import lodop from '@/libs/lodop/index'

export default class AsyncUtils {
  /**
   * 执行多个promise,将结果封装成数组,按照promise顺序返回
   * @param promises {Array<Promise>>}
   * @returns {Promise<Array>}
   */
  static all(promises) {
    let len = promises.length,
      res = []
    let count = len
    if (len) {
      return new Promise((resolve, reject) => {
        for (let i = 0; i < len; i++) {
          let promise = promises[i]
          promise.then(
            (response) => {
              res[i] = response
              if (!--count) {
                resolve(res)
              }
            },
            (error) => {
              res[i] = error
              if (!--count) {
                resolve(res)
              }
            }
          )
        }
      })
    }
  }

  /**
   * 延迟指定毫秒数
   * @param time 毫秒值
   * @returns {Promise<boolean>}  返回一个promise
   */
  static wait(time = 100) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true)
      }, time)
    })
  }

  /**
   * 包装promise,将错误也作为返回
   * @param promises
   * @returns {Promise<unknown>}
   */
  static wrapper(promises) {
    return new Promise(resolve => {
      promises.then(
        (response) => {
          resolve(response)
        },
        (error) => {
          resolve({
            code: 500,
            msg: error.message
          })
        }
      )
    })
  }

  /**
   * examTypeName,remarks,
   *       region,visitNum,patientName,
   *       reservationDate,timeFrame,timeSlot,
   *       examAddress,examDeptName,
   *       itemName
   * @returns {Promise<void>}
   */
  static async print(rows = []) {
    console.log('需要打印的数据', rows)
    let param = { id: '8' }
    param = JSON.stringify(param)
    let data = {
      apiId: '456',
      param: param
    }
    let printTemplate = {}
    const res1 = await axios.post('http://172.16.9.109:28081/open/api/handlerRequestNoAuth', data)
    printTemplate = res1.data.data[0]
    let param2 = { tempId: '8' }
    param2 = JSON.stringify(param2)
    let data2 = {
      apiId: '457',
      param: param2
    }
    let printTemplateItems = []
    const res2 = await axios.post('http://172.16.9.109:28081/open/api/handlerRequestNoAuth', data2)
    printTemplateItems = res2.data.data
    for (let i = 0; i < printTemplateItems.length; i++) {
      printTemplateItems[i].dragable = printTemplateItems[i]['dragable2str']
      printTemplateItems[i].style = JSON.parse(printTemplateItems[i]['style2str'])
      printTemplateItems[i].lodopStyle = JSON.parse(printTemplateItems[i]['lodop_style2str'])
      printTemplateItems[i].resizable = printTemplateItems[i]['resizable2str']
    }
    printTemplate.tempItems = printTemplateItems
    let printData = []
    rows.forEach(item => {
      let pInfo = ''
      const {
        examTypeName, remarks,
        region, visitNum, patientName,
        reservationDate, timeFrame, timeSlot,
        examAddress, examDeptName,
        itemName, isUrgent
      } = item
      let singleData = {}
      singleData.registerTitle = `${examTypeName}预约单${isUrgent + '' === '1' ? '（加急）' : ''}`
      singleData.name = patientName
      singleData.area = region
      singleData.bedNum = visitNum
      singleData.dateTime = `${reservationDate.substring(0, 4)}年${reservationDate.substring(5, 7)}月${reservationDate.substring(8, 10)}日`
      singleData.timeInterval = `${timeFrame}${timeSlot}`
      singleData.checkItem = itemName.split('、').join('\n')
      singleData.address = `${examAddress}${examDeptName}`
      singleData.item1 = remarks
      if (item['visitTypeCode'] === '1') {
        // 门诊模板
        //pInfo = `请${region} 科室,门诊号: ${visitNum} 的患者 ${patientName} 于${reservationDate.substring(0, 4)}年${reservationDate.substring(5, 7)}月${reservationDate.substring(8, 10)}日${timeFrame}${timeSlot}持此预约单到${examAddress}${examDeptName}进行 ${itemName} 检查`
        singleData.area = `科室:${region}`
        singleData.bedNum = `门诊号:${visitNum}`
      } else {
        // 住院模板
        //pInfo = `请${region} 病区 ${visitNum}床的患者 ${patientName} 于${reservationDate.substring(0, 4)}年${reservationDate.substring(5, 7)}月${reservationDate.substring(8, 10)}日${timeFrame}${timeSlot}持此预约单到${examAddress}${examDeptName}进行 ${itemName} 检查`
        singleData.area = `病区:${region}`
        singleData.bedNum = `住院号:${visitNum}`
      }
      printData.push(singleData)
      /*      printData.push({
              registerTitle: `${examTypeName}预约单${isUrgent + '' === '1' ? '（加急）' : ''}`,
              printInfo: pInfo,
              item1: remarks
            })*/
    })
    lodop.print(printTemplate, printData)
  }

}
