<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['mchNo']" v-if="props.configMode != 'mch'" :placeholder="'用户号/名称/手机号'" />
        <jeepay-text-up v-model:value="data.searchData['routeId']"  :placeholder="'策略名称/ID'" />


        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="data.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>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
          ref="infoTable"
          :init-data="true"
          :req-table-data-func="reqTableDataFunc"
          :statisticsIsShow="true"
          :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   type="primary"  v-if="$access('ENT_ROUTE_ADD') && props.configMode == 'mch'"    class="mg-b-30"  @click="addFunc()"  >  <plus-outlined /> 新建  </a-button>
          </div>
        </template>
        <template #bodyCell="{column,record}">



          <template v-if="column.key === 'routeId'">
            <b @click="editFunc(record)"> <a > {{ record.routeId }}</a>  </b>
          </template>
          <template v-if="column.key === 'name'">
            {{ record.name }}
            <QrcodeOutlined style="font-size: 16px;margin-left: 5px" v-if="props.configMode != 'mch'" @click="showQrImgFunc(record.routeId)" />
          </template>
          <template v-if="column.key === 'succAmount'">
<!--            <b style="color: #15B86C;">￥{{  (record.succAmount / 100).toFixed(2) }}/￥{{   (record.totalAmount / 100).toFixed(2) }}</b>-->
            <b style="color: #15B86C;">￥{{  (record.succAmount / 100).toFixed(2) }}</b>
          </template>
          <template v-if="column.key === 'totalNum'">
            <b style="color: #15B86C;">{{ record.succNum }}/{{ record.totalNum }}</b>
          </template>

          <template v-if="column.key === 'succRate'">
            <b style="color: #FF8800;">{{ record.succRate }}%</b>
          </template>
          <template v-if="column.key === 'num'">
           <b> <a  @click="storeFunc(record,1)">{{ record.num }}</a></b>
          </template>
          <template v-if="column.key === 'storeNum'">
            <b>  <a @click="storeFunc(record)">{{ record.storeNum }}</a></b>
          </template>

          <template v-if="column.key === 'state'">
            <JeepayTableColState :state="record.state" :show-switch-type="true" :on-change="(state) => { return updateState(record, state,0)}" />
          </template>
          <template v-if="column.key === 'isDefault'">
            <a-badge status="error" text="否" v-if="record.isDefault === 0"/>
            <a-badge status="processing" text="是" v-if="record.isDefault === 1"/>
<!--            <JeepayTableColState :isDefault="record.isDefault" :show-switch-type="true" :on-change="(isDefault) => { return updateState(record, isDefault,1)}" />-->
          </template>

          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button type="link" @click="storeFunc(record)">路由配置</a-button>
              <a-button v-if="$access('ENT_ROUTE_EDIT')" type="link" @click="editFunc(record)">修改</a-button>
              <a-button v-if="$access('ENT_ROUTE_DEL')" type="link"  style="color: red" @click="delFunc(record)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <SybProductTradeRouteStrategyAddOrEdit ref="sybProductTradeRouteStrategyAddOrEdit" @itemRender="getOnClose" :configMode="props.configMode" :callbackFunc="getOnClose"  />

  </page-header-wrapper>
</template>
<script setup lang="ts">
import {
  req,
  reqLoad,
  $exportExcel,
  exportExcelUrl,
  API_URL_PAY_ORDER_ROUTE_COUNT,
  API_URL_PAY_ORDER_ROUTE_DEL,
  API_URL_PAY_ORDER_ROUTE_LIST,
  API_URL_PAY_ORDER_ROUTE_SAVE,
  $getAqfRouteQrcode
} from '@/api/manage'
import {reactive, ref, getCurrentInstance, onMounted} from 'vue'
import fileDownload from "js-file-download";
import {message} from "ant-design-vue";
import { useRouter, useRoute } from 'vue-router'
const router = useRouter() //这是全部路由

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

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


