<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :mask-closable="false"
    title="代理商高级配置"
    :body-style="{ paddingBottom: '80px' }"
    width="60%"
    class="drawer-width"
    @close="getvisible"
    ref="ISdrawerRef"
  >
    <div style="background: #fff">
      <a-tabs v-if="vdata.visible" @change="selectTabs">
        <a-tab-pane key="applymentConfig" tab="进件配置">
          <div v-if="vdata.groupKey == 'applymentConfig'" class="account-settings-info-view" style="margin-left: 40px">
            <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }">
              <a-row justify="start" type="flex" style="margin-top: 10px">
                <a-col :span="12">
                  <p>当前代理商进件配置管理方式</p>
                </a-col>
                <a-col :span="12" />
                <a-col :span="12">
                  <a-radio-group v-model:value="vdata.applymentAuditMode">
                    <a-radio value="DEF">使用默认配置</a-radio>
                    <a-radio value="CUSTOM">自定义配置</a-radio>
                  </a-radio-group>
                </a-col>
                <a-col :span="12" />
              </a-row>
              <a-row v-if="vdata.applymentAuditMode == 'CUSTOM'" justify="start" type="flex" style="margin-top: 40px">
                <a-col :span="8">
                  <p>当前代理商进件是否需要运营平台预审核</p>
                </a-col>
                <a-col :span="8">
                  <p>代理商发起进件时间限制</p>
                </a-col>
                <a-col :span="8" />
                <a-col :span="8">
                  <a-radio-group v-model:value="vdata.agentApplymentPreAudit">
                    <a-radio value="0">无需预审</a-radio>
                    <a-radio value="1">需要预审</a-radio>
                  </a-radio-group>
                </a-col>
                <a-col :span="8">
                  <a-space direction="vertical" :size="12">
                    <a-time-range-picker
                      v-model:value="vdata.agentApplyTimeLimit"
                      :show-time="{ format: 'HH:mm:ss' }"
                      format="HH:mm:ss"
                      :placeholder="['开始时间', '结束时间']"
                      :disabled="vdata.agentApplyTimeLimit == ''"
                      @change="onRangeChangeAgent"
                    />
                  </a-space>
                </a-col>
                <a-col :span="8">
                  <a-checkbox :checked="vdata.agentApplyTimeLimit == '' " @change="changeAgentRange">不限制</a-checkbox>
                </a-col>
              </a-row>
              <div style="margin-left: 20%; margin-top: 60px">
                <a-button type="primary" :loading="vdata.btnLoading" style="margin-right:8px" @click="confirmByApplymentConfig('onlySelf')">
                  <check-circle-outlined v-if="!vdata.btnLoading" />
                  确认更新
                </a-button>
                <a-button type="primary" :loading="vdata.btnLoading" @click="confirmByApplymentConfig('allCurrentAndSubAgent')">
                  <check-circle-outlined v-if="!vdata.btnLoading" />
                  确认更新并同步至所有下级代理商
                </a-button>
              </div>
            </a-form>
          </div>
        </a-tab-pane>

        <a-tab-pane key="cashoutConfig" tab="提现规则配置">
          <div v-if="vdata.groupKey == 'cashoutConfig'" class="account-settings-info-view" style="margin-left: 40px">
            <a-form ref="cashOutFormModel" :model="vdata.saveObject" :rules="vdata.rules">
              <a-row justify="space-between" type="flex">
                <a-form-item label="" name="cashoutFeeRuleType">
                  配置类型： <a-radio-group v-model:value="vdata.saveObject['cashoutFeeRuleType']">
                    <a-radio :value="1">使用系统默认</a-radio>
                    <a-radio :value="2">自定义</a-radio>
                  </a-radio-group>

                  <template v-if="vdata.saveObject['cashoutFeeRuleType'] == 2">
                    <br><br>
                    额度： 设置最低 <a-input-number v-model:value="vdata.castOutFeeRule.applyLimit" :min="0" /> 元可发起提现 <br><br>
                    规则： 提现 <a-input-number v-model:value="vdata.castOutFeeRule.freeLimit" :min="0" /> 元以内免收手续费 <br><br>
                    手续费计算模式：<br>
                  
                    <a-radio-group v-model:value="vdata.castOutFeeRule.feeType">
                      <a-radio value="FIX" style="margin-top:10px">
                        单笔固定
                        <template v-if="vdata.castOutFeeRule.feeType == 'FIX'">
                          <a-input-number v-model:value="vdata.castOutFeeRule.fixFee" :min="0" /> 元
                        </template>
                      </a-radio>
                      <br>
                      <a-radio value="SINGLE" style="margin-top:20px">
                        单笔费率
                        <template v-if="vdata.castOutFeeRule.feeType == 'SINGLE'">
                          <a-input-number v-model:value="vdata.castOutFeeRule.feeRate" :min="0" /> %
                        </template>
                      </a-radio>
                      <br>
                      <a-radio value="FIXANDRATE" style="margin-top:20px">
                        固定+费率
                        <template v-if="vdata.castOutFeeRule.feeType == 'FIXANDRATE'">
                          <a-input-number v-model:value="vdata.castOutFeeRule.fixFee" :min="0" /> 元 +  <a-input-number v-model:value="vdata.castOutFeeRule.feeRate" :min="0" /> %
                        </template>
                      </a-radio>
                    </a-radio-group>
                  </template>
                </a-form-item>
              </a-row>
              
              <a-divider orientation="left" style="color: #1A66FF;">钱包冻结金额配置项</a-divider>
              <a-row justify="space-between" type="flex">
                <a-col :span="24">
                  <a-form-item label="钱包冻结金额" name="freezeAmount">
                    <a-input-number
                      v-model:value="vdata.saveObject['freezeAmount']"
                      :min="0"
                      :precision="2"
                      addon-after="元" 
                      @change="(amount) => { return amount == 0 ? vdata.saveObject['freezeDesc'] = '' : vdata.saveObject['freezeDesc'] = vdata.saveObject['freezeDesc']}"
                    />
                  </a-form-item>
                </a-col>
                <a-col v-if="vdata.saveObject['freezeAmount'] > 0" :span="12">
                  <a-form-item label="冻结原因" name="freezeDesc">
                    <a-textarea v-model:value="vdata.saveObject['freezeDesc']" placeholder="请填写冻结原因" :rows="3" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
            <div style="margin-left: 20%; margin-top: 60px">
              <a-button type="primary" :loading="vdata.btnLoading" style="margin-right:8px" @click="confirmByCashOutConfig()">
                <check-circle-outlined v-if="!vdata.btnLoading" />
                确认更新
              </a-button>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="mchAuthorityConfig" tab="商户管理权限配置">
          <MchAuthorityConfig v-if="vdata.groupKey == 'mchAuthorityConfig'" :currentAgentNo="vdata.recordId" />
        </a-tab-pane>
        <a-tab-pane key="applicationConfig" tab="域名管理" v-if="vdata.oemType == 1">
          <ApplicationConfig v-if="vdata.groupKey == 'applicationConfig'" :currentAgentNo="vdata.recordId" />
        </a-tab-pane>
        <a-tab-pane key="oemConfig" tab="平台配置" v-if="vdata.oemType == 1">
          <OemConfig v-if="vdata.groupKey == 'oemConfig'" :currentAgentNo="vdata.recordId"  />
        </a-tab-pane>
        <a-tab-pane key="treatyConfig" tab="文章管理" v-if="vdata.oemType == 1">
          <div class="account-settings-info-view">
            <a-tabs tab-position="left">
              <a-tab-pane key="mch" tab="商户通">
                <div class="account-settings-info-view">
                  <a-form layout="vertical">
                    <a-row style="margin-top: 20px;">
                      <a-col :span="18" :offset="2">
                        <div
                            style="font-size: 20px;font-weight:600;text-align:center;padding: 10px 0">
                          隐私政策</div>
                        <div v-if="vdata.defaultPrivacyHtmlFlag" style="border: 1px solid #ccc">
                          <!-- 工具栏 -->
                          <Toolbar :editorId="editorId" :defaultConfig="toolbarConfig"
                                   style="border-bottom: 1px solid #ccc" />
                          <!-- 编辑器 -->
                          <Editor :defaultHtml="vdata.defaultPrivacyHtml" :editorId="editorId"
                                  :defaultConfig="editorConfig"
                                  style="height: 500px; overflow-y: hidden;" />
                        </div>
                        <div
                            style="font-size: 20px;font-weight:600;text-align:center;padding: 10px 0">
                          用户服务协议</div>
                        <div v-if="vdata.defaultAgreementHtmlFlag" style="border: 1px solid #ccc">
                          <!-- 工具栏 -->
                          <Toolbar :editorId="agreementId" :defaultConfig="toolbarConfig"
                                   style="border-bottom: 1px solid #ccc" />
                          <!-- 编辑器 -->
                          <Editor :defaultHtml="vdata.defaultAgreementHtml"
                                  :editorId="agreementId" :defaultConfig="editorConfig"
                                  style="height: 500px; overflow-y: hidden;" />
                        </div>

                        <div
                            style="font-size: 20px;font-weight:600;text-align:center;padding: 10px 0">
                          产品服务合同</div>
                        <div v-if="vdata.defaultFlundHtmlFlag" style="border: 1px solid #ccc">
                          <!-- 工具栏 -->
                          <Toolbar :editorId="fundId" :defaultConfig="toolbarConfig"
                                   style="border-bottom: 1px solid #ccc" />
                          <!-- 编辑器 -->
                          <Editor :defaultHtml="vdata.defaultFlundHtml"
                                  :editorId="fundId" :defaultConfig="editorConfig"
                                  style="height: 500px; overflow-y: hidden;" />
                        </div>
                      </a-col>
                    </a-row>
                    <a-form-item class="bottom-btn" style="margin-top: 20px">
                      <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" type="primary"
                                :loading="vdata.btnLoading"
                                @click="confirmTreatyConfig('mch')"><check-circle-outlined />确认更新</a-button>
                    </a-form-item>
                  </a-form>
                </div>
              </a-tab-pane>

              <a-tab-pane key="agent" tab="展业宝">
                <div class="account-settings-info-view">
                  <a-form layout="vertical">
                    <a-row style="margin-top: 20px;">
                      <a-col :span="18" :offset="2">
                        <div
                            style="font-size: 20px;font-weight:600;text-align:center;padding: 10px 0">
                          隐私政策</div>
                        <div v-if="vdata.agentDefaultPrivacyHtmlFlag"
                             style="border: 1px solid #ccc">
                          <!-- 工具栏 -->
                          <Toolbar :editorId="agentEditorId" :defaultConfig="toolbarConfig"
                                   style="border-bottom: 1px solid #ccc" />
                          <!-- 编辑器 -->
                          <Editor :defaultHtml="vdata.agentDefaultPrivacyHtml"
                                  :editorId="agentEditorId" :defaultConfig="editorConfig"
                                  style="height: 500px; overflow-y: hidden;" />
                        </div>
                        <div
                            style="font-size: 20px;font-weight:600;text-align:center;padding: 10px 0">
                          用户服务协议</div>
                        <div v-if="vdata.agentDefaultAgreementHtmlFlag"
                             style="border: 1px solid #ccc">
                          <!-- 工具栏 -->
                          <Toolbar :editorId="agentAgreementId" :defaultConfig="toolbarConfig"
                                   style="border-bottom: 1px solid #ccc" />
                          <!-- 编辑器 -->
                          <Editor :defaultHtml="vdata.agentDefaultAgreementHtml"
                                  :editorId="agentAgreementId" :defaultConfig="editorConfig"
                                  style="height: 500px; overflow-y: hidden;" />
                        </div>
                      </a-col>
                    </a-row>
                    <a-form-item class="bottom-btn" style="margin-top: 20px">
                      <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" type="primary"
                                :loading="vdata.btnLoading"
                                @click="confirmTreatyConfig('agent')"><check-circle-outlined />确认更新</a-button>
                    </a-form-item>
                  </a-form>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-tab-pane>

      </a-tabs>
    </div>
  </a-drawer>
