<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="onReset">
        <jeepay-text-up v-model:value="vdata.searchData.storeId" :placeholder="'门店ID'" />
        <jeepay-text-up v-model:value="vdata.searchData.deviceNo" :placeholder="'设备号'" />
        <jeepay-text-up v-model:value="vdata.searchData.alipayShopId" :placeholder="'蚂蚁店铺ID'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.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>
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="false"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        row-key="deviceId"
        @btnLoadClose="btnLoading=false"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_DEVICE_RUYI_ADD')" type="primary" @click="addFunc"><plus-outlined />新建</a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'state'">
            <JeepayTableColState :state="record.state" :showSwitchType="$access('ENT_DEVICE_RUYI_EDIT')" :onChange="(state) => { return updateState(record.deviceId, state)}" />
          </template>
          <template v-if="column.key === 'alipayBindState'">
            <a-tag v-if="record.alipayBindState==1" color="green">已绑定</a-tag>
            <a-span v-if="record.alipayBindState==1 && record.alipayShopId">蚂蚁店铺ID：{{ record.alipayShopId }}</a-span>
            <a-tag v-else-if="record.alipayBindState==0" color="red">未绑定</a-tag>
          </template>

          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_DEVICE_RUYI_EDIT')" type="link" @click="editFunc(record)">修改</a-button>
              <a-button v-if="$access('ENT_DEVICE_RUYI_BIND')" type="link" @click="alipayIotBindShowFunc(record)">绑定蚂蚁店铺</a-button>
              <a-button v-if="$access('ENT_DEVICE_RUYI_BIND') && record.alipayBindState == 1" type="link" style="color: red" @click="alipayIotUnBindFunc(record.deviceId)">解绑蚂蚁店铺</a-button>
              <a-button v-if="$access('ENT_DEVICE_RUYI_EDIT') && (userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" type="link" style="color: red" @click="deBindFunc(record.deviceId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <!-- 新增页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" />

    <!-- 绑定蚂蚁店铺弹窗  -->
    <a-modal :visible="vdata.alipayIotBindShow" title="绑定/解绑蚂蚁店铺" @ok="alipayIotBindFunc(vdata.alipayIotBindObject.deviceId, 1)" @cancel="() => vdata.alipayIotBindShow = false">
      <a-form ref="alipayIotBindModel" :model="vdata.alipayIotBindObject" layout="vertical">
        <a-col :span="24">
          <a-form-item label="选择门店" name="storeId">
            <a-select v-model:value="vdata.alipayIotBindObject.storeId" placeholder="请选择门店">
              <a-select-option v-for="(d, index) in vdata.storeList" :key="index" v-model:value="d.storeId">
                {{ d.storeName }} 【蚂蚁店铺ID：{{ d.alipayShopId }} 】
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-form>
    </a-modal>
  </page-header-wrapper>
</template>
<script setup lang="ts">
import { API_URL_STORE_DEVICE, API_URL_MCH_STORE_LIST, API_ALIPAY_IOT, req, reqLoad, $unbindDevice } from '@/api/manage'
import InfoAddOrEdit from '../CommonAddOrEdit.vue'
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'

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

const infoAddOrEdit = ref()
const infoTable = ref()
const userStore = useUserStore()

const deviceType = 7

let tableColumns = reactive([
  { title: '设备号', fixed: 'left', dataIndex: 'deviceNo' },
  { title: '门店编号', dataIndex: 'storeId' },
  { key: 'appId', dataIndex: 'appId', title: '应用ID' },
  { key: 'state', title: '状态' },
  { key: 'alipayBindState', title: '蚂蚁店铺绑定状态' },
  { dataIndex: 'createdAt', title: '创建日期'},
  { key: 'operation', title: '操作', fixed: 'right', align: 'center'}
])

  let btnLoading = ref(false)
  const vdata = reactive({
    searchData: {} as any,

    alipayIotBindShow: false,
    alipayIotBindObject: {} as any,
    storeList: {} as any,
  }) as any

  onMounted(() => {
    vdata.searchData.mchNo = useRoute().query.mchNo
    searchFunc()
  })

  function reqTableDataFunc(params: any) { // 请求table接口数据
    return req.list(API_URL_STORE_DEVICE, Object.assign({ deviceType: deviceType }, params))
  }
  function searchFunc () { // 点击【查询】按钮点击事件
    btnLoading.value = true
    infoTable.value.refTable(true)
  }
  function addFunc () { // 业务通用【新增】 函数
    infoAddOrEdit.value.show({ deviceType: deviceType })
  }
  function editFunc (record: any) { // 业务通用【修改】 函数
    infoAddOrEdit.value.show(record)
  }
  function alipayIotBindShowFunc (record: any) { // 蚂蚁店铺绑定管理
    req.list(API_URL_MCH_STORE_LIST, { 'pageSize': -1, 'alipayShopStatus': '99' }).then(res => { // 门店下拉选择列表
      vdata.storeList =  res.records || []
      if (vdata.storeList.length > 0 && vdata.storeList.some(i => i.storeId == record.storeId)) {
        vdata.alipayIotBindObject.storeId = record.storeId
      }
    })
    vdata.alipayIotBindObject.deviceId = record.deviceId
    vdata.alipayIotBindObject.alipayBindState = record.alipayBindState

    vdata.alipayIotBindShow = true
  }
  function alipayIotBindFunc(recordId, alipayBindState) { // 绑定蚂蚁店铺设备
    vdata.alipayIotBindObject.alipayBindState = alipayBindState
    reqLoad.add(API_ALIPAY_IOT + '/bind/' + recordId, vdata.alipayIotBindObject).then(res => {
      infoTable.value.refTable(true)
      $infoBox.message.success('操作成功')
      vdata.alipayIotBindShow = false
    }).catch(err =>console.log(err))
  }
  function alipayIotUnBindFunc(recordId) { // 解绑蚂蚁店铺设备
    $infoBox.confirmDanger('解绑蚂蚁店铺', '确定解绑蚂蚁店铺吗？', () => {
      return alipayIotBindFunc(recordId, 0)
    })
  }
  function onReset(){ //重置搜索内容
    vdata.searchData = {}
  }
  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 deBindFunc(recordId) {
    const title = '确认解绑？'
    const content = '解绑后商户将无法使用该设备！'
    $infoBox.confirmDanger(title, content, () => {
      return $unbindDevice(recordId).then(res => {
        infoTable.value.refTable(true)
        $infoBox.message.success('解绑成功')
      })
    },() => {
      console.log(1111)
    })
  }

</script>
