<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">
          <div style="margin: 10px 30px;">
            分账接收方
          </div>
<!--          :columns="tableColumnsReceiveRatio.pay"-->
          <a-form
              ref="infoFormModel"
              :model="vdata.receiveList"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 15 }">
          <a-table bordered :data-source="vdata.receiveList" :columns="ifCode == 'dgpay'?tableColumnsReceiveRatio.pay:tableColumnsReceiveRatio.dgpay"
                    :pagination="false" style="margin-left: -1px;">
            <template #name="{ record }">
              <a-input v-model:value="record.name" placeholder="请输入个人名称/商户名称" v-if="record.userType == 0" />
              <a-select style="min-width: 300px"  v-model:value="record.name"   v-if="record.userType == 1"  placeholder="请选择商户" show-search @search="handleDivisionNameChange" :filter-option="false">
                <a-select-option v-for="d in vdata.filteredMchNameInfoList" :key="d.mchShortName" v-model:value="d.mchShortName">
                  {{ d.mchShortName }} - {{ d.applyId }}- {{ d.ifName }}
                </a-select-option>
              </a-select>
            </template>
            <template #userType="{ record }">
              <a-radio-group v-model:value="record.userType">
                <a-radio   :value="0" > 个人 </a-radio>
                <a-radio   :value="1" > 商户 </a-radio>
              </a-radio-group>
            </template>

            <template #divisionNo="{ record }">
              <a-input v-model:value="record.divisionNo" v-if="record.userType == 0" placeholder="请输入手机号/商户号" />
              <a-select style="min-width: 300px"  v-model:value="record.divisionNo"   v-if="record.userType == 1"  placeholder="请选择商户" show-search @search="handleDivisionNameChange" :filter-option="false">
                <a-select-option v-for="d in vdata.filteredMchNameInfoList" :key="d.applyId" v-model:value="d.applyId">
                  {{ d.mchShortName }} - {{ d.applyId }}- {{ d.ifName }}
                </a-select-option>
              </a-select>
            </template>
            <template #divisionValue="{ record }">

              <a-input-number v-if="vdata.detailData.divisionMode == 1" addon-after="元" v-model:value="record.divisionValue" :precision="2" :min="0"
                              :step="0.01" placeholder="请输入分账金额" />
              <a-input-number v-if="vdata.detailData.divisionMode == 0"  addon-after="%" v-model:value="record.divisionValue" :precision="2" :min="0"
                              :step="0.01" placeholder="请输入分账比例" />
            </template>

            <template #isCharge="{ record }">
              <a-radio-group v-model:value="record.isCharge" >
                <a-radio   :value="0" > 否 </a-radio>
                <a-radio   :value="1" > 是 </a-radio>
              </a-radio-group>
            </template>

            <template #operation="{ record }">
              <a-popconfirm  title="确认删除吗?" @confirm="onDelete(record.key)">
                <a style="margin-right: 20px;color: #ff4c5b">删除</a>
              </a-popconfirm>
              <a @click="onAdd(0)">添加</a>
            </template>
          </a-table>
          </a-form>

        </a-col>

        <a-form
            ref="infoForm2Model"
            :model="vdata.expendList"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 15 }">
        <a-col :span="24">
          <div style="margin: 10px 30px;">
            分账分出方
          </div>