</template>
<script setup lang="ts">
import {API_URL_AGENT_CONFIG, req, API_URL_AGENT_LIST, $getConfigs, API_URL_AGENT_CONFIG_UPDATE_OEM} from '@/api/manage'
import dayjs, {Dayjs} from 'dayjs'
import ApplicationConfig from './component/ApplicationConfig.vue'
import MchAuthorityConfig from './MchAuthorityConfig.vue'
import OemConfig from './component/OemConfig.vue'
import { ref, reactive, onMounted, onBeforeUnmount, getCurrentInstance, computed, nextTick } from 'vue'
import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
import { IToolbarConfig } from '@wangeditor/editor'

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

  const payTestBarCode = ref()
  const cashOutFormModel = ref()

  const vdata : any = reactive ({
    defaultPrivacyHtmlFlag: false,
    defaultAgreementHtmlFlag: false,
    defaultFlundHtmlFlag: false,
    defaultPrivacyHtml: '',
    defaultAgreementHtml: '',
    defaultFlundHtml: '',

    agentDefaultPrivacyHtmlFlag: false,
    agentDefaultAgreementHtmlFlag: false,
    agentDefaultPrivacyHtml: '',
    agentDefaultAgreementHtml: '',
    oemType:0, //oem 贴牌 1开启
    recordId: null, // 更新对象ID
    visible: false, // 是否显示弹层/抽屉
    btnLoading: false,
    groupKey: 'applymentConfig',
    agentApplyConfigData: [] as any, // 代理商进件配置保存对象
    applymentAuditMode: 'DEF', // DEF-平台全局默认配置 ,  CUSTOM-自定义
    agentApplymentPreAuditConfig: '0', // 当前代理商进件是否需要运营平台预审核 1-需要 0不需要
    agentApplyTimeLimit: '', // 代理商进件时间限制(回显)
    agentApplyTimeLimitSave: '', // 代理商进件时间限制（保存到后端）
    castOutFeeRule: { feeType: 'FIX', fixFee: 0, feeRate: 0, freeLimit: 0, applyLimit: 0 },// 手续费配置信息
    saveObject: {}, // 数据对象
    rules: {
      freezeAmount: [{ required: true, message: '请填写钱包冻结金额', trigger: 'blur' }],
      freezeDesc: [{ required: true, message: '请填写冻结原因', trigger: 'blur' }]
    }
  })

  // 点击不限制进件日期时显示的默认日期范围
  const initDateRange = ref<[Dayjs, Dayjs]>([
      dayjs('00:00:00', 'HH:mm:ss'),
      dayjs('23:59:59', 'HH:mm:ss'),
  ])

  // 勾选“不限制”按钮时的时间数据处理
  function changeAgentRange(value){
    if (value.target.checked) {
      vdata.agentApplyTimeLimit = ''
      vdata.agentApplyTimeLimitSave = ''
    } else {
      vdata.agentApplyTimeLimit = initDateRange.value
      vdata.agentApplyTimeLimitSave = JSON.stringify(['00:00:00', '23:59:59'])
    }
  }

  function show (record) { // 弹层打开事件
      vdata.recordId = record.agentNo
      vdata.oemType = record.oemType
      vdata.agentApplyTimeLimit = ''
    getEditorId()
      selectTabs('applymentConfig') //初始化数据
      vdata.visible = true
  }


