<template>
  <a-drawer
      v-model:visible="vdata.isShow"
      :title="vdata.isAdd ? '新增路由配置' : '编辑路由配置'"
      width="80%"
      :mask-closable="false"
      @close="vdata.isShow = false"
  >

      <a-row  >


        <a-col :span="24">
          <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">编辑路由门店</a-divider>

<!--          <a-col :sm="12">-->
<!--            <a-descriptions>-->
<!--              <a-descriptions-item label="策略规则" >-->
<!--               <div style="display: block">-->
<!--                 <div>-->
<!--                   <span v-if="vdata.detailData.ruleStrategy == 'TRADE_NUM'">按收款笔数</span>-->
<!--                   <span v-if="vdata.detailData.ruleStrategy == 'TRADE_AMOUNT'">按累计收款金额</span>-->
<!--                   <span v-if="vdata.detailData.ruleStrategy == 'TRADE_TIME'">按收款时间</span>-->
<!--                   <span v-if="vdata.detailData.ruleStrategy == 'TRADE_AMOUNT_INTERVAL'">按交易金额区间</span>-->
<!--                 </div>-->
<!--                 <div>-->
<!--                   <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 'TRADE_NUM'">设置允许用户在一定时间内（如每日、每周、每月）的最大收款笔数。</span>-->
<!--                   <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 'TRADE_AMOUNT'">设置用户在一定时间内的累计收款金额上限。</span>-->
<!--                   <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 'TRADE_TIME'">设置允许用户收款的有效时间段。</span>-->
<!--                   <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 'TRADE_AMOUNT_INTERVAL'">设置不同交易金额区间对应的路由策略。</span>-->
<!--                 </div>-->
<!--               </div>-->
<!--              </a-descriptions-item>-->
<!--            </a-descriptions>-->
<!--&lt;!&ndash;            <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 5">选择适用的交易类型（如微信、支付宝等）。</span>&ndash;&gt;-->
<!--          </a-col>-->
          <a-col :sm="24">

            <a-form-item label="策略规则：" name="ruleStrategy" >
              <div style="display: grid">

                <a-select v-model:value="vdata.detailData.ruleStrategy" :disabled="vdata.ruleStrategy" placeholder="策略规则" @change="getRuleStrategy">
                  <a-select-option value="TRADE_NUM">按收款笔数</a-select-option>
                  <a-select-option value="TRADE_AMOUNT">按累计收款金额</a-select-option>
                  <a-select-option value="TRADE_TIME">按收款时间</a-select-option>
                  <a-select-option value="TRADE_AMOUNT_INTERVAL">按交易金额区间</a-select-option>
                </a-select>
                <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 'TRADE_NUM'">设置允许用户在一定时间内（如每日、每周、每月）的最大收款笔数。</span>
                <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 'TRADE_AMOUNT'">设置用户在一定时间内的累计收款金额上限。</span>
                <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 'TRADE_TIME'">设置允许用户收款的有效时间段。</span>
                <span  class="jeepay-tip-text" v-if="vdata.detailData.ruleStrategy == 'TRADE_AMOUNT_INTERVAL'">设置不同交易金额区间对应的路由策略。</span>
                <span  class="jeepay-tip-text" v-if="vdata.saveObject.rule == 5">选择适用的交易类型（如微信、支付宝等）。</span>

              </div>
            </a-form-item>
          </a-col>
          <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">策略门店规则设置</a-divider>

          <a-form
              ref="infoFormModel"
              :model="vdata.receiveList"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 15 }">
          <a-table bordered :data-source="vdata.receiveList" :columns="tableColumns"
                    :pagination="false" style="margin-left: -1px;">
            <template #headerCell="{ column }">
              <span v-if="column.tooltipTitle">
                {{ column.title }}
                <a-tooltip :title="column.tooltipTitle"><info-circle-outlined /></a-tooltip>
              </span>
            </template>
            <template #storeId="{ record }">
               <a-select class="tb_width_80"  v-model:value="record.storeId"    placeholder="请选择商户" show-search @change="handleStoreChange" @search="handleDivisionNameChange" :filter-option="false">
                <a-select-option v-for="d in vdata.filteredMchNameInfoList" :key="d.mchShortName" v-model:value="d.storeId">
                  {{ d.storeName }} - {{ d.storeId }}- {{ d.ifName }}
                </a-select-option>
              </a-select>
            </template>
            <template #value="{ record }" >
              <a-input-number class="tb_width_80" addon-after="笔" :min="1" :precision="0" v-model:value="record.value" v-if="vdata.detailData.ruleStrategy == 'TRADE_NUM'" placeholder="请输入交易笔数"/>
              <a-input-number class="tb_width_80"  addon-after="元" :min="1" :precision="2" v-model:value="record.value" v-if="vdata.detailData.ruleStrategy == 'TRADE_AMOUNT'" placeholder="请按照门店收款情况预估，输入收款金额"/>
