<template>
  <div style="background: #fff">
    <a-tabs @change="selectTabs">
      <a-tab-pane key="applicationConfig" tab="域名管理">
        <ApplicationConfig v-if="vdata.groupKey == 'applicationConfig'" />
      </a-tab-pane>

      <a-tab-pane key="defaultConfig" tab="默认配置">
        <DefaultConfig v-if="vdata.groupKey == 'defaultConfig'" />
      </a-tab-pane>

      <a-tab-pane key="oemConfig" tab="平台配置">
        <OemConfig v-if="vdata.groupKey == 'oemConfig'" />
      </a-tab-pane>

      <a-tab-pane key="treatyConfig" tab="文章管理">
        <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-tab-pane key="smsConfig" tab="高级配置">
        <div class="account-settings-info-view">
          <!-- 高级配置 左侧 tabs  -->
          <a-tabs tab-position="left" @change="selectTabs">
            <a-tab-pane key="smsConfig" tab="短信配置">
              <SmsConfig v-if="vdata.groupKey == 'smsConfig'" ref="smsConfigRef" />
            </a-tab-pane>

            <a-tab-pane key="ocrConfig" tab="OCR识别">
              <a-form ref="ocrConfigInfoFormModel" :model="vdata.configData" layout="vertical">
                <a-row style="margin-top: 20px;">
                  <a-col :span="6" :offset="2">
                    <a-form-item label="启用类型" name="ocrType">
                      <a-radio-group v-model:value="vdata.configData.ocrType"
                                     @change="checkOcrTYpe(vdata.configData.ocrType)">
                        <a-radio :value="'1'">腾讯OCR</a-radio>
                        <a-radio :value="'2'">阿里OCR</a-radio>
                        <a-radio :value="'3'">百度OCR</a-radio>
                      </a-radio-group>
                    </a-form-item>
                  </a-col>
                  <a-col :span="6" :offset="2">
                    <a-form-item label="使用状态" name="state">
                      <a-radio-group v-model:value="vdata.configData.ocrState">
                        <a-radio :value="'1'">开启</a-radio>
                        <a-radio :value="'0'">关闭</a-radio>
                      </a-radio-group>
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row style="margin-top: 20px;">
                  <a-col :span="12" :offset="2">
                    <a-collapse v-model:activeKey="vdata.activeKey" expand-icon-position="right">
                      <a-collapse-panel key="1" header="[ 腾讯OCR识别配置 ]">
                        <a-form-item label="SecretId" name="tencentSecretId">
                          <a-input v-model:value="vdata.configData.tencentSecretId"
                                   placeholder="请填写" />
                        </a-form-item>
                        <a-form-item label="SecretKey" name="tencentSecretKey">
                          <a-input v-model:value="vdata.configData.tencentSecretKey"
                                   :placeholder="vdata.configDataDesen.tencentSecretKey || '请填写' " />
                        </a-form-item>
                      </a-collapse-panel>
                      <a-collapse-panel key="2" header="[ 阿里OCR识别配置 ]">
                        <a-form-item label="AccessKey ID" name="aliAccessKeyId">
                          <a-input v-model:value="vdata.configData.aliAccessKeyId"
                                   placeholder="请填写" />
                        </a-form-item>
                        <a-form-item label="AccessKey Secret" name="aliAccessKeySecret">
                          <a-input v-model:value="vdata.configData.aliAccessKeySecret"
                                   :placeholder="vdata.configDataDesen.aliAccessKeySecret || '请填写' " />
                        </a-form-item>
                      </a-collapse-panel>
                      <a-collapse-panel key="3" header="[ 百度OCR识别配置 ]">
                        <a-form-item label="Api Key" name="baiduApiKey">
                          <a-input v-model:value="vdata.configData.baiduApiKey"
                                   placeholder="请填写" />
                        </a-form-item>
                        <a-form-item label="Secret Key" name="baiduSecretKey">
                          <a-input v-model:value="vdata.configData.baiduSecretKey"
                                   :placeholder="vdata.configDataDesen.baiduSecretKey || '请填写' " />
                        </a-form-item>
                      </a-collapse-panel>
                    </a-collapse>
                  </a-col>
                </a-row>
                <a-form-item class="bottom-btn" style="margin-top: 20px">
                  <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" :disabled="!vdata.isEdit"
                            type="primary" :loading="vdata.btnLoading"
                            @click="confirmOcrConfig"><check-circle-outlined />确认更新</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>

            <a-tab-pane key="ossConfig" tab="存储配置">
              <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }">
                <a-form-item label="选择上传服务">
                  <a-radio-group v-model:value="vdata.configData.ossUseType">
                    <a-radio value="localFile">本地存储</a-radio>
                    <a-radio value="aliyunOss">阿里云OSS</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-col :span="12" :offset="1">
                  <a-alert message="分布式环境下，需要使用云OSS存储" type="success" />
                </a-col>
                <div v-if="vdata.configData.ossUseType == 'localFile'">
                  <a-divider orientation="left">本地存储配置</a-divider>

                  <a-form-item label="公共oss访问地址(不包含结尾/)">
                    <a-input v-model:value="vdata.configData.ossPublicSiteUrl"
                             placeholder="例如： https://mgr.xxx.com/api/anon/localOssFiles" />
                    <span
                        class="jeepay-tip-text">如：https://mgr.xxx.com/api/anon/localOssFiles</span>
                  </a-form-item>
                </div>

                <div v-if="vdata.configData.ossUseType == 'aliyunOss'">
                  <a-divider orientation="left">阿里云OSS配置</a-divider>

                  <a-form-item label="endpoint">
                    <a-input v-model:value="vdata.aliyunOssConfig.endpoint"
                             placeholder="例如： oss-cn-beijing.aliyuncs.com" />
                  </a-form-item>
                  <a-form-item label="[公共读]桶名称">
                    <a-input v-model:value="vdata.aliyunOssConfig.publicBucketName"
                             placeholder="请填写[公共读]桶名称" />
                  </a-form-item>
                  <a-form-item label="[私有]桶名称">
                    <a-input v-model:value="vdata.aliyunOssConfig.privateBucketName"
                             placeholder="请填写[私有]桶名称" />
                  </a-form-item>
                  <a-form-item label="AccessKeyId">
                    <a-input v-model:value="vdata.aliyunOssConfig.accessKeyId"
                             placeholder="请填写AccessKeyId" />
                  </a-form-item>
                  <a-form-item label="AccessKeySecret">
                    <a-input v-model:value="vdata.aliyunOssConfig.accessKeySecret"
                             :placeholder="vdata.configDataDesen.accessKeySecret || '请填写accessKeySecret'" />
                  </a-form-item>
                  <a-form-item label="请求过期时间">
                    <a-input-number v-model:value="vdata.aliyunOssConfig.expireTime"
                                    style="width: 100%;" placeholder="请填写请求过期时间， 默认30000， 单位： ms" />
                  </a-form-item>
                </div>

                <a-form-item class="bottom-btn" style="margin-top: 50px">
                  <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" :disabled="!vdata.isEdit"
                            type="primary" :loading="vdata.btnLoading"
                            @click="confirmOSSConfig"><check-circle-outlined />确认更新</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>

            <a-tab-pane key="apiMapConfig" tab="地图配置">
              <a-form ref="mapConfigFormModel" :model="vdata.configData" layout="vertical">
                <a-row style="margin-top: 20px;">
                  <a-col :span="6" :offset="2">
                    <a-form-item label="[高德地图商户端web配置] key" name="apiMapWebKey">
                      <a-input v-model:value="vdata.configData.apiMapWebKey" placeholder="请填写" />
                    </a-form-item>
                    <a-form-item label="[高德地图商户端web配置] 秘钥" name="apiMapWebSecret">
                      <a-input v-model:value="vdata.configData.apiMapWebSecret"
                               :placeholder="vdata.configDataDesen.apiMapWebSecret || '请填写'" />
                    </a-form-item>
                    <a-form-item label="[高德地图商户端web服务key] key" name="apiMapWebServiceKey">
                      <a-input v-model:value="vdata.configData.apiMapWebServiceKey"
                               :placeholder="vdata.configDataDesen.apiMapWebServiceKey || '请填写'" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-form-item class="bottom-btn" style="margin-top: 20px">
                  <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" :disabled="!vdata.isEdit"
                            type="primary" :loading="vdata.btnLoading"
                            @click="cconfirmMapConfigon"><check-circle-outlined />确认更新</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>

            <a-tab-pane key="emailConfig" tab="邮箱配置">
              <a-form ref="emailConfigFormModel" :model="vdata.configData" layout="vertical">
                <a-row style="margin-top: 20px;">
                  <a-col :span="6" :offset="2">
                    <a-form-item label="host" name="邮箱host">
                      <a-input v-model:value="vdata.configData.emailHost" placeholder="请填写邮箱host" />
                    </a-form-item>
                    <a-form-item label="端口" name="邮箱端口">
                      <a-input v-model:value="vdata.configData.emailPort" placeholder="请填写邮箱端口" />
                    </a-form-item>
                    <a-form-item label="账户名" name="邮箱账户名">
                      <a-input v-model:value="vdata.configData.emailName" placeholder="请填写邮箱账户名" />
                    </a-form-item>
                    <a-form-item label="账号" name="邮箱账号">
                      <a-input v-model:value="vdata.configData.emailAccountNo" placeholder="请填写邮箱账号" />
                    </a-form-item>
                    <a-form-item label="密码" name="邮箱密码">
                      <a-input v-model:value="vdata.configData.emailPassword" placeholder="请填写邮箱密码" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-form-item class="bottom-btn" style="margin-top: 20px">
                  <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" :disabled="!vdata.isEdit"
                            type="primary" :loading="vdata.btnLoading"
                            @click="confirmEmailConfigon"><check-circle-outlined />确认更新</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>

            <a-tab-pane key="paymentConfig" tab="打款配置">
              <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }">
                <a-form-item label="选择打款渠道">
                  <a-radio-group v-model:value="vdata.configData.paymentType">
                    <a-radio value="flpay">福穗·灵工</a-radio>
                    <a-radio value="aqfpay">安全发</a-radio>
                  </a-radio-group>
                </a-form-item>
                <div v-if="vdata.configData.paymentType == 'flpay'">
                  <a-divider orientation="left">福穗·灵工配置</a-divider>

                  <a-form-item label="appId">
                    <a-input v-model:value="vdata.configData.appId" placeholder="" />
                  </a-form-item>
                  <a-form-item label="secret">
                    <a-input v-model:value="vdata.configData.secret" placeholder="" />
                  </a-form-item>
                  <a-form-item label="任务ID">
                    <a-input v-model:value="vdata.configData.taskNo" placeholder="" />
                  </a-form-item>
                </div>

                <div v-if="vdata.configData.ossUseType == 'aqfpay'">
                  <a-divider orientation="left">安全发配置</a-divider>

                </div>

                <a-form-item class="bottom-btn" style="margin-top: 50px">
                  <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" :disabled="!vdata.isEdit"
                            type="primary" :loading="vdata.btnLoading"
                            @click="confirmPaymentConfig"><check-circle-outlined />确认更新</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-tab-pane>

      <a-tab-pane key="securityConfig" tab="安全配置">
        <div v-if="vdata.groupKey == 'securityConfig'" class="account-settings-info-view">
          <a-form ref="securityConfigFormModel" layout="vertical">
            <a-row>
              <a-col :span="8" :offset="1">
                <a-form-item label="HTTP传输应用层加密开关">
                  <a-radio-group v-model:value="vdata.configData.httpMessageEncryptFlag">
                    <a-radio value="1">开启</a-radio>
                    <a-radio value="0">关闭</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="登录失败次数限制">
                  <a-input-number v-model:value="vdata.loginErrorMaxLimit.limitMinute" :min="1"
                                  :precision="0" />
                  分钟最多尝试
                  <a-input-number v-model:value="vdata.loginErrorMaxLimit.errMax" :min="0" :max="10"
                                  :precision="0" />
                  次（0次表示不限制）
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="密码有效期超期是否强制更改">
                  <a-radio-group v-model:value="vdata.configData.passwordExpiredMustModify">
                    <a-radio value="1">是</a-radio>
                    <a-radio value="0">否</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="密码有效期">
                  <a-input-number v-model:value="vdata.configData.passwordExpireDay" :min="1"
                                  :precision="0">
                    <template #addonAfter>天</template>
                  </a-input-number>
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="密码规则">
                  <a-checkbox-group v-model:value="vdata.passwordReg.checkedArr">
                    <a-checkbox value="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])">是否要求大小写和数字</a-checkbox>
                    <a-checkbox value=".{maxLength,}">密码最少<a-input-number
                        v-model:value="vdata.passwordReg.maxLength" :min="0" :max="10"
                        :precision="0" />位</a-checkbox>
                  </a-checkbox-group>
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item>
                  <template #label>
                    <span>平台通信秘钥</span> &nbsp;
                    <a-popover placement="top">
                      <template #title><span>平台通信秘钥</span></template>
                      <template #content>
                        <p>当通过平台操作接口（比如：下单、退款）时将传入该值，用于区分是平台调用还是商户自调用。 </p>
                        <p>区分调用者用于判断商户的接口权限。 如发现异常调用，请及时更改此秘钥。</p>
                      </template>
                      <question-circle-outlined />
                    </a-popover>
                  </template>
                  <a-input v-model:value="vdata.configData.platformApiSecret"
                           :placeholder="vdata.configDataDesen.platformApiSecret || '请填写秘钥' " />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item class="bottom-btn">
              <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" :disabled="!vdata.isEdit" type="primary"
                        :loading="vdata.btnLoading" @click="confirmSecurityConfig">
                <check-circle-outlined />
                确认更新
              </a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>

      <a-tab-pane key="marketingConfig" tab="营销配置">
        <RedConfig v-if="vdata.groupKey == 'marketingConfig'" />
      </a-tab-pane>

