<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchConditionNum="6" :searchFunc="searchFunc" :resetFunc="onReset">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="vdata.searchData['queryDateRange']" customDateRangeType="date" />
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.qrcType" 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-option value="2">实体立牌</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.entryPage" placeholder="页面类型">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="default">默认</a-select-option>
            <a-select-option value="h5">H5</a-select-option>
            <a-select-option value="lite">小程序</a-select-option>
          </a-select>
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.qrcAlias" placeholder="二维码名称/编号" />
        <jeepay-text-up  v-model:value="vdata.searchData['mchApplyName']" :placeholder="'商户名称/商户号'" />
        <jeepay-text-up v-model:value="vdata.searchData.storeId" placeholder="门店名称/门店编号" />
        <jeepay-text-up   v-model:value="vdata.searchData['ifName']" :placeholder="'支付通道'" />
        <jeepay-text-up  v-model:value="vdata.searchData['isvNo']" :placeholder="'渠道名称/渠道号'"  />
        <jeepay-text-up v-model:value="vdata.searchData.appId" placeholder="应用名称/应用ID" />


        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.bindState" 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>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        rowKey="qrcId"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_MCH_QR_CODE_ADD')" type="primary" @click="addOrEditFunc()"><PlusOutlined /> 新建电子码</a-button>
          <a-button v-if="$access('ENT_MCH_QR_CODE_SOILD_ADD')" type="primary" @click="showBind()"> <PlusOutlined /> 绑定实体码</a-button>
          <a-button v-if="$access('ENT_MCH_QR_CODE_SHOP')" type="primary" @click="showShop()"> <PlusOutlined /> 设备商城</a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'qrcId'">
            {{ record.qrcId }}
            <QrcodeOutlined style="font-size: 16px" @click="showQrImgFunc(record.qrcId)" />
          </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 === '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 === '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 === 'qrcType'">
            <a-tag v-if="record.qrcType == 0" color="blue">电子码牌</a-tag>
            <a-tag v-if="record.qrcType == 1" color="orange">实体码牌</a-tag>
            <a-tag v-if="record.qrcType == 2" color="green">实体立牌</a-tag>
          </template>
          <template v-if="column.key === 'bindState'">
            <JeepayTableColState :state="record.bindState" :showSwitchType="$access('ENT_MCH_QR_CODE_EDIT')" :onChange="(state) => { return updateState(record.qrcId, state)}" />
          </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 === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_MCH_QR_CODE_VIEW')" type="link" @click="showQrImgFunc(record.qrcId)">详情</a-button>
              <a-button v-if="$access('ENT_MCH_QR_CODE_EDIT')" type="link" @click="addOrEditFunc(record.qrcId)">修改</a-button>
              <a-button v-if="$access('ENT_MCH_QR_CODE_EDIT') && record.qrcBelongType == 2 && record.bindState == 1 && (userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" type="link" style="color: red" @click="unBindFunc(record.qrcId)">解绑</a-button>
              <a-button v-if="$access('ENT_MCH_QR_CODE_EDIT') && record.qrcBelongType == 2 && record.bindState == 1 && (userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" type="link" @click="getBindDeviceFunc(record.qrcId)">关联设备</a-button>
              <a-button v-if="$access('ENT_MCH_QR_CODE_DEL') && record.qrcBelongType == 1" type="link" style="color: red" @click="delFunc(record.qrcId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>

      <AddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" />
      <Bind ref="bindRef" :callbackFunc="searchFunc" />
      <JeepayQrcDeviceList ref="jeepayQrcDeviceListRef" sysType="MCH" />
    </a-card>
  </page-header-wrapper>
</template>
<script setup lang="ts">
import AddOrEdit from './AddOrEdit.vue'
import Bind from './Bind.vue'
import {API_URL_MCH_QR_CODE_LIST, req, reqLoad, $qrcShellViewByQrc, $unbindQrc} from '@/api/manage'
import {ref, reactive, getCurrentInstance, onMounted} from 'vue'
import { useUserStore } from '@/store/modules/user'
import {useRoute} from "vue-router";

