<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :title="vdata.isAdd ? '新增代付通道' : vdata.isCloneMode ? '克隆通道' : '修改代付通道'"
    width="40%"
    :maskClosable="false"
    @close="onClose"
  >
    <a-form ref="infoFormModel" :model="vdata.saveObject" layout="vertical" :rules="vdata.rules">

      <a-row :gutter="16">
        <p class="jee-drawer-title">基本配置</p>
        <a-col :span="12">
          <a-form-item label="转账功能代码" name="transIfCode">
            <a-input v-model:value="vdata.saveObject['transIfCode']" placeholder="请输入" :disabled="!vdata.isAdd" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="转账功能名称" name="transIfName">
            <a-input v-model:value="vdata.saveObject['transIfName']" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="24">

          <a-form-item label="关联支付接口代码" name="payIfCode">
            <JeepaySelect ref="ifCodeRef" placeholder="支付接口" :reset="isReset">
              <a-select v-model:value="vdata.saveObject.payIfCode" @change="ifCodeRef.textupHandle()" allow-clear="true">
                <template v-for="(item) in vdata.ifCodeList" :key="item.ifCode">
                  <a-select-option :value="item.ifCode">{{ item.ifName }}[{{ item.ifCode }}]</a-select-option>
                </template>
              </a-select>
            </JeepaySelect>
          </a-form-item>
        </a-col>
        <a-col  :span="24">
          <a-form-item label="服务商通道配置定义描述" name="isvParams">
            <a-textarea v-model:value="vdata.saveObject['isvParams']" :readonly="vdata.isCloneMode" placeholder="请输入" type="textarea" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="state">
            <a-radio-group v-model:value="vdata.saveObject['state']">
              <a-radio :value="1">
                启用
              </a-radio>
              <a-radio :value="0">
                停用
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remark">
            <a-input v-model:value="vdata.saveObject['remark']" placeholder="请输入" />
            <p style="color: grey;">将显示在商户APP的[通道申请]页面</p>
          </a-form-item>
        </a-col>

        <a-divider class="m-b-20" />
        <p class="jee-drawer-title">到账方式</p>
        <a-col :span="24">
          <a-form-item label="支持的到账方式" name="checkedList">
            <a-checkbox-group :value="vdata.checkedList" :options="vdata.wayCodesOptions" @change="onWayCodesChange" />
          </a-form-item>
        </a-col>

        <a-divider class="m-b-20" />
        <p class="jee-drawer-title">页面展示</p>
        <a-col :span="12">
          <a-form-item label="卡片icon" name="icon">
            <JeepayUpload v-model:src="vdata.saveObject['icon']" bizType="ifBG" />
          </a-form-item>
        </a-col>
        <a-col :span="12" class="m-b-50">
          <a-form-item label="卡片背景色" name="bgColor">
            <a-input v-model:value="vdata.saveObject['bgColor']" type="color" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="onSubmit"><check-outlined />保存</a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import {
  API_URL_IFDEFINES_LIST,
  API_URL_PAYWAYS_LIST,
  req,
  reqLoad,
  upload,
  $queryCloneInfos,
  API_URL_PAY_TRANSFERDEFINE_ADD
} from '@/api/manage'
import { onMounted,ref,reactive, getCurrentInstance, computed } from 'vue'
import { message } from 'ant-design-vue'
import {useRoute} from "vue-router";
const { $infoBox} = getCurrentInstance()!.appContext.config.globalProperties

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


    const validateNormalMchParams = (rule, value, callback) => { // 普通商户通道配置定义描述 验证器
      if (vdata.saveObject['isMchMode'] === 1 && vdata.saveObject['configPageType'] === 1 && !value) {
        return Promise.reject(new Error('请输入普通商户通道配置定义描述'))
      }
      return Promise.resolve()
    }
    const validateIsvParams = (rule, value, callback) => { // 服务商通道配置定义描述 验证器
      if (vdata.saveObject['isIsvMode'] === 1 && vdata.saveObject['configPageType'] === 1 && !value) {
        return Promise.reject(new Error('请输入服务商通道配置定义描述'))
      }
      return Promise.resolve()
    }
    const validateIsvsubMchParams = (rule, value, callback) => { // 特约商户通道配置定义描述 验证器
      if (vdata.saveObject['isIsvMode'] === 1 && vdata.saveObject['configPageType'] === 1 && !value) {
        return Promise.reject(new Error('请输入特约商户通道配置定义描述'))
      }
      return Promise.resolve()
    }
    const validateWayCodes = (rule, value, callback) => { // 支付方式 验证器
      if (vdata.checkedList.length <= 0) {
        return Promise.reject(new Error('请选择支付方式'))
      }
      return Promise.resolve()
    }

