import { getWebsit } from '@/api/customerManagement.js'

window.AppVueThis = null

export function setAppVueThis(e) {
  AppVueThis = e
}

export default function (pam = {}, option = [], placeholder = '请选择操作网点', errMsg = '请选择操作网点') {
  return new Promise((r, j) => {
    if (!AppVueThis) {
      j({})
      return
    }
    const h = AppVueThis.$createElement
    var done_ = null
    function tanchuang() {
      AppVueThis.$msgbox({
        title: placeholder,
        message: h(
          'el-select',
          {
            style: {
              width: '100%'
            },
            props: {
              value: '',
              filterable: true,
              clearable: true,
              size: 'mini'
            },
            ref: 'selectOptionWebsit',
            on: {
              change: e => {
                console.log(AppVueThis)
                AppVueThis.$refs.selectOptionWebsit.value = e
              }
            }
          },
          [
            option.map(it => {
              return h('el-option', {
                props: {
                  key: it.websitId,
                  label: it.name,
                  value: it.websitId
                }
              })
            })
          ]
        ),
        beforeClose: function (action, instance, done) {
          if (action === 'confirm') {
            if (AppVueThis?.$refs?.selectOptionWebsit?.value) {
              done()
            } else {
              done_ = done
              AppVueThis.$message({
                message: errMsg,
                type: 'warning'
              })
            }
          } else {
            done()
          }
        },
        showCancelButton: true,
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(_ => {
          if (AppVueThis?.$refs?.selectOptionWebsit?.value) {
            r(option?.find(item => item?.websitId === AppVueThis?.$refs?.selectOptionWebsit?.value))
            done_?.()
          } else {
            j()
          }
        })
        .catch(_ => {
          j()
        })
    }
    if (option && option.length) {
      if (option.length == 1) {
        r(option?.[0])
      } else if (option.length > 1) {
        tanchuang()
      }
    } else {
      getWebsit({ status: true, ...pam }).then(res => {
        option = res.data
        if (option.length == 1) {
          r(option?.[0])
        } else if (option.length > 1) {
          tanchuang()
        }
      })
    }
  })
}
