<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="onReset">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="searchData['queryDateRange']" customDateRangeType="date" />
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="searchData['provider']" placeholder="设备厂商">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="item in speakerList" :key="item.value" :value="item.value">{{ item.text }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="searchData['state']" placeholder="页面类型">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">H5</a-select-option>
            <a-select-option value="1">小程序</a-select-option>
          </a-select>
        </a-form-item>
        <jeepay-text-up v-model:value="searchData['deviceName']" :placeholder="'设备名称/设备号'" />
        <jeepay-text-up v-model:value="searchData['bindQrcName']" placeholder="二维码名称/编号" />
        <jeepay-text-up  v-model:value="searchData['mchApplyName']" :placeholder="'商户名称/商户号'" />
        <jeepay-text-up v-model:value="searchData['storeId']" :placeholder="'门店名称/编号'" />
        <jeepay-text-up   v-model:value="searchData['ifName']" :placeholder="'支付通道'" />
        <jeepay-text-up  v-model:value="searchData['isvNo']" :placeholder="'渠道名称/渠道号'"  />
<!--        <a-form-item label="" class="table-search-item">-->
<!--          <a-select v-model:value="searchData['state']" placeholder="绑定状态">-->
<!--            <a-select-option value="">全部</a-select-option>-->
<!--            <a-select-option value="0">未绑定</a-select-option>-->
<!--            <a-select-option value="1">已绑定</a-select-option>-->
<!--          </a-select>-->
<!--        </a-form-item>-->
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="searchData['state']" placeholder="使用状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">禁用</a-select-option>
            <a-select-option value="1">启用</a-select-option>
          </a-select>
        </a-form-item>
<!--        <jeepay-text-up v-model:value="searchData['deviceId']" :placeholder="'设备ID'" />-->
<!--        <jeepay-text-up v-model:value="searchData['deviceNo']" :placeholder="'设备号'" />-->
<!--        <jeepay-text-up v-model:value="searchData['deviceName']" :placeholder="'应用名称'" />-->
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="searchData"
        row-key="deviceId"
        @btnLoadClose="btnLoading=false"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_DEVICE_SPEAKER_ADD')" type="primary" @click="addFunc"><plus-outlined />绑定设备</a-button>
          <a-button v-if="$access('ENT_DEVICE_SPEAKER_SHOP')" type="primary" @click="showShop()"> <PlusOutlined /> 设备商城</a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'bindType'">
            <a-tag v-if="record.bindType == 0" color="green">门店</a-tag>
            <a-tag v-if="record.bindType == 1" color="purple">码牌</a-tag>
          </template>

          <template v-if="column.key === 'bindQrcId'">
<!--            <a-tooltip   class="my-tooltip">-->
<!--              <template #title>-->
<!--                码牌ID：{{record.bindQrcId}}-->
<!--              </template>-->
<!--            </a-tooltip>-->
            {{record.bindQrcId}}
            <QrcodeOutlined v-if="record.bindQrcId" style="font-size: 16px" @click="showQrImgFunc(record.bindQrcId)" />
          </template>
          <template v-if="column.key === 'deviceNo'">
            {{ record.deviceNo }}
          </template>

          <template v-if="column.key === 'bindAppIdName'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>应用名称：{{record.bindAppIdName}}</span><br>
                <span>应用ID：{{record.appId}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.bindAppIdName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'isvNo'">
            <a-tooltip  overlayClassName="tooltip-box-name">
              <template #title>
                <span>渠道名称：{{record.isvName}}</span><br>
                <span>渠道号：{{record.isvNo}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.isvName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'state'">
            <JeepayTableColState :state="record.state" :showSwitchType="$access('ENT_DEVICE_SPEAKER_EDIT')" :onChange="(state) => { return updateState(record.deviceId, state)}" />
          </template>
          <template v-if="column.key === 'bindState'">
            <JeepayTableColState :state="record.bindState" :showSwitchType="$access('ENT_DEVICE_SPEAKER_EDIT')" :onChange="(bindState) => { return updateBindState(record.deviceId, bindState)}" />
          </template>

          <template v-if="column.key === 'provider'">
            <a-tag :key="record.provider" color="processing">
              {{ (speakerList.find(item => item.value == record.provider) as any).text || '其他' }}
            </a-tag>
          </template>


          <template v-if="column.key === 'mchApplyName'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>商户名称：{{record.mchApplyName}}</span><br>
                <span>商户号：{{record.mchApplyId}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.mchApplyName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'storeId'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>门店名称：{{record.storeName}}</span><br>
                <span>门店编号：{{record.storeId}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.storeName}}</div>
            </a-tooltip>
          </template>

          <template v-if="column.key === 'fixedFlag'">
            <span v-if="record.fixedFlag === 0">任意金额</span>
            <span v-else>￥{{ (record.fixedPayAmount / 100).toFixed(2)}}</span>
          </template>

          <template v-if="column.key === 'operation'">
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_DEVICE_SPEAKER_EDIT')" type="link" @click="editFunc(record)">修改</a-button>
              <a-button v-if="$access('ENT_DEVICE_SPEAKER_TEST')" type="link" @click="speak(record.deviceId)">播报测试</a-button>
              <a-button v-if="$access('ENT_DEVICE_SPEAKER_UNBIND') && (userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" type="link" style="color: red" @click="unBindFunc(record.deviceId)">解绑</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>
    <!-- 新增页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" />
    <!-- 测试设备组件  -->
    <TestDevice ref="testDevice" :callbackFunc="searchFunc" />
  </page-header-wrapper>
</template>
<script setup lang="ts">

import { API_URL_STORE_DEVICE, req, reqLoad, $unbindDevice ,$qrcShellViewByQrc} from '@/api/manage'
import InfoAddOrEdit from './AddOrEdit.vue'
import TestDevice from '../TestDevice.vue'
import {ref, reactive, getCurrentInstance, onMounted} from 'vue'
import provider from '../provider.json'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'

const speakerList = provider.speaker

const { $infoBox, $access ,$viewerApi} = getCurrentInstance()!.appContext.config.globalProperties

const userStore = useUserStore()
const infoAddOrEdit = ref()
const testDevice = ref()
const infoTable = ref()
const deviceType = ref(1)

let tableColumns = reactive([
  { key: 'provider', title: '设备厂商', },
  // { key: 'entryPage',  title: '页面类型', customRender: ({ record }) => {return record.entryPage == 'default' ? '默认' : record.entryPage == 'h5' ? 'H5' : '小程序'} ,},
  // { title: '设备ID', fixed: 'left', dataIndex: 'deviceId' },
  {  key: 'deviceNo',title: '设备号', dataIndex: 'deviceNo' },
  { title: '设备名称', dataIndex: 'deviceName', },
  { key: 'bindQrcId', title: '二维码编号', },
  { title: "商户名称", key: "mchApplyName", dataIndex: "mchApplyName" },
  { key: 'storeId', title: '门店名称', dataIndex: 'storeId',  },
  { key: "ifName", title: "支付通道", dataIndex: "ifName" },
  { key: "isvNo", title: "所属渠道", dataIndex: "isvNo" },
  // { key: 'bindAppIdName', dataIndex: 'bindAppIdName', title: '所属应用', },
  // { title: '门店编号', dataIndex: 'storeId',},
  { key: 'bindType', title: '绑定类型',},
  { key: 'state', title: '使用状态', },
  // { key: 'bindState', title: '绑定状态', },
  { key: 'fixedFlag', title: '固定金额', },
  { dataIndex: 'createdAt', title: '创建日期',},
  { key: 'operation', title: '操作',  fixed: 'right', align: 'center'}
])

  let btnLoading = ref(false)
  let searchData = ref({})



  function reqTableDataFunc(params: any) { // 请求table接口数据
    return req.list(API_URL_STORE_DEVICE, Object.assign({ deviceType: deviceType.value }, params))
  }
  function searchFunc () { // 点击【查询】按钮点击事件
    btnLoading.value = true
    infoTable.value.refTable(true)
  }
  function addFunc () { // 业务通用【新增】 函数
    infoAddOrEdit.value.show({ deviceType: deviceType.value })
  }
  function editFunc (record: any) { // 业务通用【修改】 函数
    infoAddOrEdit.value.show(record)
  }
  function onReset(){ //重置搜索内容
    searchData.value = {}
  }
  function speak(recordId){ //重置搜索内容
    testDevice.value.show(recordId, 1)
  }
  function showShop(){
    $infoBox.message.error('暂未开通')
  }
  function updateState (recordId, state) { // 【更新状态】
    const title = state ? '确认启用？' : '确认禁用？'
    const content = state ? '' : '禁用后该设备将无法使用！'
    return new Promise<void>((resolve, reject) => {
      $infoBox.confirmDanger(title, content, () => {
        return reqLoad.updateById(API_URL_STORE_DEVICE, recordId, { state: state }).then(res => {
          searchFunc()
          resolve()
        }).catch(err => reject(err))
      },
        () => {
        reject(new Error())
      })
    })
  }

function updateBindState (recordId, bindState) { // 【更新状态】
  const title = bindState ? '确认启用？' : '确认禁用？'
  const content = bindState ? '' : '禁用后该设备将无法使用！'
  return new Promise<void>((resolve, reject) => {
    $infoBox.confirmDanger(title, content, () => {
          return reqLoad.updateById(API_URL_STORE_DEVICE, recordId, { bindState: bindState }).then(res => {
            searchFunc()
            resolve()
          }).catch(err => reject(err))
        },
        () => {
          reject(new Error())
        })
  })
}
  
  // 解绑设备
  function unBindFunc(recordId) {
    const title = '确认解绑？'
    const content = '解绑后商户将无法使用该设备！'
    $infoBox.confirmDanger(title, content, () => {
      return $unbindDevice(recordId).then(res => {
        infoTable.value.refTable(true)
        $infoBox.message.success('解绑成功')
      })
    },() => {
      console.log(1111)
    })
  }
// 显示二维码图片
function showQrImgFunc(recordId){
  $qrcShellViewByQrc(recordId).then((res) => {
    $viewerApi({images: [res]})
  })
}

onMounted(() => {
  searchData.value['deviceName'] = useRoute().query.deviceName

  setTimeout(function (){
    searchFunc()
  },1000)
})
</script>
