<!--
  支付参数填写组件

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/04/06 10:14
-->
<template>
  <div>
    <a-form ref="formRef" :model="vdata.saveObject" layout="vertical" :rules="vdata.formRules" style="margin-top: 20px">
      <a-row :gutter="24">
        <a-col :span="6">
          <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-col>


        <!--
        服务商、代理商进件配置
        支付接口支持进件，便可配置进件开启开关（2023/04/04 改动）
        -->
        <a-col
          v-if="(props.configMode == 'mgrIsv'
            || (props.configMode == 'mgrAgent' || props.configMode == 'agentSelf' || props.configMode == 'agentSubagent')) && vdata.saveObject.isSupportApplyment"
          :span="6"
        >
          <a-form-item label="是否开启进件" name="isOpenApplyment">
            <a-radio-group v-model:value="vdata.saveObject.isOpenApplyment">
              <a-radio :value="1">开启</a-radio>
              <a-radio :value="0">关闭</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 提现配置组件 -->
      <CashoutParams ref="cashoutParamsRef" />

      <!-- 服务商对账配置 -->
      <a-row :gutter="24">
        <a-col v-if="(props.configMode == 'mgrIsv' || (props.configMode == 'mgrMch' && vdata.saveObject.mchType == 1)) && vdata.saveObject.isSupportCheckBill" :span="8">
          <a-form-item label="是否开启对账" name="isCheckBill">
            <a-radio-group v-model:value="vdata.saveObject.isCheckBill">
              <a-radio :value="1">开启</a-radio>
              <a-radio :value="0">关闭</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-if="props.configMode == 'mgrIsv' && vdata.saveObject.isSupportCheckBill && vdata.saveObject.isCheckBill" :span="24">
          <a-form-item name="ignoreCheckBillMchNos">
            <template #label>
              <span style="padding-right: 5px">对账过滤子商户</span>
              <a-tooltip class="tooltip">
                <template #title>填写不执行对账的渠道子商户号<br>多个以英文逗号隔开<br>为空表示下属子商户全部执行对账</template>
                <i class="bi bi-info-circle" />
              </a-tooltip>
            </template>
            <a-input v-model:value="vdata.saveObject.ignoreCheckBillMchNos" placeholder="请输入" type="textarea" />
          </a-form-item>
        </a-col>
      </a-row>



      <a-row>
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-input v-model:value="vdata.saveObject['remark']" placeholder="请输入" type="textarea" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- 进件特殊参数配置 -->
    <ApplymentExtParams ref="applymentExtParamsRef" />

    <a-divider v-if="props.configMode == 'mgrIsv' || props.configMode == 'mgrMch' || props.configMode == 'agentMch'" orientation="left"><a-tag color="#FF4B33">{{ vdata.saveObject['ifCode'] }} 参数配置</a-tag></a-divider>

    <!-- 动态组件 -->
    <component :is="vdata.configComponent" v-if="props.configMode == 'mgrIsv' || props.configMode == 'mgrMch' || props.configMode == 'agentMch' || props.configMode == 'mchSelfApp1'" ref="configComponentRef" />

    <div class="drawer-btn-center">
      <a-button type="primary" :loading="vdata.btnLoading" @click="onSubmit"><check-outlined />  保存</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup >

/** 引入全部定义的配置组件 **/
import ConfigPageByCommons from '../../../JeepayPayParamsConfig/commons/Commons.vue'
import CashoutParams from '../../../JeepayPayParamsConfig/CashoutParams.vue'
import ApplymentExtParams from '../../../JeepayPayParamsConfig/ApplymentExtParams.vue'
import {
  $getInterfaceSavedConfigs,
  $saveInterfaceParams,
  $getOauth2DiyList,
  $getPaySaveConfigAlternative, $getTransferDefineInstanceCode, $saveTransferDefineInstance
} from '@/api/manage'
import { ref, reactive, getCurrentInstance, onMounted, defineProps, nextTick, provide } from 'vue'
import { getOriginIfCode } from '../../../util/jeepayComponentUtil.js'

// 定义父组件的传值
const props : any = defineProps({
  selectIfCode: { type: String ,default: '' }, // 默认选中的支付接口
  infoId: { type: String, default: '' }, // 当前配置的所属infoId
  configMode: { type: String, default: '' },   // 模式
  selectDetail:{},//内容数据
})


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


// 当前的form组件
const formRef = ref()

const configComponentRef = ref()
const cashoutParamsRef = ref()
const applymentExtParamsRef = ref()


const vdata : any = reactive({
  payInterfaceCodes : [] as any,
  channelTypeOption:{
    type_0:'-1',
    type_1:'-1',
    type_2:'-1',
  } as any,//支持通道类型
  configComponent: null as any, // 动态组件 当前配置组件
  saveObject: {} as any, // 保存的对象
  cashoutObject: {} as any, // 提现配置对象
  formRules: {
    state:  [{ type: 'number',  required: true, trigger: 'blur', message: '请选择状态' }],
    settHoldDay: [{ type: 'number',  required: true, trigger: 'blur', message: '请输入结算周期' }],
    isOpenApplyment: [{ type: 'number',  required: true, trigger: 'blur', message: '请选择是否开启进件' }],
    isCheckBill: [{ type: 'number',  required: true, trigger: 'blur', message: '请选择是否开启对账' }],
  },
  btnLoading:false,

  oauth2DiyList: [], // diyList

})

