<template>
  <a-drawer
    v-model:visible="vdata.drawerVisible"
    :mask-closable="false"
    :title=" vdata.isAdd ? '新增设备' : '修改设备' "
    :body-style="{ paddingBottom: '80px' }"
    width="40%"
    class="drawer-width"
    @close="onClose"
  >
    <a-form v-if="vdata.drawerVisible" ref="infoFormModel" :model="vdata.saveObject" layout="horizontal" :rules="vdata.rules">
      <a-row justify="space-between" type="flex">
        <a-col :span="24">
          <a-form-item label="选择厂商" name="provider">
            <a-select v-model:value="vdata.saveObject.provider" :disabled="!vdata.isAdd" placeholder="请选择厂商" @change="changeProvider">
              <a-select-option v-for="item in vdata.providerList" :key="item.value" :value="item.value">{{ item.text }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="选择厂商配置" name="configId">
            <a-select v-model:value="vdata.saveObject.configId" placeholder="请选择厂商配置" @change="changeProviderConfig">
              <a-select-option v-for="d in vdata.providerConfigList" :key="d.configId" v-model:value="d.configId">
                {{ d.configDesc }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.isAdd" :span="24">
          <a-form-item label="批次号" name="batchId">
            <a-input v-model:value="vdata.saveObject.batchId" placeholder="请输入批次号" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row v-if="!vdata.isAdd" justify="space-between" type="flex">
        <a-col :span="24">
          <a-form-item label="设备名称" name="deviceName">
            <a-input v-model:value="vdata.saveObject.deviceName" placeholder="请输入设备名称" />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 动态组件 -->
      <component :is="vdata.configComponent" ref="configComponentRef" />
    </a-form>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc"><check-outlined />保存</a-button>
    </div>

    <!-- 业务参数配置组件 -->
    <BizConfig ref="bizConfigRef" />
  </a-drawer>
</template>

<script lang="ts" setup>
import { API_URL_DEVICE_PROVIDER, API_URL_STORE_DEVICE, req } from '@/api/manage'
import BizConfig from '@/views/device/mchstoredevice/BizConfig.vue'
import CommonConfig from '@/views/device/mchstoredevice/CommonConfig.vue'
import BsjConfig from '@/views/device/mchstoredevice/provider/BsjConfig.vue'
import FeConfig from '@/views/device/mchstoredevice/provider/FeConfig.vue'
import ZgwlConfig from '@/views/device/mchstoredevice/provider/ZgwlConfig.vue'
import ZwConfig from '@/views/device/mchstoredevice/provider/ZwConfig.vue'
import YlyConfig from '@/views/device/mchstoredevice/provider/YlyConfig.vue'
import { defineProps, getCurrentInstance, nextTick, reactive, ref } from 'vue'
import providerJSON from '../provider.json'

const allList = providerJSON.all

  const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
 
  const props = defineProps({
    callbackFunc: { type: Function, default:null }
  })

  const configComponentRef = ref()
  const infoFormModel = ref()
  const bizConfigRef = ref()

  /** 定义全部组件 **/
  const allConfigPage = {
    'bsj': BsjConfig,
    'ps': CommonConfig,
    'zgwl': ZgwlConfig,
    'zlbz': CommonConfig,
    'fe': FeConfig,
    'zw': ZwConfig,
    'llzn': CommonConfig,
    'yly': YlyConfig
  }

  const  vdata = reactive({
    configComponent: null as any, // 动态组件 当前配置组件
    providerList: [] as any, // 厂商列表
    providerConfigList: [] as any, // 厂商配置列表
    storeList: [] as any, // 门店列表
    btnLoading: false,
    isAdd: true, // 新增 or 修改页面标志
    deviceType: 1, // 1-云喇叭 2-云打印 3-扫码POS
    saveObject: {} as any, // 数据对象
    recordId: null, // 更新对象ID
    drawerVisible: false, // 是否显示弹层/抽屉
    rules: {
      deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }]
    }
  }) as any

  function show (record: any) { // 弹层打开事件
  
    vdata.isAdd = !record.deviceId
    vdata.deviceType = record.deviceType

    // 厂商列表
    vdata.providerList = record.deviceType == 2 ? providerJSON.printer : record.deviceType == 3 ? providerJSON.pos : allList

    vdata.saveObject = { 'state': 1, 'deviceType': vdata.deviceType, provider: record.provider }
    vdata.configComponent = null

    if (infoFormModel.value != undefined) {
      infoFormModel.value.resetFields()
    }

    if (!vdata.isAdd) { // 修改信息 延迟展示弹层
      vdata.recordId = record.deviceId
      vdata.configComponent = allConfigPage[record.provider]

      req.getById(API_URL_STORE_DEVICE, vdata.recordId).then((res: any) => {
        if(res){
          vdata.saveObject = res

          req.list(API_URL_DEVICE_PROVIDER, { 'pageSize': -1, 'state': 1, 'deviceType': vdata.deviceType, 'provider': vdata.saveObject.provider }).then(res => { // 厂商配置下拉选择列表
            vdata.providerConfigList =  res.records
          })

          // 设置当前存储的配置项
          let currentConfig = JSON.parse(vdata.saveObject.deviceParams || '{}' )
          // 调用组件的渲染函数
          configComponentRef.value.pageRender(currentConfig, vdata.saveObject.deviceType, vdata.isAdd)

          // 业务参数配置组件
          let bizConfig = JSON.parse(vdata.saveObject.bizConfigParams || '{}' )
          bizConfigRef.value.pageRender(bizConfig, vdata.deviceType, vdata.saveObject.provider)
        }
      })
    }

    vdata.drawerVisible = true // 立马展示弹层信息
  }

  function  handleOkFunc () { // 点击【确认】按钮事件
    infoFormModel.value.validate().then((valid: any) =>{
      configComponentRef.value.getConfigParams().then((deviceParams: any) => {
        bizConfigRef.value.getConfigParams().then((bizConfigParams: any) => {
        
          vdata.btnLoading = true

          // 赋值
          vdata.saveObject.deviceNoParams = deviceParams.deviceNo || ''
          vdata.saveObject.bizConfigParams = bizConfigParams || ''
          vdata.saveObject.deviceParams = deviceParams || ''

          // 请求接口
          if (vdata.isAdd) {
            req.add(API_URL_STORE_DEVICE, vdata.saveObject).then((res: any) => {
              successFunc('保存成功')
            }).catch((err: any) => {
              vdata.btnLoading = false
            })
          } else {
            req.updateById(API_URL_STORE_DEVICE, vdata.recordId, vdata.saveObject).then((res: any) => {
              successFunc('修改成功')
            }).catch((err: any) => {
              vdata.btnLoading = false
            })
          }
        })
      })
    })
  }

  function successFunc(e: string) { // 新增/更新成功
    vdata.btnLoading = false
    $infoBox.message.success(e)
    props.callbackFunc()
    vdata.drawerVisible = false
  }

  function changeProvider() {
    vdata.saveObject.configId = null
    vdata.providerConfigList = []
    // 厂商配置列表
    req.list(API_URL_DEVICE_PROVIDER, { 'pageSize': -1, 'state': 1, 'deviceType': vdata.deviceType, 'provider': vdata.saveObject.provider }).then(res => { // 厂商配置下拉选择列表
      vdata.providerConfigList =  res.records
    })
  }

  function changeProviderConfig(e) { // 选择厂商配置
    const providerConfig = vdata.providerConfigList.find( item => item.configId === e )

    vdata.configComponent = null
    vdata.configComponent = allConfigPage[providerConfig.provider]

    // 调用组件的渲染函数
    nextTick(() => {
      configComponentRef.value.pageRender(null, vdata.saveObject.deviceType, true)
    })

    bizConfigRef.value.pageRender(null, vdata.deviceType, providerConfig.provider)
  }

  function  onClose () { // 关闭抽屉
    vdata.drawerVisible = false
  }
defineExpose({
  show
})
</script>