const validatePayInterfaceCodes = (rule, value, callback) => { // 支付方式 验证器
  if (vdata.payInterfaceCodes.length <= 0) {
    return Promise.reject(new Error('请选择支持通道类型'))
  }
  return Promise.resolve()
}
    const vdata  : any = reactive ({
      ifCodeList:[] as any,
      isAdd: true, // 新增 or 修改
      visible: false, // 抽屉开关
      action: upload.ifBG, // 上传图标地址
      ifCode: '', // 支付通道定义id
      saveObject: {}, // 数据对象
      channelFeeCalModel: {}, // 渠道手续费计算方式等的配置
      btnLoading: false,
      rules: {
        ifCode: [{ required: true, message: '请输入通道代码', trigger: 'blur' }],
        ifName: [{ required: true, message: '请输入通道名称', trigger: 'blur' }],
        normalMchParams: [{ required: true, validator: validateNormalMchParams, trigger: 'blur' }],
        isvParams: [{ required: true, validator: validateIsvParams, trigger: 'blur' }],
        isvsubMchParams: [{ required: true, validator: validateIsvsubMchParams, trigger: 'blur' }],
        checkedList: [{ required: true, validator: validateWayCodes, trigger: 'blur' }],
        payInterfaceCodes: [{ required: true, validator: validatePayInterfaceCodes, trigger: 'blur' }]
      },
      wayCodesOptions: [] as any[], // 支付方式多选框选项列表
      checkedList: [], // 选中的数据
      payInterfaceCodes:[],
      isCloneMode: false, //是否克隆模式， 默认为false
    })


  onMounted(()=>{
      payWayList()
    req.list(API_URL_IFDEFINES_LIST, {state:1, isSupportApplyment: 1}).then((res) => {
      vdata.ifCodeList = res
    })
  })

defineExpose({show})
    // 抽屉显示
    function show (rerocde) {
      vdata.isAdd = !rerocde
       // 数据清空
      vdata.saveObject = {
        'state': 1,
        'bgColor': "#000",
        'payIfCode': ""
      }

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


      if (!vdata.isAdd) { // 修改信息 延迟展示弹层
        vdata.saveObject = rerocde
        rerocde.wayCodes.forEach(item => {
          vdata.checkedList.push(item.wayCode)
        })
        vdata.visible = true
      } else {
        vdata.visible = true // 展示弹层信息
      }
    }
   function onClose () {
      vdata.visible = false
   }
    // 表单提交
  function  onSubmit () {
      infoFormModel.value.validate().then(valid =>{
        vdata.saveObject['wayCodeStrs'] = vdata.checkedList.join(',')
          // 请求通道
          if (vdata.isAdd) {
            vdata.btnLoading = true // 打开按钮上的 loading
            reqLoad.add(API_URL_PAY_TRANSFERDEFINE_ADD, vdata.saveObject).then(res => {
              message.success('新增成功')
              vdata.visible = false
              props.callbackFunc() // 刷新列表
              vdata.btnLoading = false
            }).catch(valid =>{
              vdata.btnLoading = false
            })
          } else {
            reqLoad.add(API_URL_PAY_TRANSFERDEFINE_ADD, vdata.saveObject).then(res => {
              message.success('修改成功')
              vdata.visible = false
              props.callbackFunc() // 刷新列表
              vdata.btnLoading = false
            }).catch(valid =>{
              vdata.btnLoading = false
            })
          }
      })
    }
    // 支付方式列表
  function payWayList () {
      req.list(API_URL_PAYWAYS_LIST, { 'pageSize': '-1' }).then(res => {
        res.records.filter(r => r.productType == 'TRANSFER').forEach(item => {
          vdata.wayCodesOptions.push({
            label: item.wayName,
            value: item.wayCode
          })
        })
      })
    }
 function  onWayCodesChange (checkedValues) {
    vdata.checkedList = checkedValues
 }

// 更改 转账 状态
function changeTransferFlagFunc(v){

  // 删除 转账产品
  if(vdata.checkedList.indexOf('TRANSFER') >= 0){
    vdata.checkedList.splice(vdata.checkedList.indexOf('TRANSFER'), 1)
  }

  // 开启
  if(v.target.value){
    vdata.checkedList.push('TRANSFER')
  }

  console.log(vdata.checkedList)

}


// 计算属性
let changeTransferFlagVal = computed(() => {
  if(vdata.checkedList.indexOf('TRANSFER') >= 0){
      return 1
    }

    return 0
}) as any

const ifCodeRef = ref()
let isReset = ref(0) // 下拉搜索框是否重置

// 清空搜索项
const resetFunc = () => {
  isReset.value++ // 下拉搜索框重置
  vdata.searchData= {}
}
</script>

<style lang="less">
  .typePopover {
    position: absolute;
    top: 0;
    left:150px;
  }
</style>