<!--      <a-tab-pane key="oemDomainConfig" tab="贴牌域名配置">-->
<!--        <OemDomainConfig v-if="vdata.groupKey == 'oemDomainConfig'" />-->
<!--      </a-tab-pane>-->
    </a-tabs>
  </div>
</template>
<script setup lang="ts">
import ApplicationConfig from './component/ApplicationConfig.vue'
import DefaultConfig from './component/DefaultConfig.vue'
import OemConfig from './component/OemConfig.vue'
import SmsConfig from './component/SmsConfig.vue'
import RedConfig from './component/RedConfig.vue'
import OemDomainConfig from './component/oemDomainConfig.vue'
import { API_URL_SYS_CONFIG, API_URL_ISV_LIST, req, $getConfigs } from '@/api/manage'
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, $hasAgentEnt, $hasMemberEnt } = getCurrentInstance()!.appContext.config.globalProperties


const vdata : any = reactive({
  btnLoading: false,
  configData: {},
  configDataDesen: {} as any, // 脱敏数据
  isvList: [],
  groupKey: 'applicationConfig',

  aliyunOssConfig: {}, // 阿里云oss配置信息
  activeKey: '',  // OCR默认展开项
  isEdit: $access('ENT_SYS_CONFIG_EDIT'),

  defaultPrivacyHtmlFlag: false,
  defaultAgreementHtmlFlag: false,
  defaultFlundHtmlFlag: false,
  defaultPrivacyHtml: '',
  defaultAgreementHtml: '',
  defaultFlundHtml: '',

  agentDefaultPrivacyHtmlFlag: false,
  agentDefaultAgreementHtmlFlag: false,
  agentDefaultPrivacyHtml: '',
  agentDefaultAgreementHtml: '',

  loginErrorMaxLimit: { limitMinute: 15, errMax: 5 }, // 登录失败次数限制对象
  passwordReg: { checkedArr: [], maxLength: 6 }, // 密码规则对象

})

