<template>
  <div style="background: #fff">
    <a-tabs @change="selectTabs">
      <a-tab-pane key="wxMpConfig" tab="微信公众号消息配置">
        <div class="account-settings-info-view">
          <a-form ref="wxMpConfigFormModel" :model="vdata.configData" layout="vertical" :rules="vdata.wxMpConfigRules">
            <a-row justify="start" type="flex" style="margin-top: 20px">
              <a-col :span="17" :offset="1">
                <a-form-item label="微信公众号二维码" name="wxmpUrl">
                  <JeepayUpload v-model:src="vdata.configData.wxmpUrl" bizType="wxFile" fileType="img" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="微信公众号AppId" name="wxAppId">
                  <a-input v-model:value="vdata.configData.wxAppId" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="微信公众号AppSecret" name="wxAppSecret">
                  <a-input v-model:value="vdata.configData.wxAppSecret" :placeholder="vdata.configDataDesen.wxAppSecret || '请填写'" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="OAuth2地址（置空则使用微信官方）" name="mchAuthRedirectUrl">
                  <a-input v-model:value="vdata.configData.mchAuthRedirectUrl" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="备注信息" name="paySuccMsgTemplateContentRemark">
                  <a-input v-model:value="vdata.configData.paySuccMsgTemplateContentRemark" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>

              <a-col :span="8" :offset="1">
                <a-form-item label="支付成功模板消息ID" name="paySuccMsgTemplateId">
                  <a-input v-model:value="vdata.configData.paySuccMsgTemplateId" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="通知模板消息ID" name="noticeMsgTemplateId">
                  <a-input v-model:value="vdata.configData.noticeMsgTemplateId" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <!-- <a-col :span="17" :offset="1">
                <a-form-item label="微信校验文件（上传自动解析）">
                  <JeepayUpload v-model:upload="vdata.wx3rdCheckFileResult" :action="upload.wx3rdCheckFile">
                    <template #uploadSlot="{loading}">
                      <a-button style="margin-top:5px;"> <a-icon :type="loading ? 'loading' : 'upload'" /> {{ loading ? '正在上传' : '点击上传' }} </a-button>
                    </template>
                  </JeepayUpload>
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="微信校验文件名" name="wxCheckFileName">
                  <a-input v-model:value="vdata.wxMpConfigData.wxCheckFileName" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="微信校验文件内容" name="wxCheckFileValue">
                  <a-input v-model:value="vdata.wxMpConfigData.wxCheckFileValue" autocomplete="off" />
                </a-form-item>
              </a-col> -->
              <a-col :span="22" :offset="1">
                <p class="tem-title">配置指南：</p>
