<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm v-if="$access('ENT_UR_ROLE_SEARCH')" :searchConditionNum="6" :searchFunc="searchFunc" :resetFunc="() => { data.searchData= {} }">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="data.searchData['queryDateRange']" customDateRangeType="dateTime" />
        </a-form-item>
        <jeepay-text-up v-model:value="data.searchData['mchUserName']" v-if="props.configMode != 'mch'" :placeholder="'用户号/名称/手机号'" />
        <jeepay-text-up v-model:value="data.searchData['accountName']" :placeholder="'账户名称'" />
        <jeepay-text-up v-model:value="data.searchData['name']" :placeholder="'账户ID'" />
        <jeepay-text-up v-model:value="data.searchData['account']" :placeholder="'账号'" />
<!--        <a-form-item label="" class="table-search-item">-->
<!--          <a-select v-model:value="data.searchData['accountType']" placeholder="人员类型">-->
<!--            <a-select-option value="">全部</a-select-option>-->
<!--            <a-select-option value="C">个人</a-select-option>-->
<!--            <a-select-option value="B">企业</a-select-option>-->
<!--          </a-select>-->
<!--        </a-form-item>-->
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="data.searchData['pay_method']" placeholder="账户类型">
            <a-select-option value="">全部</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-option :value="4">对公账户</a-select-option>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
          ref="infoTable"
          :init-data="true"
          :req-table-data-func="reqTableDataFunc"
          :statisticsIsShow="false"
          :tableExportFunc="tableExportFunc"
          :table-columns="tableColumns"
          :search-data="data.searchData"
          row-key="sysUserId"
          @btnLoadClose="data.btnLoading=false"
      >
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in count" :key="index" class="item">
              <div v-if="item.type == 'line'" class="line" />
              <div class="title">{{ item.title }}</div>
              <div v-if="item.title" class="amount" :style="{color: item.textColor}">
                <span class="amount-num">{{ item.content }}</span>
              </div>
            </div>
          </div>
        </template>
        <template #topBtnSlot>
          <div>
            <a-button  v-if="$access('ENT_UR_USER_ADD')"  type="primary"   class="mg-b-30"  @click="addFunc()"  >  <plus-outlined /> 新建  </a-button>
          </div>
        </template>
        <template #bodyCell="{column,record}">

          <template v-if="column.key === 'accountType'">
<!--            <a-tag color="#b7eb8f" v-if="record.accountType == 'C' && record.entryType == 'ZFB'"> 个人支付宝</a-tag>-->
<!--            <a-tag color="#096dd9" v-if="record.accountType == 'B' && record.entryType == 'ZFB'"> 企业支付宝</a-tag>-->
<!--            <a-tag color="#ffbb96" v-if="record.accountType == 'C' && record.entryType == 'BANK'"> 个人银行卡</a-tag>-->
<!--            <a-tag color="#91d5ff" v-if="record.accountType == 'B' && record.entryType == 'BANK'"> 对公账户</a-tag>-->

<!--            res.records[i].accountTypeState = 0;-->
<!--            res.records[i].accountTypeStateDesc = '';-->
            <a-tag
                :key="record.accountType"
                :color="record.accountTypeState == 4?'red':record.accountTypeState == 2?'orange':record.accountTypeState === 3?'blue':record.accountTypeState === 1?'green':'volcano'"
            >
              {{record.accountTypeStateDesc}}
            </a-tag>


          </template>


          <template v-if="column.key === 'totalAmount'">

            {{ record.totalAmount?(record.totalAmount / 100).toFixed(2):0 }}
          </template>
          <template v-if="column.key === 'amountNumber'">
            {{ record.amountNumber?record.amountNumber:0 }}
          </template>
          <template v-if="column.key === 'state'">
            <JeepayTableColState :state="record.state" :show-switch-type="$access('ENT_UR_USER_EDIT')" :on-change="(state) => { return updateState(record, state)}" />
          </template>

          <template v-if="column.key === 'account'">

            <a-popover placement="top" style="background: #0c2640 !important;">
              <template #content  style="background: #ff0 !important;">
                <p style="padding: 5px">{{ record.accountTypeName[0] }}：{{record.accountName}}</p>
                <p style="padding: 5px">{{ record.accountTypeName[1] }}：{{record.account}}</p>
                <p style="padding: 5px" v-if="record.message.instProvince">{{ record.accountTypeName[2] }}：{{record.message.instProvince}}</p>
                <p style="padding: 5px" v-if="record.message.instName">{{ record.accountTypeName[3] }}：{{record.message.instName}}</p>
                <p style="padding: 5px" v-if="record.message.instBranchName">{{ record.accountTypeName[4] }}：{{record.message.instBranchName}}</p>
              </template>
              <div class="my-tooltip-title-box"><b><a >{{record.account}}</a></b></div>
            </a-popover>
          </template>

          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <!--              <a-button v-if="$access('ENT_UR_USER_EDIT')" type="link" @click="showPreUserModalFunc(record)">详情</a-button>-->
              <a-button  style="color: red"  type="link" @click="delFunc(record.id)" >删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <a-modal class="modal-box" v-model:visible="vdata.showPreUserModal" :title="vdata.userAddTitle"  :confirmLoading="vdata.preUserModalLoading" @ok="preUserHandleOkFunc">
      <SybAqfUserAddOrEdit :configMode="props.configMode" ref="sybAqfUserAddOrEditRef" @itemRender="setAqfUserInfo" />
    </a-modal>

  </page-header-wrapper>