<!--              <a-input-number addon-after="笔" :min="1" v-model:value="record.content" v-if="vdata.saveObject.rule == 1" placeholder="请输入交易笔数"/>-->
              <div v-if="vdata.detailData.ruleStrategy == 'TRADE_TIME'" class="con-flex-div" >
                <a-time-picker class="con-flex-span"  v-model:value="record.value" format="HH:mm" />
                <span class="rule-span">至</span>
                <a-time-picker class="con-flex-span"  v-model:value="record.value1" format="HH:mm" />
              </div>
              <div v-if="vdata.detailData.ruleStrategy == 'TRADE_AMOUNT_INTERVAL'" class="con-flex-div" >
                <a-input-number class="con-flex-span"  addon-after="元" :min="1" :precision="2"  v-model:value="record.value" placeholder="请输入最小金额"/>
                <span class="rule-span">至</span>
                <a-input-number class="con-flex-span"  addon-after="元" :min="1" :precision="2"  v-model:value="record.value1"  placeholder="请输入最大金额"/>
              </div>
<!--              <div v-if="vdata.saveObject.rule == 5" >-->
<!--                <a-select class="con-flex-span tb_width_80"   v-model:value="record.content"  mode="multiple" style="width: 100%"  placeholder="请选择配置"  :options="vdata.payWay"  />-->
<!--              </div>-->
<!--              <a-input-number addon-after="笔" :min="1" v-model:value="record.content" v-if="vdata.saveObject.rule == 1" placeholder="请输入交易笔数"/>-->
            </template>

            <template #timeLimit="{  record }">
              <a-select class="con-flex-span tb_width_80"   v-model:value="record.timeLimit"  style="width: 100%"  placeholder="请选择时限"    >
                <option value="不限">不限</option>
                <option value="日">日</option>
                <option value="周">周</option>
                <option value="月">月</option>
              </a-select>
            </template>

            <template #typeStrategy="{  record }">
              <a-select class="con-flex-span tb_width_80"   v-model:value="record.typeStrategy"  mode="multiple" style="width: 100%"  placeholder="请选择支付类型"  :options="vdata.payWay"  />
            </template>

            <template #rate="{  record }">
              <a-input-number class="tb_width_80" addon-after="%" :min="0" :max="1" :precision="2" v-model:value="record.record"  placeholder="请输入付款率"/>
            </template>
            <template #state="{  record }">
              <JeepayTableColState :state="record.state" :showSwitchType="true"  />
<!--              <a-select class="con-flex-span tb_width_80"   v-model:value="record.state"  mode="multiple" style="width: 100%"  placeholder="请选择支付类型"  :options="vdata.payWay"  />-->
            </template>


            <template #operation="{ record }">
              <a @click="onAdd(0)" class="operation-a" >添加</a>
              <a-popconfirm  title="确认删除吗?" @confirm="onDelete(record.key)">
                <a  class="operation-a"  style="color: #ff4c5b"  v-if="record.key != 1">删除</a>
              </a-popconfirm>
              <a @click="onMove(record,1)"  v-if="record.key != 1" class="operation-a"  >上移</a>
              <a @click="onMove(record,0)"  v-if="record.key != vdata.receiveList[vdata.receiveList.length-1].key && record.key != 1" class="operation-a"  >下移</a>
            </template>
          </a-table>
          </a-form>

        </a-col>

      </a-row>


    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="vdata.isShow = false"><close-outlined /> 取消</a-button>
      <a-button type="primary" :loading="vdata.confirmLoading" @click="handleOkFunc"><check-outlined /> 保存</a-button>
    </div>
  </a-drawer>
