<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :mask-closable="false"
    title="应用高级配置"
    :body-style="{ paddingBottom: '80px' }"
    width="60%"
    class="drawer-width"
    @close="vdata.visible = false"
  >
    <div style="background: #fff">
      <a-tabs v-if="vdata.visible" @change="selectTabs">
        <a-tab-pane key="mchApiEnt" tab="接口权限">
          <a-table :dataSource="vdata.mchApiEntTableData" :columns="vdata.mchApiEntTableColumns" :pagination="false" size="small">
            <!-- header 标题 插槽 -->
            <template #headerCell="{ column }">
              <template v-if="column.key === 'batch'">
                <a-checkbox @change="(e) => mchApiEntAllCehcked(e.target.checked)" />
              </template>
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'batch'"><a-checkbox v-model:checked="record.checked" :disabled="record.disabled" /></template>
            </template>

            <template #title>可自调用接口</template>
          </a-table>

          <a-form-item class="bottom-btn">
            <a-button type="primary" :loading="vdata.btnLoading" @click="confirmByApiEnt"><check-circle-outlined />确认更新</a-button>
          </a-form-item>
        </a-tab-pane>

      </a-tabs>
    </div>
  </a-drawer>
</template>
<script setup lang="ts">
import {
  API_URL_MCH_CONFIG,
  API_URL_MCH_LIST,
  req,
  $mchConfigCreateCashier,
  API_URL_MCH_APP,
  API_URL_MCH_STORE_LIST,
  API_URL_MCH_APP_CONFIG, API_URL_MCH_APP_CONFIG_API_ENT,
} from '@/api/manage'
import { ref, reactive, getCurrentInstance } from 'vue'
import QrcodeVue from 'qrcode.vue'

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

  const configFormModel = ref()
  const payTestBarCode =ref()


  const vdata : any = reactive ({

    recordId: null, // 更新对象ID
    visible: false, // 是否显示弹层/抽屉

    mchAppList: [] as any, // app列表
    mchStoreList: [] as any, // 门店列表
    appId: '', // 已选择的appId
    storeId: '', // 已选择的门店ID
    cashierUrl: '',  // 收银台地址
    isShowCashier: true as any,

    btnLoading: false,
    groupKey: 'mchApiEnt',
    mchConfigData: [] as any, // 配置保存对象
    defaultConfig: [{
      configKey: 'appVoice',
      configName: '是否启用app订单语音播报',
      configVal: '1',
      type: 'radio'
    },
    {
      configKey: 'qrcEscaping',
      configName: '是否启用码牌防逃单功能',
      configVal: '1',
      type: 'radio'
    },
    {
    configKey: 'weChatVoice',
    configName: '小程序语音推送',
    configVal: '0',
    type: 'radio'
    }
  ], // 默认配置项

    mchPayNotifyUrl: '', // 用户支付回调地址
    mchRefundNotifyUrl: '', // 用户退款回调地址

    mchNotifyFlag: {
      payNotifyFlag: '1',
      refundNotifyFlag: '1'
    },  // 用户回调开关

    mchNotifyPostType: 'POST_BODY', // 发送用户通知的方式  POST_BODY   POST_QUERYSTRING  POST_JSON


    mchApiEntTableColumns: [
      {key: 'batch', title: '批量选择' },
      {key: 'title', dataIndex: 'title', title: '名称' },
      {key: 'key', dataIndex: 'key', title: 'KEY' },
      {key: 'apiPath', dataIndex: 'apiPath', title: '路径' },
    ],

    mchApiEntTableData: [
      // {key: 'API_PAY_ORDER', title: '统一下单', apiPath: '/api/pay/unifiedOrder', checked: false },
      // {key: 'API_PAY_ORDER_QUERY', title: '查询支付订单', apiPath: '/api/pay/query', checked: false },
      // {key: 'API_PAY_ORDER_CLOSE', title: '支付订单关闭', apiPath: '/api/pay/close', checked: false },
      // {key: 'API_CHANNEL_USER', title: '获取渠道用户ID', apiPath: '/api/channelUserId/jump', checked: false },
      // {key: 'API_REFUND_ORDER', title: '发起支付退款', apiPath: '/api/refund/refundOrder', checked: false },
      // {key: 'API_REFUND_ORDER_QUERY', title: '查询退款订单', apiPath: '/api/refund/query', checked: false },
      // {key: 'API_TRANS_ORDER', title: '发起转账订单', apiPath: '/api/transferOrder', checked: false },
      // {key: 'API_TRANS_ORDER_QUERY', title: '查询转账订单', apiPath: '/api/transfer/query', checked: false },
      // {key: 'API_TRANS_BALANCE_QUERY', title: '查询转账可用余额', apiPath: '/api/transfer/balance/query', checked: false },
      // {key: 'API_DIVISION_BIND', title: '绑定分账用户', apiPath: '/api/division/receiver/bind', checked: false },
      // {key: 'API_DIVISION_EXEC', title: '发起订单分账', apiPath: '/api/division/exec', checked: false },
      // {key: 'API_DIVISION_CHANNEL_BALANCE', title: '查询分账用户可用余额', apiPath: '/api/division/receiver/channelBalanceQuery', checked: false },
      // {key: 'API_DIVISION_CHANNEL_CASHOUT', title: '对分账用户的渠道余额发起提现', apiPath: '/api/division/receiver/channelBalanceCashout', checked: false },
      {key: 'API_APP_PAY', title: 'APP支付', apiPath: '', checked: false },
      {key: 'API_H5_PAY', title: '手机网站支付', apiPath: '', checked: false },
      // {key: 'API_PC_PAY', title: '电脑网站支付', apiPath: '', checked: false },
      {key: 'API_APPLET_PAY', title: '小程序支付', apiPath: '', checked: false },
      {key: 'API_JSAPI_PAY', title: '公众号/生活号/银联JS支付', apiPath: '', checked: false },
      // {key: 'API_CASHIER_PAY', title: '聚合收银台支付', apiPath: '', checked: false },
      {key: 'API_MICRO_PAY', title: '聚合反扫支付(B扫C)（扫码）', apiPath: '', checked: false },
      {key: 'API_SCAN_PAY', title: '聚合码(电脑网站支付)', apiPath: '', checked: false },
      // {key: 'API_UNIFIED_REFUND', title: '统一退款', apiPath: '', checked: false },
      // {key: 'API_ORDER_QUERY', title: '订单查询', apiPath: '', checked: false },
      // {key: 'API_REFUND_QUERY', title: '退款查询', apiPath: '', checked: false },
      // {key: 'API_WXUSER_QUERY', title: '微信用户标识查询', apiPath: '', checked: false },
      // {key: 'API_ORDER_DIVISION', title: '订单分账', apiPath: '', checked: false },
      // {key: 'API_DIVISION_QUERY', title: '分账查询', apiPath: '', checked: false },
     ],
     detailData:{}
  })


  function show (record) { // 弹层打开事件

      vdata.detailData = record
      vdata.recordId = record.appId
      selectTabs('mchApiEnt') //初始化数据
      vdata.visible = true
  }


  function selectTabs (key) { // 清空必填提示
    
    if (key) {
      vdata.groupKey = key

      if(key == 'mchApiEnt'){
        // 恢复初始值
        vdata.mchApiEntTableData.forEach(r => {
          r. checked = false
        })

        req.list(API_URL_MCH_APP_CONFIG, {mchNo: vdata.detailData.mchNo, mchAppId: vdata.detailData.appId}).then(res => {
          if (res != null && res.length > 0) {
            res.forEach(item => {
              if (item.configKey == 'mchApiEntList') { // 用户接口权限集合
                let arr = JSON.parse(item.configVal)
                vdata.mchApiEntTableData.forEach(r => {
                  r.checked = arr.indexOf(r.key) >= 0
                })
              }
            })
          }
        })
      }


    }
  }




    // 确认更新
  function confirmByApiEnt (e) {

    $infoBox.confirmPrimary('确认修改用户的接口权限？', '', () => {
      vdata.btnLoading = true // 打开按钮上的 loading

      let arr : any = []
      vdata.mchApiEntTableData.forEach(r => {
          if(r.checked){
            arr.push(r.key)
          }
      })

      let configItem = [{ groupKey: vdata.groupKey, configName: '用户接口权限集合', configKey: 'mchApiEntList', configVal : JSON.stringify(arr) }]
      const data = {
        mchNo: vdata.detailData.mchNo,
        mchAppId: vdata.detailData.appId,
        configData:JSON.stringify(configItem)
      }
      req.updateById(API_URL_MCH_APP_CONFIG_API_ENT, vdata.groupKey, data).then(res => {
        $infoBox.message.success('修改成功')
        vdata.btnLoading = false
      }).catch(res => {
        vdata.btnLoading = false
      })
    })
  }


   // 全选，反选
  function notifyAllCehcked(isChekced){
      vdata.notifyTableData.filter(r => !r.disabled).forEach(r => {
        r.checked = isChekced
      })
  }

  // 全选，反选
  function mchApiEntAllCehcked(isChekced){
    vdata.mchApiEntTableData.filter(r => !r.disabled).forEach(r => {
      r.checked = isChekced
    })
  }

 // 变更 appId的事件
 function changeAppId (value) {
    immediatelyPay()
  }
  // 变更 门店ID的事件
  function changeStoreId (value) {
    immediatelyPay()
  }
  // 立即支付按钮
  function immediatelyPay () {

    // 判断是否选择门店
    if (vdata.appId === '') {
      vdata.isShowCashier = false
      return false
    }
    // 判断是否选择门店
    if (vdata.storeId === '') {
      vdata.isShowCashier = false
      return false
    }

    vdata.isShowCashier = true
    $mchConfigCreateCashier({
      appId: vdata.appId, // appId
      storeId: vdata.storeId, // storeId
      mchNo: vdata.recordId
    }).then(res => {
      vdata.cashierUrl = res
    }).catch(() => {
      payTestBarCode.value.processCatch()
    })
  }

defineExpose({
  show
})
</script>
<style lang="less" scoped>
  .bottom-btn{
    /deep/ div{
      display: flex;
      justify-content: center;
    }
  }
  .typePopover {
  position: absolute;
  top: -30px;
  left: 93px;
}
</style>