// 导入全局函数
const { $infoBox, $access, $viewerApi } = getCurrentInstance()!.appContext.config.globalProperties

const userStore = useUserStore()
// infoTable组件
const infoTable = ref()

const infoAddOrEdit = ref()

const bindRef = ref()

const dateRangePicker = ref()

const jeepayQrcDeviceListRef = ref()

// eslint-disable-next-line no-unused-vars
const tableColumns = ref([
  // { key: 'entryPage',  title: '获取方式', customRender: ({ record }) => {return record.qrcBelongType == 1 ? '自制' : '下发' }, },
  { key: 'qrcType', title: '码牌类型', },
  { key: 'entryPage',  title: '页面类型', customRender: ({ record }) => {return record.entryPage == 'default' ? '默认' : record.entryPage == 'h5' ? 'H5' : '小程序'} ,},
  { key: 'qrcId', title: '二维码编号', },
  { key: 'qrcAlias', dataIndex: 'qrcAlias', 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: '所属应用', },
  // { key: 'qrcState', title: '使用状态（无字段）', },
  { key: 'bindState', title: '使用状态', },
  { key: 'fixedFlag', title: '固定金额', },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期', },
  { key: 'op', title: '操作', fixed: 'right', align: 'center', }
])


const vdata : any = reactive({
  searchData: {},

})

function searchFunc () {
  // vdata.btnLoading = true
  infoTable.value.refTable(true)
}
// 请求table接口数据
function reqTableDataFunc (params) {
  return req.list(API_URL_MCH_QR_CODE_LIST, params)
}


// 新增 or 修改函数
function addOrEditFunc(recordId?){
  infoAddOrEdit.value.show(recordId)
}


// 显示二维码图片
function showQrImgFunc(recordId){
  $qrcShellViewByQrc(recordId).then((res) => {
    $viewerApi({images: [res]})
  })
}
onMounted(()=>{
  if(useRoute().query.storeId !== undefined){
    Object.assign(vdata.searchData,{storeId:useRoute().query.storeId})
    setTimeout(function (){
      searchFunc()
    },500)
  }
  if(useRoute().query.mchApplyId !== undefined){
    Object.assign(vdata.searchData,{mchApplyId:useRoute().query.mchApplyId})
    setTimeout(function (){
      searchFunc()
    },500)
  }
})
// 删除
function delFunc(recordId){
  $infoBox.confirmDanger('确认删除？', '', () => {
    req.delById(API_URL_MCH_QR_CODE_LIST, recordId).then(res => {
      $infoBox.message.success('删除成功')
      searchFunc()
    })
  },() => {
    console.log(1111)
  })
}


function  updateState (recordId, state) { // 【更新状态】

  const title = state === 1 ? '确认[启用]？' : '确认[停用]？'
  return new Promise<void>((resolve, reject) => {
    $infoBox.confirmDanger(title, '', () => {
          return reqLoad.updateById(API_URL_MCH_QR_CODE_LIST, recordId, { qrcState: state }).then(res => {
            searchFunc()
            resolve()
          }).catch(err => reject(err))
        },
        () => {
          reject(new Error())
        })
  })
}
// 绑定码牌
function showBind() {
  bindRef.value.show()
}
function showShop(){
  $infoBox.message.error('暂未开通')
}

// 解绑
function unBindFunc(recordId) {
  const title = '确认解绑？'
  const content = '解绑后商户将无法使用该码牌！'
  $infoBox.confirmDanger(title, content, () => {
    return $unbindQrc(recordId).then(res => {
      infoTable.value.refTable(true)
      $infoBox.message.success('解绑成功')
    })
  },() => {
    console.log(1111)
  })
}

// 受支持的设备
function getBindDeviceFunc(recordId) {
  jeepayQrcDeviceListRef.value.show(recordId)
}

function onReset(){
  //重置搜索内容
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { queryDateRange: '' }
}
</script>