</template>
<script lang="ts" setup>
import {
  API_MCH_PAY_DEFINES,
  API_URL_DIVISION_TEMPLATE_SAVE_CONFIG,
  API_URL_DIVISION_TEMPLATE_EDIT,
  API_URL_MCH_QR_CODE_LIST,
  req,
  reqLoad,
  $getMchDivisionTemplateConfig,
  API_URL_MCH_STORE_LIST,
  API_URL_MCH_APPLYMENT_LIST,
  $getMchRouteConfig,
   $getMchRouteSetConfigSave
} from '@/api/manage'

import { reactive, ref, getCurrentInstance, computed ,watch} from 'vue'
import {message} from "ant-design-vue";
import moment from 'moment';

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

const infoFormModel = ref()
const infoForm2Model = ref()
const ifCode = ref('')

const props = defineProps({
  callbackFunc: { type: Function, default: () => { } },
  columnsType: { type: Number, default: 0 }
})

//接收方
const tableColumns = reactive([
  // { key: 'key', title: '序号', dataIndex: 'key', align: 'center',width:'5%'},
  { key: 'storeId',title: '门店名称', dataIndex: 'storeId', align: 'center',slots: { customRender: 'storeId' },width:'30%' },
  { key: 'value',title: '配置', dataIndex: 'value', align: 'center',slots: { customRender: 'value' } ,width:'20%'},
  { key: 'timeLimit',title: '时效', dataIndex: 'timeLimit', align: 'center',slots: { customRender: 'timeLimit' } ,width:'20%'},
  { key: 'typeStrategy',title: '支付类型', dataIndex: 'typeStrategy', align: 'center',slots: { customRender: 'typeStrategy' } ,width:'15%'},
  { key: 'rate',title: '付款率', dataIndex: 'rate', tooltipTitle: '付款率低于设置的，自动下架', align: 'center',slots: { customRender: 'rate' } ,width:'10%'},
  { key: 'state',title: '状态', dataIndex: 'state', align: 'center',slots: { customRender: 'state' } ,width:'10%'},
  { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' },width:'15%' },
])

const onAdd = (type = 0) => {
    if (!vdata.receiveList) {
      vdata.receiveList = [] as any
    }
    if(vdata.receiveList.length >=9){
      return $infoBox.message.error('分账接收方最多设置 9 个！')
    }
    vdata.receiveList.push({
      key: vdata.receiveList[vdata.receiveList.length - 1].key + 1,
      storeId: '',
      value: '',
      value1:"",
      rate:"",
      state:"",
      typeStrategy: [] as any,
    })
  console.log(vdata.receiveList,'vdata.receiveList')

}
// const tableColumnsReceive=()=>{
//
// console.log(tableColumnsReceiveRatio,'tableColumnsReceivetableColumnsReceivetableColumnsReceive')
//   return tableColumnsReceiveRatio.pay as any
// }
// function tableColumnsCede(){
//   return tableColumnsCedePrice.pay
// }

//
const infoTable = ref();

const handleAdd = () => {
  // if (vdata.saveObject.appPlaceType == '1' && vdata.saveObject.receiveList.length > 1) {
  //   return $infoBox.message.error('卡片模版最多添加两条记录！')
  // }

  const newData = { key: 1, storeId: '',rate:"",state:"",value: '' as any, typeStrategy: [] as any,value1:'', operation: '' }
  vdata.receiveList.push(newData)
  infoTable.value.refTable(true);
}

const vdata: any = reactive({
  ruleStrategy:true,
  filteredMchNameInfoList:[] as any,
  filteredMchNoInfoList:[] as any,
  storeList:[] as any,
  detailData:{} as any,
  payDefines: [] as any,
  confirmLoading: false, // 显示确定按钮loading图标
  isAdd: true, // 新增 or 修改页面标识
  isShow: false, // 是否显示弹层/抽屉
  receiveList:[{ key: 1, storeId: '',rate:"",state:"",value: '' as any, typeStrategy: [] as any, value1:'',operation: ''}],
  expendList:[{ key: 1, storeId: '',rate:"",state:"",value: '' as any, typeStrategy: [] as any, value1:'',operation: ''}],
  saveObject: {
    receiveList: [{ key: 1, storeId: '',rate:"",state:"",value: '' as any, typeStrategy: [] as any, value1:'',operation: ''}],
    expendList: [{ key: 1, storeId: '',rate:"",state:"",value: '' as any, typeStrategy: [] as any, value1:'',operation: ''}]
  } as any, // 数据对象
  recordId: null, // 更新对象ID
  groupKey: '',
  payWay:[
    {
      value: 'WECHAT',
      label: '微信',
    },
    {
      value: 'ALIPAY',
      label: '支付宝',
    }
  ]
})


async function reqTableDataFunc(){
return {
     hasNext:true,
     records:vdata.receiveList,
  }
}
const onDelete = (key,type=0) => {

  if(type == 0){
    if (vdata.receiveList.length <= 1) {
      $infoBox.message.error('最少保留一项')
      return false
    }
    vdata.receiveList = vdata.receiveList.filter(item => item.key !== key)
  }else{
    if (vdata.expendList.length <= 1) {
      $infoBox.message.error('最少保留一项')
      return false
    }
    vdata.expendList = vdata.expendList.filter(item => item.key !== key)
  }
}
const rules = {
}

function storeList(){
  req.list(API_URL_MCH_STORE_LIST, { 'pageSize': -1,autoConfigMchAppId:vdata.detailData.appid }).then(res => {
    vdata.storeList =  res.records
    vdata.filteredMchNameInfoList = res.records
    vdata.filteredMchNoInfoList = res.records
  })
}

function show( record) { // 弹层打开事件
  vdata.ruleStrategy = true
  if (infoFormModel.value !== undefined) {
    infoFormModel.value.resetFields()
  }
  vdata.groupKey = 'faceAdvert'
  vdata.isAdd = !record

  vdata.recordId = record.id
  vdata.detailData = record
  storeList()
  // 数据恢复为默认数据
  vdata.saveObject = record

  vdata.confirmLoading = false // 关闭loading

  vdata.receiveList = [{ key: 1, storeId: '',rate:"",state:"",value: '' as any, typeStrategy: [] as any, value1:'',operation: ''}]
  getMchRouteeConfig()
  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    if (vdata.saveObject.params) {
      // vdata.saveObject.receiveList = vdata.saveObject.params
    }
  }
  vdata.isShow = true // 立马展示弹层信息
}
function getMchRouteeConfig(){
  $getMchRouteConfig(vdata.detailData.id).then(config => {

    if(config.configList.length == 0){
      vdata.ruleStrategy = false;
      vdata.receiveList = [{ key: 1, storeId: '',rate:"",state:"",value: '' as any, typeStrategy: [] as any,value1:'', operation: ''}]
      return false;
    }
    const receiveList = []  as  any;
    for (let i = 0;i<config.configList.length;i++){
      // moment('12:08', 'HH:mm')
      if(vdata.detailData.ruleStrategy == 'TRADE_TIME'){
        receiveList.push({
          key:  i+1,
          storeId: config.configList[i].storeId,
          value:  moment(config.configList[i].value[0], 'HH:mm'),
          value1:  moment(config.configList[i].value[1], 'HH:mm'),
          typeStrategy: config.configList[i].typeStrategy,
          operation: ''
        })
      }else{
        receiveList.push({
          key:  i+1,
          storeId: config.configList[i].storeId,
          value:  config.configList[i].value[0],
          value1: config.configList[i].value[1],
          typeStrategy: config.configList[i].typeStrategy,
          operation: ''
        })
      }
      // receiveList.push({
      //   key:  i+1,
      //   storeId: config.configList[i].storeId,
      //   value:  value,
      //   value1: value1,
      //   typeStrategy: config.configList[i].typeStrategy,
      //   operation: ''
      // })
    }
    vdata.receiveList = receiveList;
  })
}
function handleOkFunc() { // 点击【确认】按钮事件
  vdata.confirmLoading = false // 显示loading

  const configList = vdata.receiveList
  const list = [] as any;
  for (var i=0;i<configList.length;i++){
    console.log(configList[i].value,'configList[i].value')
    if(!configList[i].storeId){
      message.error("请选择门店")
      return false;
    }
      if(!configList[i].value){
          message.error("请输入配置")
          return false;
      }
      if(configList[i].typeStrategy.length == 0){
        message.error("请选择支付配置")
        return false;
      }

       let value = [configList[i].value] as any;

       if(!configList[i].value1){
         if(vdata.detailData.ruleStrategy == 'TRADE_TIME' || vdata.detailData.ruleStrategy == 'TRADE_AMOUNT_INTERVAL'){
           message.error("请输入配置")
           return false;
         }
       }else{
         value.push(configList[i].value1)
       }
    if(vdata.detailData.ruleStrategy == 'TRADE_TIME' || vdata.detailData.ruleStrategy == 'TRADE_AMOUNT_INTERVAL'){
      // const value = [] as any;
      const value1 =  dateFormat(configList[i].value);
      const value2 = dateFormat(configList[i].value1);
      value = [value1,value2] as any;
    }
       console.log(value,'value')
       list.push({
         storeId: configList[i].storeId,
         value: value,
         typeStrategy: configList[i].typeStrategy,
         rate: configList[i].storeId,
         state: configList[i].state,
         sortNum: i,
       })
  }
  console.log(list,'listlistlist')
  const data = {
    ruleStrategy:vdata.detailData.ruleStrategy,
    configList:list,
  }

  $getMchRouteSetConfigSave(vdata.detailData.id, data).then(res => {
    message.success('添加成功')
    props.callbackFunc() // 刷新列表
  })
  // req.add(API_URL_DIVISION_TEMPLATE_SAVE_CONFIG, vdata.saveObject).then(res => {
  //   message.success('添加成功')
  //   vdata.isShow = false
  //   props.callbackFunc() // 刷新列表
  // }).catch(res => { vdata.confirmLoading = false })
}
function dateFormat(time) {
  let date = new Date(time);
  let year = date.getFullYear();
  let wk = date.getDay()
  /* 在日期格式中，月份是从0开始的，因此要加0
  * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
  * */
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
  let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  let week = weeks[wk]
  // 拼接
  return  hours + ":" + minutes;
  // return year + "年" + month + "月" + day + "日" + " " + hours + ":" + minutes + ":" + seconds + ' ' + week;
}
const handleStoreChange=(value)=>{
  const key = [];
  vdata.receiveList.forEach((vv,kk) => {
    console.log(vv,'v1')
    const index = kk as any;
    if(vv.storeId == value){
      key.push(index as any)
      // message.error("已存在门店规格")
      return false;
    }
  })
  if(key.length > 1){
    message.error("已存在门店配置")
    vdata.receiveList[key.length-1].storeId = ''
  }
  console.log(key,'key')
}
//门店搜索
const handleDivisionNameChange = (value) => {
  vdata.filteredMchNameInfoList = [];
  vdata.storeList.forEach((item: { mchShortName: string | any[], storeId:  any[] },index) => {
    if (item.mchShortName.includes(value) || item.storeId.toString().includes(value) ) {

      vdata.filteredMchNameInfoList.push(vdata.storeList[index]);
    }
  });
};
const handleDivisionNoChange = (value) => {
  vdata.filteredMchNoInfoList = [];
  vdata.storeList.forEach((item: { mchShortName: string | any[], storeId:  any[] },index) => {
    if (item.mchShortName.includes(value) || item.storeId.toString().includes(value) ) {
      vdata.filteredMchNoInfoList.push(vdata.storeList[index]);
    }
  });
};