function selectTabs (key) { // 清空必填提示
  if (key) {
    vdata.groupKey = key
    if(key == 'applymentConfig'){
      req.list(API_URL_AGENT_CONFIG, {groupKey: vdata.groupKey, agentNo: vdata.recordId}).then(res => {
        if (res != null && res.length > 0) {
          // 当前代理商进件配置管理方式 DEF-平台全局默认配置 ,  CUSTOM-自定义
          const applymentAuditModeIndex = res.findIndex((v) => v.configKey == 'applymentAuditMode')
          vdata.applymentAuditMode = (applymentAuditModeIndex > -1) ? res[applymentAuditModeIndex].configVal : 'DEF'
          // 代理商进件是否需要运营平台预审核
          const agentApplymentPreAuditIndex = res.findIndex((v) => v.configKey == 'agentApplymentPreAuditConfig')
          vdata.agentApplymentPreAudit = (agentApplymentPreAuditIndex > -1) ? res[agentApplymentPreAuditIndex].configVal : '0'
          // 代理商发起进件默认时间限制
          const agentApplyTimeLimitIndex = res.findIndex((v) => v.configKey == 'agentApplyTimeLimitConfig')
          if (agentApplyTimeLimitIndex > -1 && res[agentApplyTimeLimitIndex].configVal) {
              vdata.agentApplyTimeLimitSave = res[agentApplyTimeLimitIndex].configVal
              vdata.agentApplyTimeLimit = JSON.parse(res[agentApplyTimeLimitIndex].configVal)
              if (vdata.agentApplyTimeLimit[0]) {
                vdata.agentApplyTimeLimit[0] = dayjs(vdata.agentApplyTimeLimit[0], 'HH:mm:ss')
              }
              if (vdata.agentApplyTimeLimit[1]) {
                vdata.agentApplyTimeLimit[1] = dayjs(vdata.agentApplyTimeLimit[1], 'HH:mm:ss')
              }
          } else {
            vdata.agentApplyTimeLimit = ''
            vdata.agentApplyTimeLimitSave = ''
          }
        } else {
          vdata.applymentAuditMode = 'DEF'
          vdata.agentApplymentPreAudit = '0'
          vdata.agentApplyTimeLimit = ''
          vdata.agentApplyTimeLimitSave = ''
        }
      })
    } else if (key == 'cashoutConfig') {

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

      vdata.saveObject = { 'state': 1, passwordType: 'default', isNotify: 0, addAgentFlag:  1, addMchFlag:  1, cashoutFeeRuleType: 1} // 数据清空
      req.getById(API_URL_AGENT_LIST, vdata.recordId).then(res => {
      vdata.saveObject = res
      // 钱包信息
      vdata.saveObject.freezeAmount = Number.parseFloat((res.freezeAmount / 100).toFixed(2)) || 0
      // 手续费类型
      vdata.castOutFeeRule = { feeType: 'FIX', fixFee: 0, feeRate: 0, freeLimit: 0, applyLimit: 0 }

      // 转换 提现手续费对象
      let castOutFeeRuleJSON = JSON.parse(vdata.saveObject.cashoutFeeRule)
      
        if(castOutFeeRuleJSON){

            vdata.castOutFeeRule.feeType = castOutFeeRuleJSON.feeType || 'FIX'

            if(castOutFeeRuleJSON.fixFee){
              vdata.castOutFeeRule.fixFee = Number.parseFloat((castOutFeeRuleJSON.fixFee / 100).toFixed(2))
            }
            if(castOutFeeRuleJSON.feeRate){
              vdata.castOutFeeRule.feeRate = Number.parseFloat((castOutFeeRuleJSON.feeRate * 100).toFixed(2))
            }
            if(castOutFeeRuleJSON.freeLimit){
              vdata.castOutFeeRule.freeLimit = Number.parseFloat((castOutFeeRuleJSON.freeLimit / 100).toFixed(2))
            }
            if(castOutFeeRuleJSON.applyLimit){
              vdata.castOutFeeRule.applyLimit = Number.parseFloat((castOutFeeRuleJSON.applyLimit / 100).toFixed(2))
            }
        }
      })
    }else if(key == 'treatyConfig'){
         detail('treatyConfig')
    }
  }
}