const tableColumns = reactive([
  {key:'routeId', title: '策略ID',   dataIndex: 'routeId',align: 'center' },
  {key:'name', title: '策略名称',   dataIndex: 'name',align: 'center' },
  {key:'storeNum', title: '运行门店', dataIndex: 'storeNum',align: 'center' },
  {key:'num', title: '运行次数', dataIndex: 'num',align: 'center' },
  {key:'succAmount', title: '成交金额', dataIndex: 'succAmount',align: 'center' },
  {key:'totalNum', title: '成交笔数/总订单数', dataIndex: 'totalNum',align: 'center' },
  {key:'succRate', title: '成功率', dataIndex: 'succRate',align: 'center' },
  {key:'state', title: '状态', dataIndex: 'state',align: 'center' },
  {key:'isDefault', title: '是否默认', dataIndex: 'isDefault',align: 'center' },
  {key:'createdAt', title: '创建时间', dataIndex: 'createdAt',align: 'center' },
  {key: 'op',title: '操作',   fixed: 'right',align: 'center' }
])

const infoTable = ref()
const sybProductTradeRouteStrategyAddOrEdit = ref()

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

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

  showPreRouteModal: false,  // 是否显示预审核弹层
  preRouteModalLoading: false,  // loading
  preRouteResult: {}, // 预审核结果
})

// 请求table接口数据
function reqTableDataFunc(params){
  reqTableCountFunc(params)
  return req.list(API_URL_PAY_ORDER_ROUTE_LIST, params)
}

function reqTableCountFunc(params: any) {
  params.method = 'transaction'
  req.list(API_URL_PAY_ORDER_ROUTE_COUNT, params).then(res => {
    count.value = [
      {title: '总交易金额', symbol: 'add', textColor: '#1A66FF', content: ((res.totalAmt) / 100).toFixed(2)},
      {type: 'line'},
      {title: '总交易笔数', content: (res.totalNum)},
      {type: 'line'},
      {title: '总成交金额', symbol: 'sub', content: ((res.totalSuccAmt) / 100).toFixed(2)},
      {type: 'line'},
      {title: '总成交笔数', content: (res.totalSuccNum)},
    ]
  })
}
function searchFunc() { // 点击【查询】按钮点击事件
  data.btnLoading = true // 打开查询按钮的loading
  infoTable.value.refTable(true)
}
function storeFunc(record,type=0) { // 点击【查询】按钮点击事件
  if(type == 1){
    router.push({
      path:'/tradeRouteStrategyLog',
      query:{routeId:record.routeId}
    })
  }else{
    router.push({
      path:'/tradeRouteList',
      query:{routeId:record.routeId}
    })
  }

}

function editFunc(record){

  sybProductTradeRouteStrategyAddOrEdit.value.show(record)
}
function delFunc(record){
  if(record.storeNum > 0){
    $infoBox.message.error("该策略下已绑定门店，请在支付路由管理内解绑后删除！");
    return false;
  }
  $infoBox.confirmDanger(
      "确认删除？",
      "",
      () => {
        return req
            .delById(API_URL_PAY_ORDER_ROUTE_DEL, record.routeId)
            .then((res) => {
              $infoBox.message.success("删除成功！");
              infoTable.value.refTable(false);
            })
            .catch((err) => {});
      },
      () => {
        console.log(1111);
      }
  );
}
function tableExportFunc() {
  return $exportExcel(exportExcelUrl.statistic, Object.assign({}, vdata.searchData, {})).then(res => {
    fileDownload(res.data, '商户统计.xlsx')
  }).catch((error) => { console.log(error) })
}
function addFunc(){
  sybProductTradeRouteStrategyAddOrEdit.value.show()
}
function getOnClose(e){
  console.log(1111111111)
  infoTable.value.refTable(true)
}
function  updateState (record, state,type) { // 【更新状态】

  const title = state === 1 ? '确认[启用]？' : '确认[停用]？'
  return new Promise<void>((resolve, reject) => {
    $infoBox.confirmDanger(title, '', () => {
          record.state = state
          return reqLoad.updateById(API_URL_PAY_ORDER_ROUTE_SAVE, record.routeId, record).then(res => {
            searchFunc()
            resolve()
          }).catch(err => reject(err))
        },
        () => {
          reject(new Error())
        })
  })
}
// 显示二维码图片
function showQrImgFunc(recordId){
  $getAqfRouteQrcode(recordId).then((res) => {
    $viewerApi({images: [res]})
  })
}
</script>
