<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="onReset">
        <jeepay-text-up v-if="$hasAgentEnt()" 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.batchId" :placeholder="'批次号'" />
        <jeepay-text-up v-model:value="vdata.searchData.deviceNo" :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 pluginList" :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="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 v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_ADD')" type="primary" @click="addFunc"><plus-outlined />批量新建</a-button>
          <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_ALLOT') && $hasAgentEnt()" type="primary" @click="allotBatchFunc"><partition-outlined />勾选划拨/收回</a-button>
          <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_ALLOT') && $hasAgentEnt()" type="primary" @click="allotByBatchIdFunc"><partition-outlined />批次划拨/收回</a-button>
          <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_DEL')" type="danger" @click="deleteBatchFunc"><delete-outlined />批量删除</a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <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'">
            <a-tag v-if="record.state == 0" color="orange">待激活</a-tag>
            <a-switch v-else :checked="record.state == 1 ? true : false" @change="(state) => { return updateState(record.deviceId, state)}" />
          </template>

          <template v-if="column.key === 'provider'">
            <a-popover title="厂商配置" trigger="hover">
              <template #content>
                <p>
                  配置ID：{{ record.configId }}
                  <a-button v-clipboard:copy="record.configId" v-clipboard:success="() => $infoBox.message.success('复制成功')" type="link">复制</a-button>
                </p>
                <p>
                  配置备注：{{ record.configDesc }}
                  <a-button v-clipboard:copy="record.configDesc" v-clipboard:success="() => $infoBox.message.success('复制成功')" type="link">复制</a-button>
                </p>
              </template>
              <a-tag :key="record.provider" color="processing">
                {{ (pluginList.find(item => item.value == record.provider) as any).text || '其他' }}&nbsp;<info-circle-outlined />
              </a-tag>
            </a-popover>
          </template>

          <template v-if="column.key === 'expiredTime'">
            {{ JSON.parse(record.deviceParams).expiredTime == 0 ? '长期有效' : dateUtil.formatDate(JSON.parse(record.deviceParams).expiredTime) }}
          </template>

          <template v-if="column.key === 'activeTime'">
            <template v-if="record.deviceParams && JSON.parse(record.deviceParams).activeTime">
              {{ JSON.parse(record.deviceParams).activeTime }}
            </template>
          </template>
 
          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_EDIT')" type="link" @click="editFunc(record)">修改</a-button>
              <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_EDIT')" type="link" @click="bindFunc(record)">绑定</a-button>
              <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_EDIT') && record.bindState == 1" type="link" @click="deBindFunc(record.deviceId)">解绑</a-button>
              <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_ALLOT') && $hasAgentEnt()" type="link" @click="allotFunc(record)">划拨/收回</a-button>
              <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_DEL')" type="link" style="color: red" @click="delFunc(record.deviceId)">删除</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>

    <!-- 新增页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" />
    <!-- 绑定组件  -->
    <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, req, reqLoad, $allotDevice, $batchDelDevice, $unbindDevice } from '@/api/manage'
import InfoAddOrEdit from './AddOrEdit.vue'
import Bind from '../Bind.vue'
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import dateUtil from '@/utils/dateUtil.js'
import { useRoute } from 'vue-router'
import provider from '../../provider.json'

const pluginList = provider.plugin

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

const jeepayModelAgentList = ref()
const infoAddOrEdit = ref()
const bind = ref()
const infoTable = ref()
const allotFormModel = ref()
const deviceType = 5

let tableColumns = reactive([
  // { key: 'deviceName', fixed: 'left', title: '激活码名称', dataIndex: 'deviceName', width: 280 },
  { title: '激活码', fixed: 'left', dataIndex: 'deviceNo', width: 180, minWidth: 180, maxWidth: 240 },
  { title: '批次号', dataIndex: 'batchId', width: 100 },
  { key: 'provider', title: '厂商', dataIndex: 'provider', width: 100, minWidth: 100, maxWidth: 150},
  { title: '服务商号', dataIndex: 'agentNo', agentEntCol: true, width: 140, minWidth: 140, maxWidth: 170},
  { key: 'bindState', title: '绑定商户信息', width: 260 },
  { key: 'state', title: '激活状态', width: 90, minWidth: 90, maxWidth: 110},
  { key: 'activeTime', title: '激活时间', width: 160, minWidth: 160, maxWidth: 200},
  { key: 'expiredTime', title: '有效期止', width: 120, minWidth: 120, maxWidth: 200},
  // { dataIndex: 'createdAt', title: '创建日期', width: 160, minWidth: 160, maxWidth: 230},
  { key: 'operation', title: '操作', fixed: 'right', width: 220, minWidth: 220, maxWidth: 250, align: 'center'}
])

  let btnLoading = ref(false)
  const vdata = reactive({
    allotByBatchIdVisible: false, // 批次划拨激活码弹窗
    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
    vdata.searchData.configId = useRoute().query.configId
    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 bindFunc (record: any) { // 绑定激活码函数
    bind.value.show(record)
  }
  function deleteBatchFunc() {  // 批量删除
    if (vdata.allotDeviceIdList.length < 1) {
      $infoBox.message.error('请选择激活码')
    } else {
      $infoBox.confirmDanger('确认删除？', '', () => {
        $batchDelDevice(vdata.allotDeviceIdList.join(',')).then((res: any) => {
          infoTable.value.refTable(true)
          $infoBox.message.success('删除成功')
        })
      })
    }
  }
  function delFunc (recordId: any) { // 业务通用【删除】 函数
    $infoBox.confirmDanger('确认删除？', '', () => {
        $batchDelDevice(recordId).then((res: any) => {
            infoTable.value.refTable(true)
            $infoBox.message.success('删除成功')
          })
    })
  }
  function onReset(){ //重置搜索内容
    vdata.searchData = {}
  }
  function updateState (recordId, state) { // 【更新状态】
    return new Promise<void>((resolve, reject) => {
      $infoBox.confirmDanger('确认解除激活？', '解除激活后，该激活码将不可用！', () => {
        return reqLoad.updateById(API_URL_STORE_DEVICE, recordId, { state: state }).then(res => {
          searchFunc()
          resolve()
        }).catch(err => reject(err))
      },
        () => {
        reject(new Error())
      })
    })
  }

    // 按批次号划拨
  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 infoTableSelectChangeFunc(selectedRowKeys, selectedRows) {
    
    vdata.allotDeviceIdList = selectedRowKeys
    // vdata.allotDeviceIdList = []

    // const allotRows = selectedRows.filter(record => record.bindState == 0)

    // let allotDeviceIds = [] as any
    // allotRows.forEach(item => allotDeviceIds.push(item.deviceId))
    // vdata.allotDeviceIdList = allotDeviceIds
  }

  // 勾选划拨激活码
  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 deBindFunc(recordId) {
    const title = '确认解绑？'
    const content = '解绑后商户将无法使用该激活码！'
    $infoBox.confirmDanger(title, content, () => {
      return $unbindDevice(recordId).then(res => {
        infoTable.value.refTable(true)
        $infoBox.message.success('解绑成功')
      })
    })
  }

  // 划拨/收回选择完成
  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>