// 确认更新进件配置
function confirmByApplymentConfig(value) {
    let primaryStr = ''
    if (value) {
      if (value == 'onlySelf') {
        primaryStr = '注：仅当前代理商生效'
      } else if(value == 'allCurrentAndSubAgent') {
        primaryStr = '注：当前代理商及当前代理商的所有下级代理商均生效'
      }
    }

    $infoBox.confirmPrimary('确认更新进件配置吗？', primaryStr, () => {
      vdata.agentApplyConfigData = []
      vdata.btnLoading = true // 打开按钮上的 loading
      if (!vdata.applymentAuditMode) {
        vdata.applymentAuditMode = 'DEF'
      }
      vdata.agentApplyConfigData.push({ groupKey: vdata.groupKey, configKey: 'applymentAuditMode', configVal : vdata.applymentAuditMode })
      if (vdata.applymentAuditMode == 'CUSTOM') {
        vdata.agentApplyConfigData.push({ groupKey: vdata.groupKey, configKey: 'agentApplymentPreAuditConfig', configVal : vdata.agentApplymentPreAudit ? vdata.agentApplymentPreAudit : '0' })
        vdata.agentApplyConfigData.push({ groupKey: vdata.groupKey, configKey: 'agentApplyTimeLimitConfig', configVal : vdata.agentApplyTimeLimitSave })
      }
      req.updateById(API_URL_AGENT_CONFIG, vdata.groupKey, {agentNo: vdata.recordId, configData: JSON.stringify(vdata.agentApplyConfigData), updateType: value}).then(res => {
        $infoBox.message.success('更新成功')
        vdata.btnLoading = false
      }).catch(res => {
        vdata.btnLoading = false
      })
    })
}