const ocrConfigInfoFormModel = ref()
const mapConfigFormModel = ref()
const smsConfigRef = ref()

function detail() { // 获取基本信息

  $getConfigs(vdata.groupKey).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 ('smsConfig' === vdata.groupKey) {

      nextTick(() => {
        smsConfigRef.value.pageRender(res) // 特殊处理
      })

    } else if ('ocrConfig' === vdata.groupKey) {

      res.forEach(item => vdata.configData[item.configKey] = item.configVal)
      // OCR默认展开赋值
      vdata.activeKey = vdata.configData.ocrType
    } else if ('ossConfig' === vdata.groupKey) { // oss配置

      res.forEach(item => vdata.configData[item.configKey] = item.configVal)
      vdata.flpayConfig = JSON.parse(itemMap.aliyunOssConfig.configVal || '{}')
      vdata.flpayConfig = JSON.parse(itemMap.aliyunOssConfig.configValDesen || '{}')

    } else if ('treatyConfig' === vdata.groupKey) { // 隐私政策与服务协议

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

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


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

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

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

    } else if ('apiMapConfig' === vdata.groupKey) { // 地图配置
      vdata.configData.apiMapWebKey = res[0].configVal
      vdata.configData.apiMapWebSecret = res[1].configVal
      vdata.configData.apiMapWebServiceKey = res[2].configVal

    } else if ('emailConfig' === vdata.groupKey) { // 地图配置
      vdata.configData.emailHost = res[0].configVal
      vdata.configData.emailPort = res[1].configVal
      vdata.configData.emailName = res[2].configVal
      vdata.configData.emailAccountNo = res[3].configVal
      vdata.configData.emailPassword = res[4].configVal

    }else if ('securityConfig' === vdata.groupKey) { // 安全配置

      res.forEach(item => vdata.configData[item.configKey] = item.configVal)

      if (vdata.configData.loginErrorMaxLimit) {
        vdata.loginErrorMaxLimit = JSON.parse(vdata.configData.loginErrorMaxLimit)
      }

      vdata.passwordReg.checkedArr = []
      if (vdata.configData.passwordRegexp.includes('(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])')) {
        vdata.passwordReg.checkedArr.push('(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])')
      }

      const regex = /.{([0-9]*),}/g
      const matchArr = [...vdata.configData.passwordRegexp.matchAll(regex)]
      if (matchArr.length > 0) {
        vdata.passwordReg.checkedArr.push('.{maxLength,}')

        console.log(matchArr[0])
        vdata.passwordReg.maxLength = parseInt(matchArr[0][1])
      }

    }else if ('paymentConfig' === vdata.groupKey){
      vdata.configData = JSON.parse(res[0].configVal)
    }else {
      vdata.configData = res
    }
  })
  // 服务商列表
  getIsvList()

}

