<template>
  <page-header-wrapper>
    <a-card v-if="vdata.showShellList">
      <div style="background-color:#69a2e3; height: 30px; text-align: center;">
        <a-button style="color:white; position:absolute; left : 0" type="link" @click="vdata.showShellList = false">
          <left-outlined />
          返回列表页
        </a-button>
        <span style="color:white;line-height: 30px;">模板管理</span>
      </div>
      <ShellList v-if="vdata.showShellList" />
    </a-card>


    <a-card v-show="!vdata.showShellList">
      <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-option value="3">云音响码牌</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['batchId']" placeholder="批次号" />
        <jeepay-text-up v-model:value="vdata.searchData['storeId']" placeholder="门店名称/门店编号" />
        <jeepay-text-up v-model:value="vdata.searchData['appId']" placeholder="应用名称/应用ID" />

        <jeepay-text-up v-if="$hasAgentEnt()" 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['qrcId']" placeholder="码牌ID" />-->

<!--        <jeepay-text-up v-model:value="vdata.searchData['appId']" placeholder="应用AppId" />-->
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="false"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        :tableExportFunc="$access('ENT_DEVICE_QRC_EXPORT') ? tableExportFunc : null"
        rowKey="qrcIdAndKey"
        :rowSelection="{ type: 'checkbox', onChange: infoTableSelectChangeFunc }"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_DEVICE_QRC_ADD')" type="primary" @click="addOrEditFunc(null, vdata.searchData['mchNo'])"><PlusOutlined /> 创建空码</a-button>

          <!-- <a-button type="default" @click="() => vdata.showShellList = true"><border-outer-outlined /> 模板管理</a-button> -->

          <!-- <a-button type="primary" @click="batchChecked(true)">全选</a-button>
          <a-button type="primary" @click="batchChecked(false)">反选</a-button> -->
          <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT') && $hasAgentEnt()" type="primary" @click="allotBatchFunc">勾选划拨</a-button>
          <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT') && $hasAgentEnt()" type="primary" @click="allotByBatchIdFunc">批次划拨</a-button>
          <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT') && $hasAgentEnt()" type="primary" @click="allotByQrcIdRangeFunc">区间划拨</a-button>
          <a-button v-if="$access('ENT_DEVICE_QRC_DEL')" type="danger" @click="deleteBatchFunc"><delete-outlined />批量删除</a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'qrcId'">
            <QrcodeOutlined style="font-size: 16px" @click="showQrImgFunc(record.qrcId)" />
            {{ record.qrcId }}
          </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>
            <a-tag v-if="record.qrcType == 3" color="tan">音响码牌</a-tag>
          </template>
          <template v-if="column.key === 'urlPlaceholder'">
            <a-popover v-if="record.entryPage == 'default' || record.entryPage == 'lite' " placement="top">
              <template #title><span>  二维码地址自定义占位符：{{ record.urlPlaceholder || '无' }}</span></template>
              <template #content>
                小程序绑定普通二维码规则： {{ getQrUrlView(record.payHostUrl, record.entryPage, record.urlPlaceholder ) }}
              </template>
              <exclamation-circle-outlined />  {{ record.urlPlaceholder || '标准配置' }}
            </a-popover>
          </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 === '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 === 'mchNo'">
            <template v-if="record.bindState == 0"><exclamation-circle-outlined />未绑定</template>