</template>
<script setup lang="ts">
import {
  API_URL_MCH_APPLYMENT_LIST,
  req,
  reqLoad,
  $deleteLoginLimit,
  $exportExcel,
  exportExcelUrl,
  API_URL_STATISTIC, API_URL_PAY_AQF_ADD_JS, API_URL_PAY_AQF_LIST, API_URL_PAY_AQF_DEL
} from '@/api/manage'
import { useUserStore } from '@/store/modules/user'
import { reactive,ref,getCurrentInstance} from 'vue'
import fileDownload from "js-file-download";
import {message} from "ant-design-vue";

const props = defineProps({
  configMode: { type: String, default: '' },   // 模式
})

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


const tableColumns = reactive([
  {key:'id', title: '账户ID',   dataIndex: 'id' },
  {key:'accountName', title: '账户名称', dataIndex: 'accountName', },
  {key:'account', title: '账号', dataIndex: 'account', },
  {key:'accountType', title: '账户类型', dataIndex: 'accountType', },
  // {key:'message', title: '账户信息', dataIndex: 'message', },
  {key:'totalAmount', title: '实收金额', dataIndex: 'totalAmount',align: 'center' },
  {key:'amountNumber', title: '实收笔数', dataIndex: 'amountNumber',align: 'center' },
  {key:'createdTime', title: '创建时间', dataIndex: 'createdTime', },
  // {key: 'op',title: '操作',   fixed: 'right',align: 'center' }
])

const infoTable = ref()
const sybAqfUserAddOrEditRef =ref()

let data : any = reactive ({
  tableColumns: tableColumns,
  searchData: { queryDateRange: '' } as any,
  btnLoading: false
})

let count:any = ref([]) // 数据统计数组
let vdata : any = reactive({
  userAddTitle:"",
  visible:false,
  showRechargeModal:false,
  rechargeModalLoading: false,  // loading
  rechargeObject: {}, // 预审核结果

  showPreUserModal: false,  // 是否显示预审核弹层
  preUserModalLoading: false,  // loading
  preUserResult: {}, // 预审核结果
})

// 请求table接口数据
async  function reqTableDataFunc(params){
  // reqTableCountFunc(params)
  params.transIfCode = 'aliaqf'
  params.subjectType = 'JS'

  if(params.pay_method == 1){
    params.accountType = 'C'
    params.entryType = 'ZFB'
  }else if(params.pay_method == 2){
    params.accountType = 'B'
    params.entryType = 'ZFB'
  }else if(params.pay_method == 3){
    params.accountType = 'C'
    params.entryType = 'BANK'
  }else if(params.pay_method == 4){
    params.accountType = 'B'
    params.entryType = 'BANK'
  }

  let  res =  await  req.list(API_URL_PAY_AQF_LIST, params)
  for (let i = 0; i < res.records.length; i++) {
    res.records[i].accountTypeState = 0;
    res.records[i].accountTypeStateDesc = '';
    if(res.records[i].accountType == 'C' && res.records[i].entryType == 'ZFB'){
      res.records[i].accountTypeState = 1;
      res.records[i].accountTypeStateDesc = '个人支付宝';
      res.records[i].accountTypeName = [ '支付宝名称','支付宝账号'];
    }else if(res.records[i].accountType == 'B' && res.records[i].entryType == 'ZFB'){
      res.records[i].accountTypeState = 2;
      res.records[i].accountTypeStateDesc = '企业支付宝';
      res.records[i].accountTypeName = [ '企业支付宝名称','企业支付宝账号'];
    }else if(res.records[i].accountType == 'C' && res.records[i].entryType == 'BANK'){
      res.records[i].accountTypeState = 3;
      res.records[i].accountTypeStateDesc = '个人银行卡';
      res.records[i].accountTypeName = [ '姓名','银行卡号'];
    }else if(res.records[i].accountType == 'B' && res.records[i].entryType == 'BANK'){
      res.records[i].accountTypeState = 4;
      res.records[i].accountTypeStateDesc = '对公账户';
      res.records[i].accountTypeName = [ '营业执照名称','对公账户账号','开户行省','开户银行','开户支行名称'];
    }
    if(!res.records[i].accountMessage){
      res.records[i].message = {};
    }else{
      var message = JSON.parse(res.records[i].accountMessage)
      // res.records[i].message = messgae.instProvince + "-"+messgae.instName + "-"+messgae.instBranchName
      res.records[i].message = message
    }
  }
  console.log(res,'resresres')
  return res
}