// 进件时间限制  传给后端的格式 '' 或 时间数组字符串
function onRangeChangeAgent(value: any, dateString: any) {
  if (!dateString[0] && !dateString[1]) {
    vdata.agentApplyTimeLimitSave = ''
    return
  }
  if (dateString[0] && !dateString[1]) {
    dateString[1] = '23:59:59'
  } else if (!dateString[0] && dateString[1]) {
    dateString[0] = '00:00:00' 
  }
  vdata.agentApplyTimeLimitSave = JSON.stringify(dateString)
}

function confirmByCashOutConfig() {
  cashOutFormModel.value.validate().then(valid =>{
 // 手续费
 vdata.saveObject['cashoutFeeRule'] = null
      if(vdata.saveObject['cashoutFeeRuleType'] == 2){
        // 转换 提现手续费对象
        const castOutFeeRule : any = {}
        
        if(vdata.castOutFeeRule.freeLimit == null || vdata.castOutFeeRule.freeLimit < 0){
          return $infoBox.message.error('免收手续费不可小于0')
        }
        castOutFeeRule.freeLimit = Number.parseInt((vdata.castOutFeeRule.freeLimit * 100).toFixed(0))

        if(vdata.castOutFeeRule.applyLimit == null || vdata.castOutFeeRule.applyLimit < 0){
          return $infoBox.message.error('提现额度不可小于0')
        }
        castOutFeeRule.applyLimit = Number.parseInt((vdata.castOutFeeRule.applyLimit * 100).toFixed(0))

        castOutFeeRule.feeType = vdata.castOutFeeRule.feeType
        if(vdata.castOutFeeRule.feeType == 'FIX'){

          if(vdata.castOutFeeRule.fixFee == null || vdata.castOutFeeRule.fixFee < 0){
            return $infoBox.message.error('固定金额不可小于0')
          }
          castOutFeeRule.fixFee = Number.parseInt((vdata.castOutFeeRule.fixFee * 100).toFixed(0))

        }else if(vdata.castOutFeeRule.feeType == 'SINGLE'){

          if(vdata.castOutFeeRule.feeRate == null || vdata.castOutFeeRule.feeRate < 0){
            return $infoBox.message.error('费率不可小于0')
          }
          castOutFeeRule.feeRate = Number.parseFloat((vdata.castOutFeeRule.feeRate / 100).toFixed(4))

        }else if(vdata.castOutFeeRule.feeType == 'FIXANDRATE'){

          if(vdata.castOutFeeRule.fixFee == null || vdata.castOutFeeRule.fixFee < 0){
            return $infoBox.message.error('固定金额不可小于0')
          }
          if(vdata.castOutFeeRule.feeRate == null || vdata.castOutFeeRule.feeRate < 0){
            return $infoBox.message.error('费率不可小于0')
          }
          castOutFeeRule.fixFee = Number.parseInt((vdata.castOutFeeRule.fixFee * 100).toFixed(0))
          castOutFeeRule.feeRate = Number.parseFloat((vdata.castOutFeeRule.feeRate / 100).toFixed(4))
        }

        vdata.saveObject['cashoutFeeRule'] = JSON.stringify(castOutFeeRule)
      }  

      vdata.btnLoading = true

      req.updateById(API_URL_AGENT_LIST, vdata.recordId, vdata.saveObject).then(res => {
        $infoBox.message.success('更新成功')
        vdata.btnLoading = false
      }).catch(res => {
        vdata.btnLoading = false
      })
  })
}