<!--            <template v-else>已绑定用户: {{ record.mchName }} ({{ record.mchId }})<br>应用： {{ record.appName }}({{ record.appId }})<br>门店： {{ record.storeName }} ({{ record.storeId }})</template>-->
            <template v-else>
               <div style="text-align: left;">
                 <p v-if="record.appName">应用： {{ record.appName }}({{ record.appId }})</p>
                 <p v-if="record.mchApplyName">商户： {{ record.mchApplyName }} ({{ record.mchApplyId }})</p>
                 <p v-if="record.storeName">门店： {{ record.storeName }} ({{ record.storeId }})</p>
               </div>
            </template>

          </template>

          <template v-if="column.key === 'agentNo'">
            <a-tooltip   class="my-tooltip">
              <template #title>
                服务商号：{{record.agentNo}}
              </template>
              {{record.agentName}}
            </a-tooltip>
          </template>

          <template v-if="column.key === 'qrcState'">
            <JeepayTableColState :state="record.qrcState" :showSwitchType="$access('ENT_DEVICE_QRC_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 }}</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')" type="link" @click="addOrEditFunc(record.qrcId, record.mchNo)">修改</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_EDIT')" type="link" @click="showBind(record)">绑定</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_EDIT') && record.bindState == 1" type="link" @click="unBindFunc(record.qrcId)">解绑</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_EDIT') && record.bindState == 1" type="link" @click="getBindDeviceFunc(record.qrcId)">受支持设备</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT') && $hasAgentEnt()" type="link" @click="allotFunc(record)">划拨/收回</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_DEL')" style="color: red" type="link" @click="delFunc(record.qrcId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>

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

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

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

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

      <!-- 批次号划拨弹窗 -->
      <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.allotByQrcIdRangeVisible" title="按码牌ID区间划拨">
        <template #footer>
          <a-button key="back" @click="() => vdata.allotByQrcIdRangeVisible = false">取消</a-button>
          <a-button key="submit" type="primary" :loading="vdata.btnLoading" @click="checkAllot">检查</a-button>
          <a-button key="submit" type="primary" :disabled="!vdata.allotObject.checkAllotResult"  @click="allotOk">确认</a-button>
        </template>

        <a-form ref="allotByQrcIdRangeFormModel" :model="vdata.allotObject" layout="vertical" :rules="vdata.allotRules">
          <a-row type="flex" align="middle" :gutter="5">
            <a-col flex="auto">
              <a-form-item label="起始码牌ID：" name="startQrcId">
                <a-input-number
                  v-model:value="vdata.allotObject.startQrcId"
                  :min="1"
                  placeholder="请输入起始码牌ID"
                  style="width:100%;"
                  @change="vdata.allotObject.checkAllotResult = ''"
                />
              </a-form-item>
            </a-col>
            <a-col flex="0px">-</a-col>
            <a-col flex="auto">
              <a-form-item label="截止码牌ID：" name="endQrcId">
                <a-input-number
                  v-model:value="vdata.allotObject.endQrcId"
                  :min="1"
                  placeholder="请输入截止码牌ID"
                  style="width:100%;"
                  @change="vdata.allotObject.checkAllotResult = ''"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="24">{{ vdata.allotObject.checkAllotResult }}</a-col>
          </a-row>
        </a-form>
      </a-modal>

      <a-modal v-model:visible="vdata.exportVisible" title="导出选项" :width="550" @ok="tableExportDowonloadFunc">
        <a-divider orientation="left" style="color: #1A66FF;">数据范围</a-divider>
        <a-radio-group v-model:value="vdata.exportModelScope">
          <a-radio value="checkedData" style="margin-bottom: 10px;">已勾选条目</a-radio>
          <a-radio value="all" style="margin-bottom: 10px; margin-left:20px">全部搜索条件</a-radio>
        </a-radio-group>


        <a-divider orientation="left" style="color: #1A66FF;">导出内容</a-divider>

        <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 AddOrEdit from './AddOrEdit.vue'
import Bind from './Bind.vue'
import {API_URL_MCH_QR_CODE_LIST, req, reqLoad, $qrcShellViewByQrc, $exportExcel, exportExcelUrl, $allotQrc, $check4RangeAllot, $batchDelQrc, $unbindQrc } from '@/api/manage'
import { ref, reactive, provide, getCurrentInstance, onMounted } from 'vue'
import ShellList from './shell/List.vue'
import { useRoute } from 'vue-router'
import fileDownload from 'js-file-download'
import {getCurrentDatetime} from '@/utils/util'
import { genRowKey } from '@/utils/util'

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

// infoTable组件
const infoTable = ref()

const infoAddOrEdit = ref()

const bindRef = ref()

const allotFormModel = ref()

const allotByQrcIdRangeFormModel = ref()

const jeepayModelAgentList = ref()

const jeepayQrcDeviceListRef = ref()

const dateRangePicker = ref()


// eslint-disable-next-line no-unused-vars
const tableColumns = ref([
  { key: 'qrcType', title: '码牌类型', align: 'center'  },
  { key: 'entryPage',  title: '页面类型', align: 'center', customRender: ({ record }) => {return record.entryPage == 'default' ? '默认' : record.entryPage == 'h5' ? 'H5' : '小程序'}  },
  { key: 'qrcId', title: '二维码编号', align: 'center'  },
  { key: 'batchId', title: '批次号', dataIndex: 'batchId' , align: 'center'},
  { key: 'mchNo', title: '绑定商户信息', align: 'center' },
  { key: 'mchUserName', title: ' 所属用户', dataIndex: 'mchUserName', agentEntCol: true ,align: 'center',},
  { key: 'mchServiceName', title: ' 所属服务商', dataIndex: 'mchServiceName', agentEntCol: true ,align: 'center',},
  { key: 'urlPlaceholder', title: '小程序配置', dataIndex: 'urlPlaceholder' },
  { key: 'qrcState', title: '状态', align: 'center' },
  { key: 'fixedFlag', title: '固定金额',  align: 'center' },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期',  },
  { key: 'op', title: '操作', fixed: 'right', align: 'center',   }
])


const vdata : any = reactive({
  searchData: {},
  exportVisible: false, // 显示导出弹层
  exportModel: '', //二维码导出模式
  showShellList: false,

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

  exportModelScope: 'checkedData', // 数据导出范围： checkedData   all

  listExportIds: [] as any, //列表的批量导出选择项目

  allotByBatchIdVisible: false, // 批次划拨弹窗
  allotByQrcIdRangeVisible: false, // 区间划拨弹窗
  allotObject: {
    checkAllotResult: '', // 划拨前校验结果
    agentNo: null, // 划拨代理商号
    allotType: null, // 划拨类型：select-勾选划拨  batch-批次划拨   range-区间划拨
    batchId: null, // 批次号，划拨类型为 batch-批次划拨 时必填
    allotIds: [] as any, // 要划拨的码ID，划拨类型为 select-勾选划拨 时必填
    startQrcId: null, // 开始码牌ID  range-区间划拨必填
    endQrcId: null // 结束码牌ID  range-区间划拨必填
  } as any, // 划拨设备对象

  allotRules: {
    batchId: [{ required: true, message: '请输入批次号', trigger: 'blur' }],
    startQrcId: [{ required: true, message: '请输入起始码牌ID', trigger: 'blur' }],
    endQrcId: [{ required: true, message: '请输入截止码牌ID', trigger: 'blur' }]
  }
})


onMounted(() => {
  vdata.searchData['mchNo'] = useRoute().query.mchNo
  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) || []

    vdata.listRecords.forEach(r => {
      r.qrcIdAndKey = r.qrcId + '_' + genRowKey()
    })


    return Promise.resolve(res)
  })
}


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


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

