<template>
  <a-drawer
      v-model:visible="vdata.isShow"
      :title=" vdata.isAdd ? '新增分账模版' : '修改分账模版' "
      :confirmLoading="vdata.confirmLoading"
      @ok="handleOkFunc"
      @close="onClose"
      width="50%"
  >
    <a-form ref="infoFormModel" layout="vertical" :model="vdata.saveObject"  :rules="vdata.rules">

      <a-row justify="space-between" type="flex">
        <a-col :span="11">
          <a-form-item label="分账模版名称：" name="name">
            <a-input v-model:value="vdata.saveObject.name" placeholder="请输入分账模版名称" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="支付通道：" name="ifCode">
            <a-select v-model:value="vdata.saveObject.ifCode" placeholder="支付通道" @change="getIfCode">
              <a-select-option  v-for="item in vdata.payDefines" :key="item.ifCode" :value="item.ifCode"   :disabled="item.ifCode != 'yspay' && item.ifCode != 'dgpay'">{{ item.ifName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="vdata.saveObject.divisionMode==1?24:11">
          <a-form-item label="分账模式：" name="divisionMode" >
            <div style="display: grid;">
              <a-radio-group v-model:value="vdata.saveObject.divisionMode">
                <a-radio v-for="item in vdata.modeList" :key="item.value" :value="item.value"  :disabled="item.value == 1"  >
                  {{ item.name }}
                </a-radio>
              </a-radio-group>
              <span class="jeepay-tip-text" v-if="vdata.saveObject.divisionMode == 0">({{ vdata.saveObject.ifCode === 'yspay'?'默认分账比例为30%，最高可申请至100%':vdata.saveObject.ifCode === 'dgpay'?'分账比例最高为30%':'' }})</span>
            </div>
          </a-form-item>

        </a-col>
        <a-col :span="11" v-if="vdata.saveObject.divisionMode == 1">
          <a-form-item label="最小支付金额：" name="minAmount" >
            <a-input-number  addon-after="元" :min="0" :precision="2"  v-model:value="vdata.saveObject.minAmount" placeholder="请输入最小支付金额" />
          </a-form-item>
        </a-col>
        <a-col :span="11" v-if="vdata.saveObject.divisionMode == 1">
          <a-form-item label="分账金额："   name="divisionAmount" >
            <a-input-number  addon-after="元" :min="0" :precision="2" v-model:value="vdata.saveObject.divisionAmount" placeholder="请输入分账金额" />
          </a-form-item>

        </a-col>
        <a-col :span="11">
          <a-form-item label="分账类型：" name="divisionType">
            <div style="display: grid;">
              <a-radio-group v-model:value="vdata.saveObject.divisionType">
                <a-radio  v-for="item in vdata.typeList" :key="item.value" :value="item.value" :disabled="item.value ==3 && vdata.saveObject.ifCode == 'dgpay'" >
                  {{ item.name }}
                </a-radio>
              </a-radio-group>
              <span class="jeepay-tip-text" v-if="vdata.saveObject.divisionType == 0">(订单产生后立马发起分账指令，资金D1结算)</span>
              <span class="jeepay-tip-text"  v-if="vdata.saveObject.divisionType == 1">({{ vdata.saveObject.ifCode === 'yspay'?'订单产生后90天内都可以发起分账指令，资金D1结算，如90天内未发起分账指令，资金于第二个工作日自动结算至收款商户的结算银行卡':vdata.saveObject.ifCode === 'dgpay'?'订单产生后180天内都可以发起分账指令，资金D1结算，如180天内未发起分账指令，资金于第二个工作日自动结算至收款商户的结算银行卡':'' }})</span>
              <span class="jeepay-tip-text"  v-if="vdata.saveObject.divisionType == 2 && vdata.saveObject.ifCode === 'yspay'">({{ vdata.saveObject.ifCode === 'yspay'?'订单产生后立马发起分账指令，资金D0结算':'' }})</span>
            </div>
          </a-form-item>

        </a-col>

        <a-col :span="11">
          <a-form-item label="自动分账组" name="isAuto">
            <a-radio-group v-model:value="vdata.saveObject.isAuto">
              <a-radio :value="1">是</a-radio> <a-radio :value="0">否</a-radio>
            </a-radio-group>
            <div class="jeepay-tip-text" style="margin-left:-10px; margin-top:20px">
              <p>1. 自动分账组: 当订单分账模式为自动分账，该组下的所有正常分账状态的账号将作为订单分账对象</p>
              <p>2. 每个商户仅有一个自动分账组， 当该组更新为自动分账时，其他组将改为否</p>
            </div>
          </a-form-item>

        </a-col>
        <a-col :span="11">
          <a-form-item label="分账场景说明函：" name="url">
            <JeepayUpload v-model:src="vdata.saveObject.url" bizType="applyment" />
            <span class="jeepay-tip-text" >(示例查看)</span>
          </a-form-item>
        </a-col>
        <a-col :span="24" style="margin:10px 0px">
          <a-form-item label="分出方" name="storeIdList">
            <a-textarea v-if="vdata.saveObject.storeName" v-model:value="vdata.saveObject.storeName"
                        disabled />
            <a-button  style="margin-top: 5px" type="primary" @click="showStoreIdSelectPackageModel">{{
                vdata.isAdd ?
                    '选择绑定门店' : '重新绑定门店' }}</a-button>
          </a-form-item>
        </a-col>

        <a-col :span="24" style="margin:10px 0px">
          <a-form-item label="接收方" name="storeIdList">

            <a-table bordered :data-source="vdata.receiverList" :columns="vdata.receiverColumns"
                      :pagination="false" style="margin-left: -1px;">
              <template #versionName="{ record }">
                <a-input v-model:value="record['versionName']" />
              </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 #divisionNo="{ record }">
                <a-input  v-model:value="record['divisionNo']"  />
              </template>

              <template #value="{ record }">
                <a-input  v-model:value="record['value']"  />
              </template>

              <template #operation="{ record }">
                <a @click="onAdd">添加</a>
                <a-popconfirm v-if="vdata.receiverList.length" title="确认删除吗?" @confirm="onDelete(record.key)">
                  <a style="margin-left: 20px;color: red">删除</a>
                </a-popconfirm>
              </template>
            </a-table>
          </a-form-item>
        </a-col>

      </a-row>
    </a-form>
    <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>
  <JeepayModelStoreList  style="margin-top: -70px !important; height: 300px !important;" v-if="jeepayModelStoreListFlag" ref="jeepayModelStoreListFlag"
                        @selectFinishFunc="selectStoreIdFinishProductFunc" />
</template>

<script lang="ts" setup>
import {
  API_MCH_PAY_DEFINES,
   API_URL_DIVISIONTASK,
  req
} from '@/api/manage'
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
import { message } from 'ant-design-vue'
import {getCurrentInstance, nextTick, reactive, ref} from 'vue'

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

const infoFormModel = ref()
const vdata = reactive ({
  receiverList: [{
    value: '',
    isCharge: '',
    divisionNo: '',
    key: 0 as any,
  },],
  modeList:[
    {name:"按比例分账",value:0},
    {name:"按金额分账",value:1},
  ],
  typeList:[
    {name:"实时分账",value:0},
    {name:"延时分账",value:1},
    {name:"秒到分账",value:2},
  ],
  payDefines: [] as any,
  confirmLoading: false, // 显示确定按钮loading图标
  isAdd: true, // 新增 or 修改页面标识
  isShow: false, // 是否显示弹层/抽屉
  saveObject: {isAuto:0, divisionMode: 0,divisionType:0,divisionAmount:0,ifCode:"yspay",name:"" } as any, // 数据对象
  recordId: null, // 更新对象ID
  rules: {
    name: [{ required: true, message: '请输入组名称', trigger: 'blur' }],
    ifCode: [{ required: true, message: '请选择所属渠道', trigger: 'blur' }],
    divisionMode: [{ required: true, message: '请输入分账模式', trigger: 'blur' }],
    divisionType: [{ required: true, message: '请输入分账类型', trigger: 'blur' }],
    divisionAmount: [{ required: true, message: '请输入分账金额', trigger: 'blur' }],
    divisionImg: [{ required: true, message: '请输入分账金额', trigger: 'blur' }],
    minAmount: [{ required: true, message: '请输入最小支付金额', trigger: 'blur' }],
  },
  receiverColumns: [
    {title: '账户',dataIndex: 'divisionNo',slots: { customRender: 'divisionNo' },},
    {title: '属性值',   dataIndex: 'value',  slots: { customRender: 'value' },  },
    { title: '是否收取手续费', dataIndex: 'isCharge', slots: { customRender: 'isCharge' },},
    { title: '操作',dataIndex: 'operation', slots: { customRender: 'operation' },width: '15%',},
  ],
})
function onClose(){
  vdata.isShow = false
}
defineExpose({show})
function  show (record) { // 弹层打开事件
  vdata.isAdd = !record
  vdata.saveObject = {isAuto:0, divisionMode: 0,divisionType:0,divisionAmount:0,ifCode:"yspay",name:"" } // 数据清空
  vdata.confirmLoading = false // 关闭loading

  if (infoFormModel.value !== undefined) {
    infoFormModel.value.resetFields()
  }

  payFefines()
  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    vdata.recordId = record.id
    // vdata.saveObject = record
    // if(record.divisionMode == 1){
    //   vdata.saveObject.divisionAmount = (record.divisionAmount/ 100).toFixed(2)
    //   vdata.saveObject.minAmount = (record.minAmount/ 100).toFixed(2)
    // }
    vdata.isShow = true
  } else {
    vdata.isShow = true // 立马展示弹层信息
  }
}
function getType(e){
  console.log(vdata.saveObject.type,'vdata.saveObject.type')
}
function  payFefines() {
  req.list(API_MCH_PAY_DEFINES,{ 'pageSize': -1 }).then(res => {
    vdata.payDefines = res
  })
}

function getIfCode(){


}
function  handleOkFunc() { // 点击【确认】按钮事件
  infoFormModel.value.validate().then(valid=>{
    vdata.confirmLoading = true // 显示loading

    if (vdata.isAdd) {
      req.add(API_URL_DIVISIONTASK, vdata.saveObject).then(res => {
        message.success('添加成功')
        vdata.isShow = false
        props.callbackFunc() // 刷新列表
      }).catch(res => { vdata.confirmLoading = false })
    } else {
      req.updateById(API_URL_DIVISIONTASK, vdata.recordId, vdata.saveObject).then(res => {
        message.success('修改成功')
        vdata.isShow = false
        props.callbackFunc() // 刷新列表
      }).catch(res => { vdata.confirmLoading = false })
    }
  })
}
const jeepayModelStoreListFlag = ref()
function showStoreIdSelectPackageModel(title) {
  jeepayModelStoreListFlag.value = true
  nextTick(() => {
    jeepayModelStoreListFlag.value.show(vdata.saveObject.storeIdList,2)
  })
}

function selectStoreIdFinishProductFunc(e) { // 码牌选择完成事件
  jeepayModelStoreListFlag.value = false
  if (!e || e.length <= 0) {
    vdata.saveObject.storeName = ''
    vdata.saveObject.storeIdList = []
    return $infoBox.message.error('请开启要绑定的门店！')
  }
  vdata.saveObject.storeName = ''
  vdata.saveObject.storeIdList = []

  e.forEach((item) => {
    vdata.saveObject.storeName += item.storeName + ','
    vdata.saveObject.storeIdList.push(item.storeId)
  })
  // jeepayModelStoreListFlag.value.close()
}
const onDelete = (key) => {
  if (vdata.receiverList.length <= 1) {
    $infoBox.message.error('最少保留一项')
    return false
  }
  console.log(key)
  vdata.receiverList = vdata.receiverList.filter(item => item.key !== key)
 }
const onAdd = () => {
  if (!vdata.receiverList) {
    vdata.receiverList = [] as any
  }
  if (vdata.receiverList.length == 9) {
    $infoBox.message.error('最多设置9个接收方')
    return false
  }
  vdata.receiverList.push({
    value: '',
    isCharge: '',
    divisionNo: '',
    key: vdata.receiverList[vdata.receiverList.length - 1].key + 1,
  })
}
</script>
<style lang="less" scoped>
.jeepay-tip-text::before{
  border: none !important;
}

.ant-modal-content{
  margin-top: -60px !important;
}
</style>
