<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchConditionNum="4" :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['mchUserName']"  :placeholder="'用户号/名称/手机号'"  />
        <jeepay-text-up v-model:value="vdata.searchData['mchServiceName']" :placeholder="'服务商号'" />
<!--        <JeepaySearchInfoInput v-model:value="vdata.searchData['mchNo']" placeholder="用户号" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />-->
        <jeepay-text-up v-model:value="vdata.searchData.qrcAlias" placeholder="二维码名称/编号" />
        <jeepay-text-up  v-model:value="vdata.searchData['mchApplyId']" :placeholder="'商户名称/商户号'" />
        <jeepay-text-up v-model:value="vdata.searchData.storeId" 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"
        :initData="false"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        :tableExportFunc="$access('ENT_DEVICE_QRC_EXPORT') ? tableExportFunc : null"
        :rowSelection="{ type: 'checkbox', onChange: infoTableSelectChangeFunc }"
        rowKey="qrcId"
      >
        <template #topBtnSlot>
          <a-button type="primary" @click="addOrEditFunc()"><PlusOutlined /> 申请新码</a-button>

          <!-- <a-button @click="batchChecked(true)">全选</a-button>
          <a-button @click="batchChecked(false)">反选</a-button> -->
          <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT')" type="primary" @click="allotBatchFunc"><partition-outlined />勾选划拨/收回</a-button>
          <!-- <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT')" type="primary" @click="allotByBatchIdFunc">批次划拨</a-button> -->
          <a-button v-if="$access('ENT_DEVICE_QRC_EXPORT')" @click="tableExportByBatchSelectFunc">导出选择项</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 === '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 === '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 === '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 === '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_DEVICE_QRC_VIEW')" type="link" @click="showQrImgFunc(record.qrcId)">详情</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_EDIT') && record.isSelf" type="link" @click="showBind(record.qrcId)">绑定</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_RELIEVE') && record.bindState == 1 && record.isSelf" type="link" @click="unBindFunc(record.qrcId)">解绑</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT')" type="link" @click="allotFunc(record)">划拨/收回</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_EDIT') && record.bindState == 1" type="link" @click="getBindDeviceFunc(record.qrcId)">受支持设备</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>

      <!-- <AddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" /> -->

      <Bind ref="bindRef" :callbackFunc="searchFunc" />

      <JeepayQrcDeviceList ref="jeepayQrcDeviceListRef" sysType="AGENT" />

      <JeepayModelAgentList ref="jeepayModelAgentList" showType="AGENT" @selectFinishFunc="searchAgentFinishFunc" />

      <!-- 批次号划拨弹窗 -->
      <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>

      <a-modal v-model:visible="vdata.exportVisible" title="导出选项" :width="500" @ok="tableExportDowonloadFunc">
        <a-radio-group v-model:value="vdata.exportModel">
          <a-radio value="infoAndUrl" style="margin-bottom: 10px;">Excel： 二维码信息并且包含二维码解析URL</a-radio><br>
          <a-radio value="templateImg" style="margin-bottom: 10px;">压缩包： 模板图片（如果有）</a-radio> <br>
          <a-radio value="qrcode" style="margin-bottom: 10px;">压缩包： 二维码图片(不含编号)</a-radio><br>
          <a-radio value="qrcodeAndQrcId" style="margin-bottom: 10px;">压缩包： 二维码图片(含编号) </a-radio><br>
        </a-radio-group>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>