<!--          :table-columns="tableColumnsCede as any"-->

          <a-table bordered :data-source="vdata.expendList" :columns="ifCode == 'dgpay'?tableColumnsCedeRatio.pay:tableColumnsCedePrice.dgpay"
                   :pagination="false" style="margin-left: -1px;">
            <template #name="{ record }">
              <a-input v-model:value="record.name" v-if="record.userType == 0" placeholder="请输入个人名称/商户名称" />
              <a-select style="min-width: 300px"  v-model:value="record.name"   v-if="record.userType == 1"  placeholder="请选择商户" show-search @search="handleDivisionNoChange" :filter-option="false">
                <a-select-option v-for="d in vdata.filteredMchNoInfoList" :key="d.mchShortName" v-model:value="d.mchShortName">
                  {{ d.mchShortName }} - {{ d.applyId }}- {{ d.ifName }}
                </a-select-option>
              </a-select>
            </template>
            <template #userType="{ record }">
              <a-radio-group v-model:value="record.userType">
                <a-radio   :value="0" > 个人 </a-radio>
                <a-radio   :value="1" > 商户 </a-radio>
              </a-radio-group>
            </template>

            <template #divisionNo="{ record }">
              <a-input v-model:value="record.divisionNo" v-if="record.userType == 0" placeholder="请输入手机号/商户号" />
              <a-select style="min-width: 300px"  v-model:value="record.divisionNo"   v-if="record.userType == 1"  placeholder="请选择商户" show-search @search="handleDivisionNoChange" :filter-option="false">
                <a-select-option v-for="d in vdata.filteredMchNoInfoList" :key="d.applyId" v-model:value="d.applyId">
                  {{ d.mchShortName }} - {{ d.applyId }}- {{ d.ifName }}
                </a-select-option>
              </a-select>
            </template>
            <template #divisionValue="{ record }">
              <a-input v-model:value="record.divisionValue" />
            </template>

            <template #isCharge="{ record }">
              <a-radio-group v-model:value="record.isCharge">
                <a-radio   :value="0" > 否 </a-radio>
                <a-radio   :value="1" > 是 </a-radio>
              </a-radio-group>
            </template>

            <template #operation="{ record }">
              <a-popconfirm  title="确认删除吗?" @confirm="onDelete(record.key,1)">
                <a style="margin-right: 20px;color: #ff4c5b">删除</a>
              </a-popconfirm>
              <a @click="onAdd(1)">添加</a>
            </template>
          </a-table>
        </a-col>
        </a-form>
      </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
} from '@/api/manage'

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

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 tableColumnsReceiveRatio = reactive({
  "pay":[
    { key: 'key', title: '序号', dataIndex: 'key', align: 'center'},
    { key: 'userType',title: '用户类型', dataIndex: 'userType', align: 'center',slots: { customRender: 'userType' } },
    { key: 'name',title: '个人名称/商户名称', dataIndex: 'name', align: 'center',slots: { customRender: 'name' } },
    { key: 'divisionNo',title: ' 手机号/商户号', dataIndex: 'divisionNo', align: 'center',slots: { customRender: 'divisionNo' } },
    { key: 'divisionValue ',title: '分账接收', dataIndex: 'divisionValue ', align: 'center',slots: { customRender: 'divisionValue' }},
    { key: 'isCharge',title: '是否承担手续费 ', dataIndex: 'isCharge', align: 'center',slots: { customRender: 'isCharge' }},
    { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' } },
  ],
  "dgpay":[
    { key: 'key', title: '序号', dataIndex: 'key', align: 'center' },
    { key: 'userType',title: '用户类型', dataIndex: 'userType', align: 'center',slots: { customRender: 'userType' } },
    { key: 'name',title: '个人名称/商户名称', dataIndex: 'name', align: 'center',slots: { customRender: 'name' } },
    { key: 'divisionNo',title: ' 手机号/商户号', dataIndex: 'divisionNo', align: 'center',slots: { customRender: 'divisionNo' } },
    { key: 'divisionValue ',title: '分账接收', dataIndex: 'divisionValue ', align: 'center',slots: { customRender: 'divisionValue' }},
    { key: 'isCharge',title: '是否承担手续费 ', dataIndex: 'isCharge', align: 'center',slots: { customRender: 'isCharge' }},
    { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' } },
  ],
})
//分出方
const tableColumnsCedeRatio = reactive({
  "pay":[
    { title: '序号', dataIndex: 'key', align: 'center' },
    { key: 'userType',title: '用户类型', dataIndex: 'userType', align: 'center',slots: { customRender: 'userType' } },
    { key: 'name',title: '个人名称/商户名称', dataIndex: 'name', align: 'center',slots: { customRender: 'name' } },
    { key: 'divisionNo',title: ' 手机号/商户号', dataIndex: 'divisionNo', align: 'center',slots: { customRender: 'divisionNo' } },
    { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' } },
  ],
  "dgpay":[
    { title: '序号', dataIndex: 'key', align: 'center' },
    { key: 'userType',title: '用户类型', dataIndex: 'userType', align: 'center',slots: { customRender: 'userType' } },
    { key: 'name',title: '个人名称/商户名称', dataIndex: 'name', align: 'center',slots: { customRender: 'name' } },
    { key: 'divisionNo',title: ' 手机号/商户号', dataIndex: 'divisionNo', align: 'center',slots: { customRender: 'divisionNo' } },
    { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' } },
  ],
})

//接收方
const tableColumnsReceivePrice = reactive({
  "pay":[
    { key: 'key', title: '序号', dataIndex: 'key', align: 'center' },
    { key: 'userType',title: '用户类型', dataIndex: 'userType', align: 'center',slots: { customRender: 'userType' } },
    { key: 'name',title: '个人名称/商户名称', dataIndex: 'name', align: 'center',slots: { customRender: 'name' } },
    { key: 'divisionNo',title: ' 手机号/商户号', dataIndex: 'divisionNo', align: 'center',slots: { customRender: 'divisionNo' } },
    { key: 'divisionValue ',title: '分账接收', dataIndex: 'divisionValue ', align: 'center',slots: { customRender: 'divisionValue' }},
    { key: 'isCharge',title: '是否承担手续费 ', dataIndex: 'isCharge', align: 'center',slots: { customRender: 'isCharge' }},
    { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' } },
  ],
  "dgpay":[
    { title: '序号', dataIndex: 'key', align: 'center' },
    { key: 'userType',title: '用户类型', dataIndex: 'userType', align: 'center',slots: { customRender: 'userType' } },
    { key: 'name',title: '个人名称/商户名称', dataIndex: 'name', align: 'center',slots: { customRender: 'name' } },
    { key: 'divisionNo',title: ' 手机号/商户号', dataIndex: 'divisionNo', align: 'center',slots: { customRender: 'divisionNo' } },
    { key: 'divisionValue ',title: '分账接收', dataIndex: 'divisionValue ', align: 'center',slots: { customRender: 'divisionValue' }},
    { key: 'isCharge',title: '是否承担手续费 ', dataIndex: 'isCharge', align: 'center',slots: { customRender: 'isCharge' }},
    { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' } },
  ],
})
//分出方
const tableColumnsCedePrice = reactive({
  "pay":[
    { title: '序号', dataIndex: 'key', align: 'center' },
    { key: 'userType',title: '用户类型', dataIndex: 'userType', align: 'center',slots: { customRender: 'userType' } },
    { key: 'name',title: '个人名称/商户名称', dataIndex: 'name', align: 'center',slots: { customRender: 'name' } },
    { key: 'divisionNo',title: ' 手机号/商户号', dataIndex: 'divisionNo', align: 'center',slots: { customRender: 'divisionNo' } },
    { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' } },
  ],
  "dgpay":[
    { title: '序号', dataIndex: 'key', align: 'center' },
    { key: 'userType',title: '用户类型', dataIndex: 'userType', align: 'center',slots: { customRender: 'userType' } },
    { key: 'name',title: '个人名称/商户名称', dataIndex: 'name', align: 'center',slots: { customRender: 'name' } },
    { key: 'divisionNo',title: ' 手机号/商户号', dataIndex: 'divisionNo', align: 'center',slots: { customRender: 'divisionNo' } },
    { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' } },
  ],
})
const onAdd = (type = 0) => {
  if(type == 0){
    if (!vdata.receiveList) {
      vdata.receiveList = [] as any
    }
    if(vdata.receiveList.length >=9){
      return $infoBox.message.error('分账接收方最多设置 9 个！')
    }
    vdata.receiveList.push({
      name: '',
      userType: 0,
      divisionNo: '',
      divisionValue: '',
      isCharge: 0,
      key: vdata.receiveList[vdata.receiveList.length - 1].key + 1,
    })
  }

  if(type == 1){
    if (!vdata.expendList) {
      vdata.expendList = [] as any
    }
    vdata.expendList.push({
      name: '',
      userType: 0,
      divisionNo: '',
      divisionValue: '',
      isCharge: 0,
      key: vdata.expendList[vdata.expendList.length - 1].key + 1,
    })
  }
}
// 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, userType: 0,name: '', divisionNo: '',divisionValue: '',isCharge: 0, operation: '' }
  vdata.receiveList.push(newData)
  infoTable.value.refTable(true);
}

const vdata: any = reactive({
  filteredMchNameInfoList:[] as any,
  filteredMchNoInfoList:[] as any,
  mchList:[] as any,
  detailData:{} as any,
  payDefines: [] as any,
  confirmLoading: false, // 显示确定按钮loading图标
  isAdd: true, // 新增 or 修改页面标识
  isShow: false, // 是否显示弹层/抽屉
  receiveList:[{ key: 1, userType: 0,name: '', divisionNo: '',divisionValue: '',isCharge: 0, operation: '' }],
  expendList:[{ key: 1, userType: 0,name: '', divisionNo: '',divisionValue: '',isCharge: 0, operation: '' }],
  saveObject: {
    receiveList: [{ key: 1, userType: 0,name: '', divisionNo: '',divisionValue: '',isCharge: 0, operation: '' }],
    expendList: [{ key: 1,userType: 0,name: '', divisionNo: '',divisionValue: '',isCharge: 0, operation: '' }]
  } as any, // 数据对象
  recordId: null, // 更新对象ID
  groupKey: '',
})


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  payFefines() {
  req.list(API_MCH_PAY_DEFINES,{ 'pageSize': -1 }).then(res => {
    vdata.payDefines = res
  })
}

function mchList(){
  req.list(API_URL_MCH_APPLYMENT_LIST, { 'pageSize': -1 ,state:99,ifCode: vdata.detailData.ifCode}).then(res => {
    vdata.mchList =  res.records
    vdata.filteredMchNameInfoList = res.records
    vdata.filteredMchNoInfoList = res.records
  })
}

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

  vdata.recordId = record.id
  vdata.detailData = record
  payFefines()
  mchList()
  // 数据恢复为默认数据
  vdata.saveObject = { id: record.id }

  getMchDivisionTemplateConfig()
  vdata.confirmLoading = false // 关闭loading

  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    if (vdata.saveObject.params) {
      // vdata.saveObject.receiveList = vdata.saveObject.params
    }
  }
  vdata.isShow = true // 立马展示弹层信息
}
function getMchDivisionTemplateConfig(){
  $getMchDivisionTemplateConfig(vdata.recordId).then(config => {

    if(config.expendList == 0 || config.receiveList == 0){
      vdata.expendList = [{ key: 1,userType: 0,name: '', divisionNo: '',divisionValue: '',isCharge: 0, operation: ''}]
      vdata.receiveList = [{ key: 1, userType: 0,name: '', divisionNo: '',divisionValue: '',isCharge: 0, operation: ''}]
      return false;
    }
    const expendList = [] as  any;
      for (let i = 0;i<config.expendList.length;i++){
        expendList.push({
          key: i+1 ,
          userType: config.expendList[i].userType,
          name: config.expendList[i].name,
          divisionNo: config.expendList[i].divisionNo,
          divisionValue: config.expendList[i].divisionValue,
          isCharge:  config.expendList[i].isCharge,
          operation: ''
        })
      }
      vdata.expendList = expendList;
    const receiveList = []  as  any;
    for (let i = 0;i<config.receiveList.length;i++){
      receiveList.push({
        key:  i+1,
        userType: config.receiveList[i].userType,
        name: config.receiveList[i].name,
        divisionNo: config.receiveList[i].divisionNo,
        divisionValue: config.receiveList[i].divisionValue,
        isCharge:  config.receiveList[i].isCharge,
        operation: ''
      })
    }
    vdata.receiveList = receiveList;
  })
}
function handleOkFunc() { // 点击【确认】按钮事件
  vdata.confirmLoading = true // 显示loading

  vdata.saveObject.id = vdata.recordId
  vdata.saveObject.receiveList = vdata.receiveList
  vdata.saveObject.expendList = vdata.expendList
  req.add(API_URL_DIVISION_TEMPLATE_SAVE_CONFIG, vdata.saveObject).then(res => {
    message.success('添加成功')
    vdata.isShow = false
    props.callbackFunc() // 刷新列表
  }).catch(res => { vdata.confirmLoading = false })
}
//门店搜索
const handleDivisionNameChange = (value) => {
  vdata.filteredMchNameInfoList = [];
  vdata.mchList.forEach((item: { mchShortName: string | any[], applyId:  any[] },index) => {
    if (item.mchShortName.includes(value) || item.applyId.toString().includes(value) ) {
      vdata.filteredMchNameInfoList.push(vdata.mchList[index]);
    }
  });
};
const handleDivisionNoChange = (value) => {
  vdata.filteredMchNoInfoList = [];
  vdata.mchList.forEach((item: { mchShortName: string | any[], applyId:  any[] },index) => {
    if (item.mchShortName.includes(value) || item.applyId.toString().includes(value) ) {
      vdata.filteredMchNoInfoList.push(vdata.mchList[index]);
    }
  });
};
function  updateState (fee) { // 【更新状态】

}
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;
}

</style>