function deleteBatchFunc() {  // 批量删除
  vdata.listExportIds = []
  vdata.listRecords.forEach(element => {
    if(element.checked){
      vdata.listExportIds.push(element.qrcId)
    }
  })

  if (vdata.listExportIds.length <= 0) {
    $infoBox.message.error('请选择数据')
  } else {
    $infoBox.confirmDanger('确认删除？', '', () => {
      $batchDelQrc(vdata.listExportIds.join(',')).then((res: any) => {
        $infoBox.message.success('删除成功')
        searchFunc()
      })
    })
  }
}
// 删除
function delFunc(recordId){
  $infoBox.confirmDanger('确认删除？', '', () => {
    $batchDelQrc(recordId).then(res => {
      $infoBox.message.success('删除成功')
      searchFunc()
    })
  })
}


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

// 解绑
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  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 batchChecked (checked) {
//   vdata.listRecords.forEach(element => {
//     element.checked = checked
//   })
//   console.log(vdata.listRecords)
// }

function infoTableSelectChangeFunc(selectedRowKeys){

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

  // 遍历 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.exportModelScope = 'checkedData' // 仅选择数据
}


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

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

  // 仅选择数据
  if(vdata.exportModelScope == 'checkedData'){

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

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

    queryCond.idsStr = ''
    listExportIds.forEach(r => {
        queryCond.idsStr += (r + '_')
    })
    queryCond.idsStr = queryCond.idsStr.substring(0, queryCond.idsStr.length - 1)

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

  vdata.exportVisible = false

  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', batchId: '' }
    vdata.allotByBatchIdVisible = true
  }

  // 打开弹窗  按码牌区间划拨
  function allotByQrcIdRangeFunc() {
    vdata.allotObject = { allotType: 'range', startQrcId: '', endQrcId: '', }
    vdata.allotByQrcIdRangeVisible = true
  }

  // 关闭弹窗  【按批次号划拨，批次号输入完成】或【区间划拨，起止码牌ID输入完成】
  function allotOk() {
    if (vdata.allotObject.allotType == 'batch') {
      allotFormModel.value.validate().then((valid: any) =>{
        vdata.allotByBatchIdVisible = false
        jeepayModelAgentList.value.show()
      })
    }
    else if (vdata.allotObject.allotType == 'range') {
      vdata.allotByQrcIdRangeVisible = false
      jeepayModelAgentList.value.show()
    }
  }

  function checkAllot() {
    allotByQrcIdRangeFormModel.value.validate().then((valid: any) =>{
      if (vdata.allotObject.startQrcId > vdata.allotObject.endQrcId) {
        return $infoBox.message.error('起始码牌ID应小于截止码牌ID')
      }

      $check4RangeAllot(vdata.allotObject).then((res) => {
        vdata.allotObject.checkAllotResult = res
      })
    })
  }

    // 勾选划拨设备
  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: '' }
  }

  // 获取二维码的数据
function getQrUrlView(payHostUrl, entryPage, urlPlaceholder){

return payHostUrl
+ '/cashier'
+ ( urlPlaceholder ?  ('/' + urlPlaceholder)  : '' )
+  '/pages/hub/'+ entryPage +'/'
}


</script>