function getIsvList() {
  req.list(API_URL_ISV_LIST, { pageSize: -1 }).then(res => {
    vdata.isvList = res.records
  })
}

function selectTabs(key) { // 清空必填提示
  if (key) {
    vdata.groupKey = key
    detail()
  }
}


// OCR识别配置
function confirmOcrConfig() {
  ocrConfigInfoFormModel.value.validate().then(valid => {
    $infoBox.confirmPrimary('确认更新上传服务的配置吗？', '', () => {
      vdata.btnLoading = true // 打开按钮上的 loading
      const reqData : any = {}
      reqData.ocrState = vdata.configData.ocrState
      reqData.ocrType = vdata.configData.ocrType
      reqData.tencentSecretId = vdata.configData.tencentSecretId
      if (vdata.configData.tencentSecretKey) {
        reqData.tencentSecretKey = vdata.configData.tencentSecretKey
      }
      reqData.aliAccessKeyId = vdata.configData.aliAccessKeyId
      if (vdata.configData.aliAccessKeySecret) {
        reqData.aliAccessKeySecret = vdata.configData.aliAccessKeySecret
      }
      reqData.baiduApiKey = vdata.configData.baiduApiKey
      if (vdata.configData.baiduApiKey) {
        reqData.baiduSecretKey = vdata.configData.baiduSecretKey
      }
      req.updateById(API_URL_SYS_CONFIG, vdata.groupKey, reqData)
          .then(res => {
            $infoBox.message.success('修改成功')
            vdata.btnLoading = false
          }).catch(res => {
        vdata.btnLoading = false
      })
    })
  })
}