<script setup lang="ts">
import Bind from './Bind.vue'
import {API_URL_MCH_QR_CODE_LIST, req, reqLoad, $qrcShellViewByQrc, $exportExcel, exportExcelUrl, $unbindQrc, $allotQrc } from '@/api/manage'
import { ref, reactive, provide, getCurrentInstance, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import fileDownload from 'js-file-download'
import {getCurrentDatetime} from '@/utils/util'

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

// infoTable组件
const infoTable = ref()

const bindRef = ref()

const jeepayQrcDeviceListRef = ref()

const allotFormModel = ref()

const jeepayModelAgentList = ref()

const dateRangePicker = ref()

// eslint-disable-next-line no-unused-vars
const tableColumns = ref([
  // { key: 'qrcId', title: '二维码', },
  // { key: 'agentNo', title: '服务商', dataIndex: 'agentNo', agentEntCol: true },
  // { key: 'mchNo', title: '绑定商户信息' },
  // { key: 'entryPage',  title: '扫码页面', customRender: ({ record }) => {return record.entryPage == 'default' ? '默认' : record.entryPage == 'h5' ? 'H5' : '小程序'} , },
  // { key: 'qrcState', title: '状态', },
  // { key: 'fixedFlag', title: '固定金额', },
  // { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期', },
  // { key: 'op', title: '操作', fixed: 'right', align: 'center',}

  { key: 'qrcType', title: '码牌类型', },
  { key: 'entryPage',  title: '页面类型', customRender: ({ record }) => {return record.entryPage == 'default' ? '默认' : record.entryPage == 'h5' ? 'H5' : '小程序'} ,},
  { key: 'qrcId', title: '二维码编号', },
  { key: 'qrcAlias', dataIndex: 'qrcAlias', title: '二维码名称'},
  { key: 'mchUserName', title: '用户名称', dataIndex: 'mchUserName'},
  { key: 'mchServiceName', title: '服务商名称', dataIndex: 'mchServiceName' },
  { title: "商户名称", key: "mchApplyName", dataIndex: "mchApplyName" },
  { key: 'storeId', title: '门店名称', dataIndex: 'storeId',  },
  { 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: {},
  exportVisible: false, // 显示导出弹层
  exportModel: '', //二维码导出模式

  listRecords: [], //当前列表页的缓存数据

  listExportIds: null, //列表的批量导出选择项目

  allotByBatchIdVisible: false, // 批次划拨设备弹窗
  allotObject: {
    agentNo: null, // 划拨服务商号
    allotType: null, // 划拨类型：select-勾选划拨  batch-批次划拨
    batchId: null, // 批次号，划拨类型为 batch-批次划拨 时必填
    allotIds: [] as any, // 要划拨的码ID，划拨类型为 select-勾选划拨 时必填
  } as any, // 划拨设备对象
  allotRules: {
    batchId: [{ required: true, message: '请输入批次号', trigger: 'blur' }]
  }
})


onMounted(() => {
  vdata.searchData['mchNo'] = useRoute().query.mchNo
  vdata.searchData['storeId'] = useRoute().query.storeId
  vdata.searchData['mchApplyId'] = useRoute().query.mchApplyId
  searchFunc()
})


// 向所有子组件注入刷新事件
provide('listPageSearchFunc', searchFunc)

function searchFunc () {
  infoTable.value.refTable(true)
}
// 请求table接口数据
function reqTableDataFunc (params) {
  return req.list(API_URL_MCH_QR_CODE_LIST, params).then((res) => {
    vdata.listRecords = (res && res.records) || []
    return Promise.resolve(res)
  })
}


// 新增 or 修改函数
function addOrEditFunc(){
  $infoBox.message.success('请联系运营平台申请')
}

// 显示二维码图片
function showQrImgFunc(recordId){
  $qrcShellViewByQrc(recordId).then((res) => {
    $viewerApi({images: [res]})
  })
}


// 显示绑定管理
function showBind(recordId){
  bindRef.value.show(recordId)
}


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

  const title = state === 1 ? '确认[启用]？' : '确认[停用]？'
  return $infoBox.confirmDangerPromise(title, '').then(() => {
    return reqLoad.updateById(API_URL_MCH_QR_CODE_LIST, recordId, { qrcState: state })
  })

}

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

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


// function batchChecked(checked){
//   vdata.listRecords.forEach(element => {
//     element.checked = checked
//   })
// }

function infoTableSelectChangeFunc(selectedRowKeys){

  // 获取真实的qrcId
  let qrcIdList : any = []
  selectedRowKeys.forEach(el => qrcIdList.push(el) )

  // 遍历 vdata.listRecords 如果selectedRowKeys数组中存在对应的id,则将其checked改为true,反之false
  vdata.listRecords.forEach(element => {
    qrcIdList.includes(element.qrcId) ? element.checked = true : element.checked = false
  })
}

// 第一次点击导出的事件（ 筛选条件的导出 ）
function tableExportFunc(){
  vdata.exportVisible = true
  vdata.exportModel = 'infoAndUrl' //默认excel

  vdata.listExportIds = null //批量选择清空
}


// 第一次点击导出的事件（ 批量选择的导出 ）
function tableExportByBatchSelectFunc(){

  vdata.listExportIds = []
  vdata.listRecords.forEach(element => {
    if(element.checked){
      vdata.listExportIds.push(element.qrcId)
    }
  })

  if(vdata.listExportIds.length <= 0){
    return $infoBox.message.error('请选择数据')
  }

  vdata.exportVisible = true
  vdata.exportModel = 'infoAndUrl' //默认excel
}


// 弹层点击确认按钮的事件
function tableExportDowonloadFunc(){

  vdata.exportVisible = false

  let queryCond :any = { 'exportModel': vdata.exportModel, 'pageSize': -1 } //搜索条件

  if(typeof vdata.listExportIds == 'object' && vdata.listExportIds != null){
    queryCond.idsStr = ''
    vdata.listExportIds.forEach(r => {
        queryCond.idsStr += (r + '_')
    })
    queryCond.idsStr = queryCond.idsStr.substring(0, queryCond.idsStr.length - 1)

  }else{
    queryCond = Object.assign(queryCond, vdata.searchData)
  }

  return $exportExcel(exportExcelUrl.qrCodes, queryCond).then(res => {

         if(vdata.exportModel == 'infoAndUrl'){
           fileDownload(res.data, '码牌信息导出_'+ getCurrentDatetime() +'.xlsx')
         }else{
           fileDownload(res.data, '码牌图片导出_'+ getCurrentDatetime() +'.zip')
         }

      }).catch ((error) =>{console.log(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 allotBatchFunc() {

    vdata.listExportIds = []
    vdata.listRecords.forEach(element => {
      if(element.checked){
        vdata.listExportIds.push(element.qrcId)
      }
    })

    if(vdata.listExportIds.length <= 0){
      return $infoBox.message.error('请选择数据')
    }

    vdata.allotObject.allotType = 'select'
    jeepayModelAgentList.value.show()
  }

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

    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.listExportIds.length > 0) {
      vdata.allotObject.allotIds = vdata.listExportIds.join(',')
    }

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

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