// 隐私政策与服务协议确认更新
function confirmTreatyConfig(saveType) {
  const editor : any = getEditor(editorId)
  const agreementEditor : any = getEditor(agreementId)
  const fundIdEditor : any = getEditor(fundId)

  const editorByAgent : any = getEditor(agentEditorId)
  const agreementEditorByAgent : any = getEditor(agentAgreementId)
  // const agentFundEditorByAgent : any = getEditor(agentFundId)

  $infoBox.confirmPrimary('确认更新隐私政策与服务协议吗？', '', () => {
    vdata.btnLoading = true // 打开按钮上的 loading
    const reqData : any = {}

    if (saveType == 'mch') {
      reqData.privacyPolicy = editor.getHtml()
      reqData.serviceAgreement = agreementEditor.getHtml()
      reqData.servicePaymentFlund = fundIdEditor.getHtml()
    }

    if (saveType == 'agent') {
      reqData.agentPrivacyPolicy = editorByAgent.getHtml()
      reqData.agentServiceAgreement = agreementEditorByAgent.getHtml()
    }
    console.log(saveType,'saveType')
    if (saveType == 'fund') {
      // reqData.agentPrivacyPolicy = fundIdEditor.getHtml()
      // reqData.agentServiceAgreement = agentFundEditorByAgent.getHtml()
    }
    reqData.groupKey = vdata.groupKey
    reqData.agentNo = vdata.recordId

    req.updateById(API_URL_AGENT_CONFIG_UPDATE_OEM, '', reqData)
        .then(res => {
          $infoBox.message.success('修改成功')
          vdata.btnLoading = false
        }).catch(res => { vdata.btnLoading = false })
  })
}
// 定义一个编辑器 id ，要求：全局唯一且不变！！！
const editorId = 'wangeEditor-1' // 隐私政策
const agreementId = 'wangeEditor-2' // 服务协议
const fundId = 'wangeEditor-3' // 资金授权支付服务合同