function confirmOSSConfig(e) {
  $infoBox.confirmPrimary('确认更新文件上传服务配置吗？', '', () => {
    vdata.btnLoading = true // 打开按钮上的 loading
    const reqData : any = {}

    let reqAliyunObject = Object.assign({}, vdata.aliyunOssConfig)
    if (!reqAliyunObject.accessKeySecret) {
      delete reqAliyunObject.accessKeySecret
    }

    reqData.aliyunOssConfig = JSON.stringify(reqAliyunObject)
    reqData.ossUseType = vdata.configData.ossUseType
    reqData.ossPublicSiteUrl = vdata.configData.ossPublicSiteUrl
    req.updateById(API_URL_SYS_CONFIG, vdata.groupKey, reqData)
        .then(res => {
          $infoBox.message.success('修改成功')
          vdata.btnLoading = false
        }).catch(res => {
      vdata.btnLoading = false
    })
  })
}
// 存储配置确认更新
function confirmPaymentConfig(e) {
  $infoBox.confirmPrimary('确认更新打款参数吗？', '', () => {
    vdata.btnLoading = true // 打开按钮上的 loading
    req.updateById(API_URL_SYS_CONFIG, vdata.groupKey, vdata.configData)
        .then(res => {
          $infoBox.message.success('修改成功')
          vdata.btnLoading = false
        }).catch(res => {
      vdata.btnLoading = false
    })
  })
}

function checkOcrTYpe(value) {
  vdata.activeKey = value
}

