<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 v-if="vdata.isAdd" justify="space-between" type="flex">
        <a-col :span="11">
          <a-form-item label="设备号" name="deviceNo">
            <a-input v-model:value="vdata.saveObject.deviceNo" placeholder="请输入设备号" />
            <div v-if="vdata.checkMsg" :style="vdata.checkCode == 1 ? {'color' : 'green'} : {'color' : 'red'}">{{ vdata.checkMsg }}</div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" ">
            <a-button type="primary" @click="checkFunc">查询设备是否允许绑定</a-button>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-if="vdata.providerConfigList.length > 0 && vdata.checkCode == 2" 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="请选择厂商">
              <a-select-option v-for="d in vdata.providerConfigList" :key="d.provider" v-model:value="d.provider">
                【{{ (allList.find(item => item.value == d.provider) as any).text || '其他' }}】{{ d.configDesc }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      
      <a-row justify="space-between" type="flex">
        <a-col :span="11">
          <a-form-item label="设备名称" name="deviceName">
            <a-input v-model:value="vdata.saveObject.deviceName" placeholder="请输入设备名称" />
          </a-form-item>
        </a-col>

        <a-col :span="11">
          <a-form-item label="选择门店" name="storeId">
            <a-select v-model:value="vdata.saveObject.storeId" placeholder="请选择门店" show-search @search="handleBankChange" >
              <a-select-option v-for="d in vdata.filteredStoreInfoList" :key="d.storeId" v-model:value="d.storeId">
                {{ d.storeName }} [{{ d.storeId }}]
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col v-if="vdata.deviceType != 1 && vdata.deviceType != 2 && vdata.deviceType != 3" :span="11">
          <a-form-item label="选择应用" name="appId">
            <a-select v-model:value="vdata.saveObject.appId" placeholder="请选择应用" show-search @search="handleAppidChange">
              <a-select-option v-for="d in vdata.filteredAppInfoList" :key="d.appId" v-model:value="d.appId">
                {{ d.appName }} [{{ d.appId }}]
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col v-if="vdata.deviceType != 5" :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-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 v-if="vdata.deviceType == 2 && !vdata.isAdd" ref="bizConfigRef" />
  </a-drawer>
</template>

<script lang="ts" setup>
import { API_URL_STORE_DEVICE, API_URL_MCH_STORE_LIST, API_URL_MCH_APP, req, $checkDevice } from '@/api/manage'
import { defineProps, reactive, ref, getCurrentInstance } from 'vue'
import BizConfig from '@/views/device/BizConfig.vue'
import provider from './provider.json'

const allList = provider.all

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

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

  const  vdata = reactive({
    providerConfigList: [] as any, // 厂商列表
    storeList: [] as any, // 门店列表
    filteredStoreInfoList: [] as any, // 门店列表
    appList: [] as any, // 应用列表
    filteredAppInfoList: [] as any, // 应用列表
    btnLoading: false,
    isAdd: true, // 新增 or 修改页面标志
    deviceType: 1, // 1-云喇叭 2-云打印 3-扫码POS
    saveObject: {} as any, // 数据对象
    recordId: null, // 更新对象ID
    drawerVisible: false, // 是否显示弹层/抽屉
    rules: {
      provider: [{ required: true, message: '请选择厂商', trigger: 'blur' }],
      storeId: [{ required: true,message: '请选择门店', trigger: 'blur' }],
      deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
      deviceNo: [{ required: true, message: '请输入设备号', trigger: 'blur' }],
      appId: [{
        required: false,
        trigger: 'blur'
      }, {
        validator: async (rule, value) => {
          if ((vdata.deviceType != 1 && vdata.deviceType != 2) && !value) {
              return Promise.reject('请选择应用')
          }
        }
      }] 
    }
  }) as any

  function show (record: any) { // 弹层打开事件
  
    vdata.isAdd = !record.deviceId
    vdata.deviceType = record.deviceType // 设备类型deviceType： 1-云喇叭, 2-云打印，3-扫码POS，4-智能POS
    vdata.provider = record.provider

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

    vdata.providerConfigList = []
    vdata.checkMsg = ''

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

    req.list(API_URL_MCH_STORE_LIST, { 'pageSize': -1 }).then(res => { // 门店下拉选择列表
      vdata.storeList =  res.records
      vdata.filteredStoreInfoList =  res.records
    })
    req.list(API_URL_MCH_APP, { 'pageSize': -1 }).then(res => { // 应用下拉选择列表
      vdata.appList =  res.records
      vdata.filteredAppInfoList =  res.records

    })
    
    if (!vdata.isAdd) { // 修改信息 延迟展示弹层
      vdata.recordId = record.deviceId

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

          // 业务参数配置组件
          if(vdata.deviceType == 2) {
            let bizConfig = JSON.parse(vdata.saveObject.bizConfigParams || '{}' )
            bizConfigRef.value.pageRender(bizConfig, vdata.deviceType, vdata.provider)
          }
        }
      })
    } 
    vdata.drawerVisible = true // 立马展示弹层信息
  }

  function  handleOkFunc () { // 点击【确认】按钮事件
    infoFormModel.value.validate().then((valid: any) =>{
      if(vdata.deviceType == 2 && !vdata.isAdd) {
        bizConfigRef.value.getConfigParams().then((bizConfigParams: any) => {
          // 赋值
          vdata.saveObject.bizConfigParams = bizConfigParams || ''
          addOrEdit()
        })
      } else {
        addOrEdit()
      }
    })
  }

  function addOrEdit() {
    vdata.btnLoading = true
    // 请求接口
    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 checkFunc() {
    vdata.checkMsg = ''

    $checkDevice(vdata.saveObject.deviceNo, vdata.saveObject.deviceType).then(res => {
      vdata.checkCode = res.checkCode
      vdata.checkMsg = res.checkMsg

      if (vdata.checkCode == 2) {
        vdata.providerConfigList = res.deviceList
      }
    })
  }

  function  onClose () { // 关闭抽屉
    vdata.drawerVisible = false
  }

const handleBankChange = (value) => {
  vdata.filteredStoreInfoList = [];
  vdata.storeList.forEach((item: { storeName: string | any[], storeId:  any[] },index) => {
    if (item.storeName.includes(value) || item.storeId.toString().includes(value) ) {
      vdata.filteredStoreInfoList.push(vdata.storeList[index]);
    }
  });
};

const handleAppidChange = (value) => {
  vdata.filteredAppInfoList = [];
  vdata.appList.forEach((item: { appName: string | any[], appId: string | any[] },index) => {
    if (item.appName.includes(value) || item.appId.includes(value) ) {
      vdata.filteredAppInfoList.push(vdata.appList[index]);
    }
  });
};
defineExpose({
  show
})
</script>
