<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="onReset">
        <jeepay-text-up v-model:value="vdata.searchData['mchServiceName']" :placeholder="'服务商号/名称'" />
<!--        <JeepaySearchInfoInput v-model:value="vdata.searchData['mchUserName']" placeholder="用户号" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />-->

        <jeepay-text-up  v-model:value="vdata.searchData['mchUserName']"  :placeholder="'用户号/名称/手机号'"  />
        <jeepay-text-up v-model:value="vdata.searchData.storeId" :placeholder="'门店名称/编号'" />
        <!--        <jeepay-text-up v-model:value="vdata.searchData.deviceNo" :placeholder="'设备号'" />-->
        <jeepay-text-up v-model:value="vdata.searchData['deviceName']" :placeholder="'设备名称/编号'" />
        <jeepay-text-up  v-model:value="vdata.searchData['mchApplyName']" :placeholder="'商户名称/商户号'" />
        <jeepay-text-up v-model:value="vdata.searchData['appId']" :placeholder="'应用名称'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.provider" placeholder="所属支付接口">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="item in vdata.ifCodeList" :key="item.ifCode" :value="item.ifCode">{{ item.ifName }}</a-select-option>
          </a-select>
        </a-form-item>
        <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>
        <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"
        :init-data="false"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        :rowSelection="{ type: 'checkbox', selectedRowKeys: vdata.allotDeviceIdList, onChange: infoTableSelectChangeFunc }"
        row-key="deviceId"
        @btnLoadClose="btnLoading=false"
      >
        <template #topBtnSlot>
          <a-button type="primary" @click="addFunc"><plus-outlined />申请新设备</a-button>
          <a-button v-if="$access('ENT_DEVICE_SPEAKER_DEVICE_ALLOT')" type="primary" @click="allotBatchFunc"><partition-outlined />勾选划拨/收回</a-button>
          <!-- <a-button v-if="$access('ENT_DEVICE_SPEAKER_DEVICE_ALLOT')" type="primary" @click="allotByBatchIdFunc"><partition-outlined />批次划拨/收回</a-button> -->
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'appName'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>应用名称：{{record.appName}}</span><br>
                <span>应用ID：{{record.appId}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.appName}}</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 === 'mchServiceName'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>服务商名称：{{record.mchServiceName}}</span><br>
                <span>服务商号：{{record.agentNo}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.mchServiceName}}</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 === 'bindState'">
            <template v-if="record.bindState == 0"><exclamation-circle-outlined />未绑定</template>
            <template v-else>已绑定商户: {{ record.mchNo }} ({{ record.mchName }})<br>应用： {{ record.appId }}<br>门店： {{ record.storeId }} ({{ record.storeName }})</template>
          </template>

          <template v-if="column.key === 'state'">
            <JeepayTableColState :state="record.state" :showSwitchType="$access('ENT_DEVICE_AUTO_POS_EDIT')" :onChange="(state) => { return updateState(record.deviceId, state)}" />
          </template>

          <template v-if="column.key === 'mchUserName'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>用户名称：{{record.mchUserName}}</span><br>
                <span>用户手机号：{{record.mchUserPhone}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.mchUserName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'provider'">
            <a-tag :key="record.provider" color="processing">
              {{ (vdata.ifCodeList.find(item => item.ifCode == record.provider) as any)?.ifName || '其他' }}
            </a-tag>
          </template>

          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="($access('ENT_DEVICE_AUTO_POS_EDIT') && record.isSelf)" type="link" @click="bindFunc(record)">绑定</a-button>
              <a-button v-if="($access('ENT_DEVICE_AUTO_POS_EDIT') && record.bindState == 1 && record.isSelf)" type="link" @click="deBindFunc(record.deviceId)">解绑</a-button>
              <a-button v-if="$access('ENT_DEVICE_SPEAKER_DEVICE_ALLOT')" type="link" @click="allotFunc(record)">划拨/收回</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <!-- 批次号划拨弹窗 -->
    <a-modal v-model:visible="vdata.allotByBatchIdVisible" title="按批次号划拨设备" @ok="allotOk">
      <a-form ref="allotFormModel" :model="vdata.allotObject" layout="vertical" :rules="vdata.allotRules">
        <a-form-item label="批次号：" name="batchId">
          <a-input v-model:value="vdata.allotObject.batchId" placeholder="请输入批次号" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 绑定组件  -->
    <Bind ref="bind" :callbackFunc="searchFunc" />
    <!-- 选择划拨服务商  -->
    <JeepayModelAgentList ref="jeepayModelAgentList" showType="AGENT" @selectFinishFunc="searchAgentFinishFunc" />
  </page-header-wrapper>
</template>
<script setup lang="ts">
import { API_URL_STORE_DEVICE, API_URL_IFDEFINES_LIST, req, reqLoad, $unbindDevice, $allotDevice } from '@/api/manage'
import Bind from './Bind.vue'
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import { useRoute } from 'vue-router'

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

const bind = ref()
const infoTable = ref()
const jeepayModelAgentList = ref()
const allotFormModel = ref()

const deviceType = 4

let tableColumns = reactive([
  // { title: '设备号', fixed: 'left', dataIndex: 'deviceNo',  },
  // { key: 'provider', title: '所属支付接口', dataIndex: 'provider'},
  // { title: '服务商号', dataIndex: 'agentNo', agentEntCol: true},
  // { key: 'bindState', title: '绑定商户信息' },
  // { key: 'state', title: '状态'},
  // { dataIndex: 'createdAt', title: '创建日期', },
  // { key: 'operation', title: '操作', fixed: 'right',  align: 'center'}

  { title: '设备号', fixed: 'left', dataIndex: 'deviceNo' },
  { key: 'provider', title: '所属支付接口', dataIndex: 'provider', },
  { key: 'mchUserName', title: '用户名称', dataIndex: 'mchUserName'},
  { key: 'mchServiceName', title: '服务商名称', dataIndex: 'mchServiceName' },
  { title: "商户名称", key: "mchApplyName", dataIndex: "mchApplyName" },
  { key: 'storeId',title: '门店名称', dataIndex: 'storeId',},
  { key: 'appName', dataIndex: 'appName', title: '所属应用', },
  // { key: 'bindState', title: '绑定状态',},
  { key: 'state', title: '使用状态',},
  { dataIndex: 'createdAt', title: '创建日期',},
  { key: 'operation', title: '操作', fixed: 'right',  align: 'center'}
])

  let btnLoading = ref(false)
  const vdata = reactive({
    ifCodeList: [], // 通道列表
    searchData: {} as any,
    allotObject: {
      agentNo: null, // 划拨服务商号
      allotType: null, // 划拨类型：select-勾选划拨  batch-批次划拨
      batchId: null, // 批次号，划拨类型为 batch-批次划拨 时必填
      allotDeviceIds: [] as any, // 要划拨的设备ID，划拨类型为 select-勾选划拨 时必填
    } as any, // 划拨设备对象
    allotDeviceIdList: [] as any, // 要划拨的设备ID，划拨类型为 select-勾选划拨 时必填
    allotRules: {
      batchId: [{ required: true, message: '请输入批次号', trigger: 'blur' }]
    }
  }) as any

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

    req.list(API_URL_IFDEFINES_LIST, { 'state': 1 }).then(res => { // 通道下拉选择列表
      vdata.ifCodeList = res.filter(r => r.wayCodes.some(s => s.wayCode == 'AUTO_POS' || s.wayCode == 'OUT_TRADE'))
    })
  })

  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 () { // 业务通用【新增】 函数
    $infoBox.message.success('请联系运营平台申请')
  }
  function bindFunc (record: any) { // 绑定设备函数
    bind.value.show(record)
  }
  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('解绑成功')
      })
    })
  }