// 初始化页面
function initPageFunc(){
  // props.selectIfCode格式： ifCode或ifCode_1等等，保存数据使用传入的ifCode或ifCode_1，页面渲染使用ifCode(需截取ifCode_1)
  const ifCodeView = getOriginIfCode(props.selectIfCode) // 页面渲染使用
  console.log(ifCodeView,'ifCodeViewifCodeViewifCodeView')
  // 获取当前服务商的配置信息（）
  $getTransferDefineInstanceCode(props.selectIfCode ,props.infoId).then(res => {

    vdata.channelTypeOption = res.channelTypeOption
    vdata.payInterfaceCodes = res.channelTypes

    vdata.saveObject = res
    console.log(res,'vdatasaveObjectvdataaveObject ')
    // vdata.saveObject  = props.selectDetail;
    console.log(props.selectDetail,'props.selectIfCode')

    // 设置当前存储的配置项
    let currentConfig = JSON.parse(vdata.saveObject.transIfParams || '{}' )

    // vue page 定义
    let vuePage = 'Isv'
    if(props.configMode == 'mgrMch' || props.configMode == 'agentMch' || props.configMode == 'mchSelfApp1'){
      vuePage = 'Mch'
    }

    // 其他配置类型不显示支付参数配置
    if(props.configMode == 'mgrIsv' || props.configMode == 'mgrMch' || props.configMode == 'agentMch' || props.configMode == 'mchSelfApp1') {
      // 明确使用 通用组件
      if(res.configPageType != 1){

        vdata.configComponent = ConfigPageByCommons //使用通用组件
        nextTick(() => { configComponentRef.value.pageRender(res.ifDefineArray, currentConfig) })  // 调用组件的渲染函数

      }else{

        // 动态 自定义引入组件
        import(`./diy/${ifCodeView}/${vuePage}Page.vue`).then((module) => {

          vdata.configComponent = module.default
          nextTick(() => { configComponentRef.value.pageRender(res.ifDefineArray, currentConfig, res.mchType) })  // 调用组件的渲染函数

        }).catch(() => {
          vdata.configComponent = ConfigPageByCommons //使用通用组件
          nextTick(() => { configComponentRef.value.pageRender(res.ifDefineArray, currentConfig) })  // 调用组件的渲染函数

        })
      }
    }


    // 提现配置项
    let cashoutParams = JSON.parse(vdata.saveObject.cashoutParams || '{}' )
    cashoutParamsRef.value.pageRender(vdata.saveObject.isSupportCashout, props.configMode, cashoutParams)

    // 进件特殊参数配置
    let applymentExtParams = JSON.parse(vdata.saveObject.applymentExtParams || '{}' )
    applymentExtParamsRef.value.pageRender(ifCodeView, props.configMode, applymentExtParams)

    // 运营平台配置 服务商时
    if(props.configMode == 'mgrIsv' || props.configMode == 'mgrAgent'){

      // 初始化为 默认 。
      if(!vdata.saveObject.oauth2InfoId){
        vdata.saveObject.oauth2InfoId = ''
      }

      // $getOauth2DiyList(props.infoId, props.configMode).then((res) => {
      //   vdata.oauth2DiyList = res
      // })
    }
  })

}


onMounted(() => {
  initPageFunc()
})


function onSubmit(){

  formRef.value.validate().then( () => { // 1. 验证主表单

    applymentExtParamsRef.value.getConfigParams().then(applymentExtParams => {
      // 进件渠道参数配置
      vdata.saveObject.applymentExtParams = JSON.stringify(applymentExtParams)
    })

    cashoutParamsRef.value.getConfigParams().then(cashoutParams => {

      // 其他配置类型不显示支付参数配置
      if(props.configMode == 'mgrIsv' || props.configMode == 'mgrMch' || props.configMode == 'agentMch' || props.configMode == 'mchSelfApp1') {
        configComponentRef.value.getConfigParams().then(ifPrams => { //2. 验证渲染组件表单
          updateConfigParams(ifPrams, cashoutParams)
        })
      }else {
        updateConfigParams(null, cashoutParams)
      }

    })
  })
}

function updateConfigParams(ifPrams, cashoutParams) {
  // 赋值
  vdata.saveObject.transIfParams = ifPrams ? JSON.stringify(ifPrams) : '{}'

  // 配置模式
  vdata.saveObject.infoId = props.infoId
  vdata.saveObject.infoType = "ISV"
  vdata.saveObject.ifCode = props.selectIfCode
  vdata.saveObject.configMode = props.configMode
  if (Array.isArray(vdata.payInterfaceCodes)) {
    vdata.saveObject.channelTypes = vdata.payInterfaceCodes.join(',');
  }

  // 提现参数配置
  vdata.saveObject.cashoutParams = JSON.stringify(cashoutParams)

  // 请求接口
  $saveTransferDefineInstance(vdata.saveObject).then(res => {
    $infoBox.message.success('保存成功')
  })
  // $getPaySaveConfigAlternative(vdata.saveObject).then(res => {
  //   $infoBox.message.success('保存成功')
  // })
}

// 重新渲染页面（ 粘贴参数使用 ）
function reloadParamsPageByParse(paramsVal){

  let currentConfig = JSON.parse(paramsVal || '{}' )

  nextTick(() => { configComponentRef.value.pageRender(vdata.saveObject.ifDefineArray, currentConfig, vdata.saveObject.mchType, false) })  // 调用组件的渲染函数

}


// 向所有子页面注入 参数的infoId
provide('infoId', props.infoId)

provide('initPageFunc', initPageFunc)

// 函数导出
defineExpose({ reloadParamsPageByParse })
</script>