// 隐私政策与服务协议确认更新
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()
    }

    req.updateById(API_URL_SYS_CONFIG, vdata.groupKey, 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: { /* 菜单配置，下文解释 */ }
}

// 组件销毁时，及时销毁编辑器
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 cconfirmMapConfigon() {
  $infoBox.confirmPrimary('确认更新地图配置吗？', '', () => {
    vdata.btnLoading = true // 打开按钮上的 loading

    let reqData : any = {}
    reqData.apiMapWebKey = vdata.configData.apiMapWebKey

    if (vdata.configData.apiMapWebSecret) {
      reqData.apiMapWebSecret = vdata.configData.apiMapWebSecret
    }
    if (vdata.configData.apiMapWebServiceKey) {
      reqData.apiMapWebServiceKey = vdata.configData.apiMapWebServiceKey
    }
    req.updateById(API_URL_SYS_CONFIG, vdata.groupKey, reqData)
        .then(res => {
          $infoBox.message.success('修改成功')
          vdata.btnLoading = false
        }).catch(res => {
      vdata.btnLoading = false
    })
  })
}

function confirmEmailConfigon(){
  $infoBox.confirmPrimary('确认更新邮件配置吗？', '', () => {
    vdata.btnLoading = true // 打开按钮上的 loading

    let reqData : any = {}
    reqData.emailPort = vdata.configData.emailPort
    reqData.emailHost = vdata.configData.emailHost
    reqData.emailName = vdata.configData.emailName
    reqData.emailAccountNo = vdata.configData.emailAccountNo
    reqData.emailPassword = vdata.configData.emailPassword
    req.updateById(API_URL_SYS_CONFIG, vdata.groupKey, reqData)
        .then(res => {
          $infoBox.message.success('修改成功')
          vdata.btnLoading = false
        }).catch(res => {
      vdata.btnLoading = false
    })
  })
}

// 安全配置保存
function confirmSecurityConfig() {
  $infoBox.confirmPrimary('确认更新安全配置吗？', '', () => {
    vdata.btnLoading = true // 打开按钮上的 loading

    let reqData : any = {}

    reqData.httpMessageEncryptFlag = vdata.configData.httpMessageEncryptFlag
    reqData.passwordExpireDay = vdata.configData.passwordExpireDay + ''
    reqData.passwordExpiredMustModify = vdata.configData.passwordExpiredMustModify

    if (vdata.configData.platformApiSecret) { // 非脱敏数据
      reqData.platformApiSecret = vdata.configData.platformApiSecret
    }

    reqData.loginErrorMaxLimit = JSON.stringify(vdata.loginErrorMaxLimit)

    // 拼接密码规则
    const checkedArr = vdata.passwordReg.checkedArr
    let passwordRegexp = { regexpRules: '', errTips: '' }

    if (checkedArr.includes('(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])')) {
      passwordRegexp.regexpRules += '(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])'
      passwordRegexp.errTips += '必须包含大小写字母和数字，'
    }
    if (checkedArr.includes('.{maxLength,}')) {
      if (vdata.passwordReg.maxLength < 6) {
        return $infoBox.message.success('请填写密码最少位数')
      }
      passwordRegexp.regexpRules += '.{maxLength,}'.replace('maxLength', vdata.passwordReg.maxLength)
      passwordRegexp.errTips += '最少' + vdata.passwordReg.maxLength + '位，'
    }

    if (passwordRegexp.regexpRules) {
      passwordRegexp.regexpRules = '^' + passwordRegexp.regexpRules + '$'
    }
    if (passwordRegexp.errTips) {
      passwordRegexp.errTips = '密码不符合规则，' + passwordRegexp.errTips
      passwordRegexp.errTips = passwordRegexp.errTips.substring(0, passwordRegexp.errTips.length - 1)
    }
    reqData.passwordRegexp = JSON.stringify(passwordRegexp)

    req.updateById(API_URL_SYS_CONFIG, vdata.groupKey, reqData).then(res => {
      $infoBox.message.success('修改成功')
      vdata.btnLoading = false
    }).catch(res => {
      vdata.btnLoading = false
    })
  })
}
</script>
<style lang="less" scoped>
.flex {
  display: flex;
  margin-bottom: 8px;

  i {
    margin-left: 5px;
  }
}

.bottom-btn {
  /deep/ div {
    display: flex;
    justify-content: center;
  }
}
</style>
<!-- 编辑器样式 -->
<style src="@wangeditor/editor/dist/css/style.css"></style>