function reqTableCountFunc(params: any) {
  params.method = 'transaction'
  req.list(API_URL_STATISTIC + '/total', params).then(res => {
    count.value = [
      {title: '总成交金额', symbol: 'add', textColor: '#1A66FF', content: ((res.totalSuccAmt) / 100).toFixed(2)},
      {type: 'line'},
      {title: '总成交笔数', content: (res.totalSuccNum)},
      {type: 'line'},
      {title: '总退款金额', symbol: 'sub', content: ((res.totalRefundAmt) / 100).toFixed(2)},
      {type: 'line'},
      {title: '总退款笔数', content: (res.totalRefundNum)},
    ]
  })
}
function searchFunc() { // 点击【查询】按钮点击事件
  data.btnLoading = true // 打开查询按钮的loading
  infoTable.value.refTable(true)
}

function addFunc () { // 业务通用【新增】 函数
  vdata.showPreUserModal = true
  vdata.userAddTitle = "新建人员结算信息"
  sybAqfUserAddOrEditRef.value.show()
}

function editFunc (record) { // 业务通用【修改】 函数
  vdata.showPreUserModal = false
  vdata.userAddTitle = "查看付款账户"
  sybAqfUserAddOrEditRef.value.show(record)
}
function delFunc(recordId) { // 业务通用【删除】 函数
  $infoBox.confirmDanger('确认删除？', '请确认删除该用户？', () => {
    return req.delById(API_URL_PAY_AQF_DEL, recordId).then(res => {
      $infoBox.message.success('删除成功！')
      infoTable.value.refTable(false)
    },() => {
      console.log(1111)
    })
  })
}

function deleteLoginLimit(recordId) { // 解除登录限制
  $infoBox.confirmDanger('确认解除吗？', '', () => {
    return $deleteLoginLimit(recordId).then(res => {
      $infoBox.message.success('解除成功！')
      infoTable.value.refTable(false)
    },() => {
      console.log(1111)
    })
  })
}


function onCopySuccess () {
  $infoBox.message.success('复制成功')
}
// 预审核结果
function rechargeHandleOkFunc(){

  if(!vdata.rechargeResult.state){
    return $infoBox.message.error('请选择审核结果')
  }

  if( (vdata.rechargeResult.state == 8 ) && !vdata.rechargeResult.applyErrorInfo){
    return $infoBox.message.error('请填写拒绝原因')
  }

  vdata.rechargeModalLoading = true
  // $applymentPreUser(vdata.preUserResult.applyId, vdata.preUserResult).then((res) => {
  //   vdata.showPreUserModal = false
  //   $infoBox.message.success('处理完成')
  //   infoTable.value.refTable(true)
  // }).finally(() => {
  //   vdata.preUserModalLoading = false
  // })

}
function rechargeFunc(record){
  vdata.showRechargeModal = true
}


// 显示弹层
function showPreUserModalFunc (recordId) {

  vdata.copyInfoSourceApplyId = '' // 清空副本信息

  vdata.showPreUserModal = true
  vdata.preUserResult = { applyId: recordId }
  sybAqfUserAddOrEditRef.value.show(recordId)
}
// 预审核结果
function preUserHandleOkFunc(){

  if(!vdata.preUserResult.state){
    return $infoBox.message.error('请选择审核结果')
  }

  if( (vdata.preUserResult.state == 8 ) && !vdata.preUserResult.applyErrorInfo){
    return $infoBox.message.error('请填写拒绝原因')
  }

  vdata.preUserModalLoading = true
  // $applymentPreUser(vdata.preUserResult.applyId, vdata.preUserResult).then((res) => {
  //   vdata.showPreUserModal = false
  //   $infoBox.message.success('处理完成')
  //   infoTable.value.refTable(true)
  // }).finally(() => {
  //   vdata.preUserModalLoading = false
  // })

}

function historyFunc(record){
  vdata.visible = true
}
function  updateState (recordId, state) { // 【更新状态】

  const title = state === 1 ? '确认[启用]？' : '确认[停用]？'
  return new Promise<void>((resolve, reject) => {
    $infoBox.confirmDanger(title, '', () => {
          // return reqLoad.updateById(API_URL_MCH_QR_CODE_LIST, recordId, { qrcState: state }).then(res => {
          //   searchFunc()
          //   resolve()
          // }).catch(err => reject(err))
        },
        () => {
          reject(new Error())
        })
  })
}

function tableExportFunc() {
  return $exportExcel(exportExcelUrl.statistic, Object.assign({}, vdata.searchData, {})).then(res => {
    fileDownload(res.data, '用户.xlsx')
  }).catch((error) => { console.log(error) })
}

function setAqfUserInfo(e){
  vdata.showPreUserModal = false
  infoTable.value.refTable(false)
}
</script>
<style>

.modal-box {
  margin-top: -70px !important;
}
</style>