// 表格多选
function infoTableSelectChangeFunc(selectedRowKeys, selectedRows) {
    vdata.allotDeviceIdList = selectedRowKeys
  }

  // 按批次号划拨
  function allotByBatchIdFunc() {
    vdata.allotObject.allotType = 'batch'
    vdata.allotObject.batchId = ''

    vdata.allotByBatchIdVisible = true
  }

  // 按批次号划拨，批次号输入完成
  function allotOk() {
    allotFormModel.value.validate().then((valid: any) =>{
      vdata.allotByBatchIdVisible = false
      jeepayModelAgentList.value.show()
    })
  }

   // 勾选划拨设备
   function allotBatchFunc() {
    if (vdata.allotDeviceIdList.length < 1) {
      $infoBox.message.error('请选择设备')
    } else {
      vdata.allotObject.allotType = 'select'
      jeepayModelAgentList.value.show()
    }
  }

  // 划拨单个设备
  function allotFunc(record) {
    vdata.allotObject.allotType = 'select'
    vdata.allotDeviceIdList = []
    vdata.allotDeviceIdList.push(record.deviceId)

    jeepayModelAgentList.value.show()
  }

   // 划拨/收回选择完成
   function searchAgentFinishFunc(selectObject) {

    vdata.allotObject.agentNo = selectObject[0]
    vdata.allotObject.allotOrRecover = selectObject[1]

    if (vdata.allotObject.allotOrRecover == 'allot' && !vdata.allotObject.agentNo) {
      $infoBox.message.error('请选择服务商')
      return
    }

    if (vdata.allotDeviceIdList.length > 0) {
      vdata.allotObject.allotDeviceIds = vdata.allotDeviceIdList.join(',')
    }

    $allotDevice(vdata.allotObject).then(res => {
      vdata.allotDeviceIdList = [] // 清空多选
      $infoBox.message.success('保存成功')
      jeepayModelAgentList.value.close()
      searchFunc()
    })
  }
</script>