//排序
function onMove(record,type){
  console.log(record.key,record.userType,'key')
  const key = record.key
  let receiveList = vdata.receiveList
  vdata.receiveList = [];
  let list = [];
  for (let i=0;i<receiveList.length;i++){
       if(receiveList[i].key == key){
          if(parseInt(type) === 1){
            receiveList[i].key = parseInt(receiveList[i-1].key) - 1
          }else{
            receiveList[i].key = parseInt(receiveList[i+1].key) + 1
          }
       }
  }
  receiveList.sort((a, b) => {
    return a.key - b.key;
  });
  receiveList.forEach((item,index) => {
    item.key = index+1
    vdata.receiveList.push(item)
  });
}
function  updateState (fee) { // 【更新状态】

}
function getRuleStrategy(e){
  console.log(e,'getRuleStrategy')
  const receiveList = [] as any
   for (var i=0;i<vdata.receiveList.length;i++){
     receiveList.push({
       storeId: vdata.receiveList[i].storeId,
       value: '',
       value1: '',
       rate: '',
       state: '',
       typeStrategy: vdata.receiveList[i].typeStrategy,
     })
   }
  vdata.receiveList = receiveList
}
defineExpose({ show })
</script>
<style lang="less" scoped>
.ant-btn-dangerous {
  position: absolute;
  right: 50px;
}

.ant-row-space-between {
  position: relative;
}
:deep(.jeepay-table-top-row){
  display: none;
}
.rule-span{
  padding: 5px 10px;
}
.con-flex-span{
  flex: 1 !important;
}
.tb_width_80{
  width: 80% !important;
}
.con-flex-div{
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
}
.operation-a{
  margin-right: 10px;
}
</style>