<!--                <p class="tem-msg">1. </p>-->
                <p class="tem-msg">1、 登录微信公众号开放平台：https://mp.weixin.qq.com，在设置与开发-公众号配置中，下载公众号二维码，任意边长均可。</p>
                <p class="tem-msg">2、 在设置与开发-基本配置中，获取AppID与AppSecret。</p>
                <p class="tem-msg">3、 在左侧功能栏底部-新的功能-目录管理-未开通-广告与服务-模版消息-去开通，主营行业选择：IT科技-互联网电子商务；副营行业选择：餐饮-餐饮；申请理由填写：新零售平台为商户提供会员营销、财务管理、卡券核销和店铺运营分析等功能，需要推送通知告知交易信息、购买信息、数据信息等。提交后一般一个工作日就可以开通。</p>
                <p class="tem-msg">4、 审核通过后，在左侧功能栏底部-广告与服务-模版消息-模板库-开始设置-添加类目，设置服务类目：工具-信息查询。</p>
                <p class="tem-msg">5、 在模板库-类目模板库，搜索栏输入关键词进行搜索：商户名称、订单编号、订单金额、支付方式、支付时间。</p>
                <p class="tem-msg">6、 选择编号为：47662的模板消息，支付通知场景微信模板消息需要字段：商户名称、订单编号、订单金额、支付方式、支付时间</p>
                <p class="tem-msg">7、 在我的模版-类目模版，复制模版ID配置到后台。</p>
                <p class="tem-msg">8、 在设置与开发-公众号配置-功能配置中，配置：{{ vdata.payUrl }}，在业务域名、JS接口安全域名、网页授权内。</p>
                <p class="tem-msg">9、 在设置与开发-基本配置中，将服务器IP配置到IP白名单中。</p>
              </a-col>
            </a-row>
            <a-form-item class="bottom-btn">
              <a-button v-if="$access('ENT_PUSH_CONFIG_EDIT')" :disabled="!vdata.isEdit" type="primary" :loading="vdata.btnLoading" @click="confirm"><check-circle-outlined />确认更新</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>

      <a-tab-pane key="appPushConfig" tab="app推送配置">
        <div class="account-settings-info-view">
          <a-form ref="appPushConfigFormModel" :model="vdata.configData" layout="vertical" :rules="vdata.appPushConfigRules">
            <a-row justify="start" type="flex" style="margin-top: 20px" gutter="24">
              <a-col :span="7" :offset="1">
                <a-form-item label="uniPush版本(2.0支持小程序播报)" name="uniPushVersion">
                  <a-radio-group v-model:value="vdata.configData.uniPushVersion">
                    <a-radio :value="'1'">1.0</a-radio>
                    <a-radio :value="'2'">2.0</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row
              v-if="vdata.configData.uniPushVersion == '1'"
              justify="start"
              type="flex"
              style="margin-top: 20px"
              gutter="24"
              wrap
            >
              <a-col :span="7" :offset="1">
                <a-form-item label="uniPush_appId" name="uniPushAppId">
                  <a-input v-model:value="vdata.configData.uniPushAppId" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="7" :offset="1" :pull="1">
                <a-form-item label="uniPush_appKey" name="uniPushAppKey">
                  <a-input v-model:value="vdata.configData.uniPushAppKey" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="7" :offset="1" :pull="2">
                <a-form-item label="uniPush_masterSecret" name="uniPushMasterSecret">
                  <a-input v-model:value="vdata.configData.uniPushMasterSecret" :placeholder="vdata.configDataDesen.uniPushMasterSecret || '请填写'" autocomplete="off" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row v-if="vdata.configData.uniPushVersion == '2'" justify="start" type="flex" style="margin-top: 20px" gutter="24">
              <a-col :span="7" :offset="1">
                <a-form-item label="uniPush推送云函数URL" name="uniPushCloudUrl">
                  <a-input v-model:value="vdata.configData.uniPushCloudUrl" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="7" :offset="1" :pull="1">
                <a-form-item label="uniPush查询失效cid云函数URL" name="uniPushQueryInvalidatedCidsUrl">
                  <a-input v-model:value="vdata.configData.uniPushQueryInvalidatedCidsUrl" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
            </a-row>

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

      <a-tab-pane key="baiduBceConfig" tab="百度语音配置">
        <div class="account-settings-info-view">
          <a-form ref="baiduBceConfigFormModel" :model="vdata.configData" layout="vertical" :rules="vdata.baiduBceConfigRules">
            <a-row justify="start" type="flex" style="margin-top: 20px">
              <a-col :span="8" :offset="1">
                <a-form-item label="百度语音AppKey" name="baiduBceAppKey">
                  <a-input v-model:value="vdata.configData.baiduBceAppKey" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="百度语音AppSecret" name="baiduBceAppSecret">
                  <a-input v-model:value="vdata.configData.baiduBceAppSecret" :placeholder="vdata.configDataDesen.baiduBceAppSecret || '请填写'" autocomplete="off" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item class="bottom-btn">
              <a-button v-if="$access('ENT_PUSH_CONFIG_EDIT')" :disabled="!vdata.isEdit" type="primary" :loading="vdata.btnLoading" @click="confirm"><check-circle-outlined />确认更新</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script setup lang="ts">
import { API_URL_SYS_CONFIG, req, $getConfigs, upload } from '@/api/manage'
import { ref, reactive, onMounted, getCurrentInstance, watch } from 'vue'

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

  const wxMpConfigFormModel = ref()
  const appPushConfigFormModel = ref()
  const baiduBceConfigFormModel = ref()


