<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="vertical" :rules="vdata.rules">
      <a-row justify="space-between" type="flex">
        <a-col :span="11">
          <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="d in vdata.providerList" :key="d.value" v-model:value="d.value">
                {{ d.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="状态" name="state">
            <a-radio-group v-model:value="vdata.saveObject['state']">
              <a-radio :value="1">启用</a-radio>
              <a-radio :value="0">禁用</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row justify="space-between" type="flex">
        <a-col :span="16">
          <a-form-item label="厂商配置备注（备注会在商户侧回显）" name="configDesc">
            <a-input v-model:value="vdata.saveObject.configDesc" 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>
  </a-drawer>
</template>

<script lang="ts" setup>
import BsjConfig from '@/views/device/providerconfig/diy/BsjConfig.vue'
import ZgwlConfig from '@/views/device/providerconfig/diy/ZgwlConfig.vue'
import FeConfig from '@/views/device/providerconfig/diy/FeConfig.vue'
import PsConfig from '@/views/device/providerconfig/diy/PsConfig.vue'
import PosConfig from '@/views/device/providerconfig/diy/PosConfig.vue'
import PluginConfig from '@/views/device/providerconfig/diy/PluginConfig.vue'
import ZwConfig from '@/views/device/providerconfig/diy/ZwConfig.vue'
import JsdConfig from '@/views/device/providerconfig/diy/JsdConfig.vue'
import LlznConfig from '@/views/device/providerconfig/diy/LlznConfig.vue'
import YlyConfig from '@/views/device/providerconfig/diy/YlyConfig.vue'
import LklsConfig from '@/views/device/providerconfig/diy/LklsConfig.vue'
import { API_URL_DEVICE_PROVIDER, req } from '@/api/manage'
import { defineProps, reactive, ref, getCurrentInstance, nextTick } from 'vue'
import provider from '../provider.json'

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

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

  /** 定义厂商参数配置组件 **/
  const allConfigPage = {
    'bsj': BsjConfig,
    'zgwl': ZgwlConfig,
    'fe': FeConfig,
    'ps': PsConfig,
    'zw': ZwConfig,
    'jsd': JsdConfig,
    'llzn': LlznConfig,
    'yly': YlyConfig,
    'lkls': LklsConfig,
  }

  /** 定义云喇叭厂商 **/ 
  const speakerProviderList = provider.speaker
  /** 定义云打印厂商 **/ 
  const printerProviderList = provider.printer
   /** 定义扫码POS厂商 **/ 
  const posProviderList = provider.pos
   /** 定义收银插件厂商 **/ 
  const pluginProviderList = provider.plugin

  const  vdata = reactive({
    configComponent: null as any, // 动态组件 当前配置组件
    deviceType: null,
    providerList: [] as any, // 厂商列表
    btnLoading: false,
    isAdd: true, // 新增 or 修改页面标志
    saveObject: {} as any, // 数据对象
    recordId: null, // 更新对象ID
    drawerVisible: false, // 是否显示弹层/抽屉
    rules: {
      provider: [{ required: true, message: '请选择厂商', trigger: 'blur' }],
      configDesc: [{ required: true, message: '请输入厂商配置备注', trigger: 'blur' }]
    }
  })

  function show (record: any) { // 弹层打开事件
  
    vdata.isAdd = !record.configId
    vdata.deviceType = record.deviceType // 1-云喇叭  2-打印机  3-扫码POS 4-智能POS 5-收银插件

    vdata.saveObject = { 'state': 1, 'deviceType': record.deviceType } // 数据清空
    vdata.providerList = record.deviceType==1 ? speakerProviderList : record.deviceType==2 ? printerProviderList : record.deviceType==3 ? posProviderList : pluginProviderList
    vdata.configComponent = null

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

    if (vdata.deviceType == 3) {
      vdata.configComponent = PosConfig
    } else if (vdata.deviceType == 5) {
      vdata.configComponent = PluginConfig
    } else {
      vdata.configComponent = allConfigPage[record.provider]
    }

    if (vdata.isAdd) {
      vdata.drawerVisible = true // 立马展示弹层信息
    } else { // 修改信息 延迟展示弹层
      vdata.recordId = record.configId

      req.getById(API_URL_DEVICE_PROVIDER, vdata.recordId).then((res: any) => {
        vdata.drawerVisible = true // 立马展示弹层信息
        if(res){
          vdata.saveObject = res

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

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

        // 赋值
        vdata.saveObject.providerParams = JSON.stringify(providerParams || '{}' )

        // 请求接口
        if (vdata.isAdd) {
          req.add(API_URL_DEVICE_PROVIDER, vdata.saveObject).then((res: any) => {
            successFunc('保存成功')
          }).catch((err: any) => {
            vdata.btnLoading = false
          })
        } else {
          req.updateById(API_URL_DEVICE_PROVIDER, 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(e: string) { // 选择厂商
    if (vdata.deviceType == 3) {
      vdata.configComponent = PosConfig
    } else if (vdata.deviceType == 5) {
      vdata.configComponent = PluginConfig
    } else {
      vdata.configComponent = allConfigPage[e]
    }
  }

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