// 定义一个编辑器 id ，要求：全局唯一且不变！！！
const agentEditorId = 'agent-wangeEditor-1' // 隐私政策
const agentAgreementId = 'agent-wangeEditor-2' // 服务协议
const agentFundId = 'agent-wangeEditor-3' // 服务协议

// 隐藏编辑器菜单中，一些菜单项
const toolbarConfig : Partial<IToolbarConfig> = {
  // 隐藏 全屏放大  上传视频  等
  excludeKeys: ['fullScreen', 'uploadVideo', 'insertVideo', 'deleteVideo', 'uploadImage']
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: { /* 菜单配置，下文解释 */ }
}
function getvisible() {
  getEditorId()
}
const  ISdrawerRef = ref({})
// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = getEditor(editorId)
  const agreementEditor = getEditor(agreementId)
  const fundEditor = getEditor(fundId)

  const editorByAgent = getEditor(agentEditorId)
  const agreementEditorByAgent = getEditor(agentAgreementId)
  const fundEditorByAgent = getEditor(agentFundId)

  if (editor == null || agreementEditor == null || fundEditor == null || editorByAgent == null
      || agreementEditorByAgent == null  || fundEditorByAgent == null) return

  // 销毁，并移除 editor
  editor.destroy()
  agreementEditor.destroy()
  removeEditor(editorId)
  removeEditor(agreementId)
  removeEditor(fundId)

  // 销毁，并移除 editor
  editorByAgent.destroy()
  agreementEditorByAgent.destroy()
  removeEditor(agentEditorId)
  removeEditor(agentAgreementId)
  removeEditor(agentFundId)

})
function getEditorId() {

  const editor = getEditor(editorId)
  const agreementEditor = getEditor(agreementId)

  const editorByAgent = getEditor(agentEditorId)
  const agreementEditorByAgent = getEditor(agentAgreementId)
  console.log(editor,agreementEditor,editorByAgent,agreementEditorByAgent)

  if (editor == null || agreementEditor == null  || editorByAgent == null
      || agreementEditorByAgent == null || fundId == null ) return
console.log(11111111111111111111111)
  // 销毁，并移除 editor
  editor.destroy()
  agreementEditor.destroy()
  removeEditor(editorId)
  removeEditor(agreementId)
  removeEditor(fundId)

  // 销毁，并移除 editor
  editorByAgent.destroy()
  agreementEditorByAgent.destroy()
  removeEditor(agentEditorId)
  removeEditor(agentAgreementId)
  removeEditor(agentFundId)
}
function detail(groupKey) { // 获取基本信息

  vdata.defaultPrivacyHtml = ""// html格式
  vdata.defaultAgreementHtml = ""// html格式
  vdata.defaultFlundHtml = ""// html格式
  vdata.agentDefaultPrivacyHtml =  ""// html格式
  vdata.agentDefaultAgreementHtml =  ""// html格式

  req.list(API_URL_AGENT_CONFIG, {groupKey: vdata.groupKey, agentNo: vdata.recordId}).then(res => {
    let tempConfigMap : any = {} // 临时配置信息
    res.forEach(item => tempConfigMap[item.configKey] = item.configVal)

    let itemMap : any = {} // 临时配置信息
    res.forEach(item => itemMap[item.configKey] = item)

    // 处理数据脱敏
    vdata.configDataDesen = {}  // 重置配置信息
    res.forEach(item => vdata.configDataDesen[item.configKey] = item.configValDesen)

    vdata.configData = {}  // 重置配置信息

    // vdata.groupKey = res[0].groupKey
    if ('treatyConfig' === groupKey) { // 隐私政策与服务协议
      console.log(tempConfigMap,'tempConfigMaptempConfigMaptempConfigMap')

      vdata.defaultPrivacyHtml = tempConfigMap.privacyPolicy // html格式



      vdata.defaultAgreementHtml = tempConfigMap.serviceAgreement  // html格式



      vdata.defaultFlundHtml = tempConfigMap.servicePaymentFlund   // html格式


      vdata.agentDefaultPrivacyHtml = tempConfigMap.agentPrivacyPolicy  // html格式


      vdata.agentDefaultAgreementHtml = tempConfigMap.agentServiceAgreement   // html格式


      setTimeout(function() {
        vdata.defaultPrivacyHtmlFlag = true
        vdata.defaultAgreementHtmlFlag = true
        vdata.defaultFlundHtmlFlag = true
        vdata.agentDefaultPrivacyHtmlFlag = true
        // 这里是延迟执行的代码
        vdata.agentDefaultAgreementHtmlFlag = true
      }, 2000);

    }
  })

}
defineExpose({
  show
})
</script>
<style lang="less" scoped>
  .bottom-btn{
    /deep/ div{
      display: flex;
      justify-content: center;
    }
  }
  .typePopover {
  position: absolute;
  top: -30px;
  left: 93px;
}
</style>
<!-- 编辑器样式 -->
<style src="@wangeditor/editor/dist/css/style.css"></style>