// 通用处理脱敏数据逻辑
function ruleProcessByDesen(rule, value, callback){
  if (!vdata.configDataDesen[rule.field] && !value) {
    return Promise.reject(new Error(rule.message))
  }
  return Promise.resolve()
}

  const vdata = reactive ({
    isEdit:$access('ENT_PUSH_CONFIG_EDIT'),
    btnLoading: false,
    groupKey: 'wxMpConfig',
    configData: {} as any, // 配置保存对象
    configDataDesen: {} as any, // 脱敏数据
    wx3rdCheckFileResult: '', // 微信三方校验文件解析结果
    payUrl: '',
    wxMpConfigRules: {
      wxmpUrl: [{ required: true, message: '请上传微信公众号二维码', trigger: 'blur' }],
      wxAppId: [{ required: true, message: '请填写微信公众号AppId', trigger: 'blur' }],
      wxAppSecret: [{ required: true, message: '请填写微信公众号wxAppSecret', trigger: 'blur', validator: ruleProcessByDesen }],
      paySuccMsgTemplateId: [{ required: true, message: '请填写模板消息ID', trigger: 'blur' }],
      noticeMsgTemplateId: [{ required: true, message: '请填写通知模板消息ID', trigger: 'blur' }]
    },
    appPushConfigRules: {
      uniPushVersion: [{ required: true, message: '请选择uniPush版本', trigger: 'blur' }],
      uniPushAppId: [{ required: true, message: '请填写uniPush_appId', trigger: 'blur' }],
      uniPushAppKey: [{ required: true, message: '请填写uniPush_appKey', trigger: 'blur' }],
      uniPushMasterSecret: [{ required: true, message: '请填写uniPush_masterSecret', trigger: 'blur', validator: ruleProcessByDesen }],
      uniPushCloudUrl: [{ required: true, message: '请填写云函数URL', trigger: 'blur' }]
    },
    baiduBceConfigRules: {
      baiduBceAppKey: [{ required: true, message: '请填写百度语音AppKey', trigger: 'blur' }],
      baiduBceAppSecret: [{ required: true, message: '请填写百度语音AppSecret', trigger: 'blur', validator: ruleProcessByDesen }]
    }
  })

  onMounted(()=>{
    detail()

    $getConfigs('applicationConfig').then(res => {
      res.forEach(item => {
        if(item.configKey === 'paySiteUrl') {
          vdata.payUrl = item.configVal.toString().replace('http://', '').replace('https://', '')
        }
      })
    })
  })

  function detail () { // 获取基本信息
    $getConfigs(vdata.groupKey).then(res => {

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

      vdata.groupKey = res[0].groupKey

      res.forEach(item => {
        vdata.configData[item.configKey] = item.configVal
        vdata.configDataDesen[item.configKey] = item.configValDesen
      })
    })
  }

  /* watch(() => vdata.wx3rdCheckFileResult, (nv, ov) => {
    vdata.wxMpConfigData.wxCheckFileName = nv['fileOriginName']
    vdata.wxMpConfigData.wxCheckFileValue = nv['value']
  }) */

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

  // 确认更新
  function confirm (e) {
    if ('wxMpConfig' === vdata.groupKey) {

      wxMpConfigFormModel.value.validate().then(valid => {
        saveConfig('确认修改公众号提醒配置吗？')
      })

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

      appPushConfigFormModel.value.validate().then(valid => {
        saveConfig('确认修改app推送配置吗？')
      })

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

      baiduBceConfigFormModel.value.validate().then(valid => {
        saveConfig('确认修改百度语音配置吗？')
      })

    }
  }

  function saveConfig(msg) {
    $infoBox.confirmPrimary(msg, '', () => {
      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
      })
    })
  }

</script>
<style lang="less" scoped>
  .bottom-btn{
    /deep/ div{
      display: flex;
      justify-content: center;
    }
  }
</style>
