<template>
  <div style="background: #fff">
    <div class="account-settings-info-view">
      <a-form ref="defaultConfigInfoFormModelRef" :rules="defaultConfigRules" :model="vdata.configData" layout="vertical">
        <a-row style="margin-top: 20px">
          <a-divider orientation="left">商户初始配置</a-divider>
          <a-col :span="6" :offset="2">
            <a-form-item label="商户注册时是否必填邀请码" name="mchRegisterInviteCodeRequired">
              <a-radio-group v-model:value="vdata.configData.mchRegisterInviteCodeRequired">
                <a-radio :value="'1'">必填（并且验证邀请码是否可用）</a-radio>
                <a-radio :value="'0'">非必填（不录入表示平台商户）</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item name="mchRegisterLevel">
              <template #label>
                <span>商户注册时默认商户级别</span> &nbsp;
                <a-popover placement="top">
                  <template #title><span>商户级别</span></template>
                  <template #content>
                    <p>M0商户：简单模式（页面简洁，仅基础收款功能）</p>
                    <p>M1商户：高级模式（支持api调用， 支持配置应用及分账、转账功能）</p>
                  </template>
                  <question-circle-outlined />
                </a-popover>
              </template>

              <a-radio-group v-model:value="vdata.configData.mchRegisterLevel">
                <a-radio :value="'M0'">M0</a-radio>
                <a-radio :value="'M1'">M1</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item name="mchRegisterSelfCashierState">
              <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-radio-group v-model:value="vdata.configData.mchRegisterSelfCashierState">
                <a-radio :value="'1'">开启</a-radio>
                <a-radio :value="'0'">关闭</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item name="mchRegisterWebCashierState">
              <template #label>
                <span>商户注册/创建时[WEB收银台]默认状态</span> &nbsp;
                <a-popover placement="top">
                  <template #title><span>WEB收银台</span></template>
                  <template #content>
                    <p>关闭：商户无WEB银台支付方式</p>
                    <p>开启：商户显示WEB收银台支付方式</p>
                  </template>
                  <question-circle-outlined />
                </a-popover>
              </template>

              <a-radio-group v-model:value="vdata.configData.mchRegisterWebCashierState">
                <a-radio :value="'1'">开启</a-radio>
                <a-radio :value="'0'">关闭</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="$hasMemberEnt()" :span="6" :offset="2">
            <a-form-item name="mchRegisterMemberState">
              <template #label>
                <span>商户注册/创建时[会员功能]默认状态</span> &nbsp;
                <a-popover placement="top">
                  <template #title><span>会员功能</span></template>
                  <template #content>
                    <p>开启：商户注册/创建时默认开启会员相关功能</p>
                    <p>关闭：商户注册/创建时默认关闭会员相关功能</p>
                    <p>相关功能：商户会员菜单、扫码会员支付、支付自定义金额</p>
                  </template>
                  <question-circle-outlined />
                </a-popover>
              </template>

              <a-radio-group v-model:value="vdata.configData.mchRegisterMemberState">
                <a-radio :value="'1'">开启</a-radio>
                <a-radio :value="'0'">关闭</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="$hasMemberEnt()" :span="6" :offset="2">
            <a-form-item label="商户会员最大储值余额(元), 0表示不限制">
              <a-input-number v-model:value="vdata.configData.mchMbrMaxBalance" :min="0" placeholder="请填写" style="width: 60%;" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row v-if="$hasAgentEnt()">
          <a-divider orientation="left">服务商初始配置</a-divider>
          <a-col :span="6" :offset="2">
            <a-form-item label="服务商注册时是否审核" name="agentRegisterIsAudit">
              <a-radio-group v-model:value="vdata.configData.agentRegisterIsAudit">
                <a-radio :value="'1'">审核（需由平台进行审核）</a-radio>
                <a-radio :value="'0'">不审核（注册后直接为可用服务商）</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item label="服务商创建下级服务商是否审核" name="agentNewSubIsAudit">
              <a-radio-group v-model:value="vdata.configData.agentNewSubIsAudit">
                <a-radio :value="'1'">审核（需由平台进行审核）</a-radio>
                <a-radio :value="'0'">不审核（注册后直接为可用服务商）</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item label="服务商注册时是否必填邀请码" name="agentRegisterInviteCodeRequired">
              <a-radio-group v-model:value="vdata.configData.agentRegisterInviteCodeRequired">
                <a-radio :value="'1'">必填（并且验证邀请码是否可用）</a-radio>
                <a-radio :value="'0'">非必填（不录入表示平台服务商）</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="$hasAgentEnt()">
          <a-col :span="6" :offset="2">
            <a-form-item label="服务商是否支持划拨码牌、设备" name="isSupportAgentAllot">
              <a-radio-group v-model:value="vdata.configData.isSupportAgentAllot">
                <a-radio :value="'1'">支持</a-radio>
                <a-radio :value="'0'">不支持</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-divider orientation="left">进件初始配置</a-divider>
          <a-col :span="6" :offset="2">
            <a-form-item label="商户进件是否需要运营平台预审核" name="mchApplymentPreAudit">
              <a-radio-group v-model:value="vdata.configData.mchApplymentPreAudit">
                <a-radio :value="'0'">无需预审</a-radio>
                <a-radio :value="'1'">需要预审</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="2">
            <a-form-item label="商户自主进件时间限制" name="mchApplyTimeLimit">
              <a-space direction="vertical" :size="12">
                <a-time-range-picker
                  v-model:value="vdata.mchApplyTimeLimit"
                  :show-time="{ format: 'HH:mm:ss' }"
                  format="HH:mm:ss"
                  :placeholder="['开始时间', '结束时间']"
                  :disabled="vdata.mchApplyTimeLimit == ''"
                  @change="onRangeChangeMch"
                />
              </a-space>
              <a-checkbox style="margin-left:15px" :checked="vdata.mchApplyTimeLimit == '' " @change="changeMchRange">不限制</a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="$hasAgentEnt()">
          <a-col :span="6" :offset="2">
            <a-form-item label="服务商进件是否需要运营平台预审核" name="agentApplymentPreAudit">
              <a-radio-group v-model:value="vdata.configData.agentApplymentPreAudit">
                <a-radio :value="'0'">无需预审</a-radio>
                <a-radio :value="'1'">需要预审</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="2">
            <a-form-item label="服务商发起进件默认时间限制" name="agentApplyTimeLimit">
              <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-checkbox style="margin-left:15px" :checked="vdata.agentApplyTimeLimit == '' " @change="changeAgentRange">不限制</a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="2">
            图片上传大小限制：<a-input-number v-model:value="vdata.configData.applymentImgUploadSize" :min="2" :max="20" placeholder="请填写" /> M （最小2M 最大20M）
          </a-col>
        </a-row>

        <a-divider orientation="left">其他初始配置</a-divider>
        <a-row style="margin-top: 20px">
          <a-col :span="6" :offset="2">
            <a-form-item label="默认渠道商">
              <a-select v-model:value="vdata.configData.defaultIsvNo" placeholder="默认渠道商">
                <a-select-option key="">不配置</a-select-option>
                <a-select-option v-for="(item) in vdata.isvList" :key="item.isvNo">{{ item.isvName }} [{{ item.isvNo }}]</a-select-option>
              </a-select>
              <span class="jeepay-tip-text">
                *配置此默认渠道商：<br>
                当<span v-if="$hasAgentEnt()">服务商或</span>特约商户注册成功后，将默认为此渠道商下商户。
              </span>
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item label="官方渠道(服务商)">
              <a-select v-model:value="vdata.configData.defaultAgentNo" placeholder="官方渠道">
                <a-select-option key="">不配置</a-select-option>
                <a-select-option v-for="(item) in vdata.agentList" :key="item.agentNo">{{ item.agentName }} [{{ item.agentNo }}]</a-select-option>
              </a-select>
              <span class="jeepay-tip-text">
                *配置此默认渠道商：<br>
                当<span v-if="$hasAgentEnt()">服务商或</span>特约商户注册成功后，将默认为此渠道商下商户。
              </span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6" :offset="2">
            <a-form-item label="默认密码" name="defaultPassword">
              <a-input v-model:value="vdata.configData.defaultPassword" />
              <span class="jeepay-tip-text">置空表示不更改</span>
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item label="默认收款商户号" name="sysPaymentMchNo">
              <a-input v-model:value="vdata.configData.sysPaymentMchNo" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="6" :offset="2">
            <a-form-item label="自营商户" name="platformSelfMchNo">
              <JeepaySearchInfoInput v-model:value="vdata.configData.platformSelfMchNo" placeholder="自营商户号" :mchNoAndName="true" showType="MCH" />
              <span class="jeepay-tip-text">用作： 服务商佣金提现审核可以选择自营商户的转账渠道</span>
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item label="微信小程序审核帐号" name="wxAuditUser">
              <a-input v-model:value="vdata.configData.wxAuditUser" placeholder="请填写微信小程序审核帐号" />
              <span class="jeepay-tip-text">
                配置小程序审核帐号(即系统商户号)，多个请以英文 , 隔开<br>
                * 表示全部
              </span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="6" :offset="2">
            <a-form-item label="广告名称" name="adsName">
              <a-input v-model:value="vdata.configData.adsName" placeholder="请输入广告名称" />
            </a-form-item>
          </a-col>
          <a-col :span="6" :offset="2">
            <a-form-item label="广告链接" name="adsUrl">
              <a-input v-model:value="vdata.configData.adsUrl" placeholder="请输入广告链接" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row style="margin-top: 20px">
          <a-col :span="6" :offset="2">
            <a-form-item label="设置提现手续费规则" name="castOutFeeRule">
              额度： 设置最低 <a-input-number v-model:value="vdata.castOutFeeRule.applyLimit" /> 元可发起提现 <br><br>
              规则： 提现 <a-input-number v-model:value="vdata.castOutFeeRule.freeLimit" /> 元以内免收手续费 <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" /> 元
                  </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" /> %
                  </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" /> 元 +  <a-input-number v-model:value="vdata.castOutFeeRule.feeRate" /> %
                  </template>
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item class="bottom-btn" style="margin-top: 10px">
          <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" :disabled="!vdata.isEdit" type="primary" :loading="vdata.btnLoading" @click="confirm"><check-circle-outlined />确认更新</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import {API_URL_SYS_CONFIG, API_URL_ISV_LIST, req, $getConfigs, API_URL_AGENT_LIST} from '@/api/manage'
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import dayjs, {Dayjs} from 'dayjs'
import { Base64 } from 'js-base64'

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

const defaultConfigInfoFormModelRef = ref()

const vdata = reactive ({
  isEdit:$access('ENT_PUSH_CONFIG_EDIT'),
  btnLoading: false,
  groupKey: 'defaultConfig',
  configData: {} as any, // 配置保存对象
  mchApplyTimeLimit: '', // 商户进件时间限制
  agentApplyTimeLimit: '', // 服务商进件时间限制
  castOutFeeRule: { feeType: 'FIX', fixFee: 0, feeRate: 0, freeLimit: 0, applyLimit: 0 },
  isvList: [],
  agentList: [],
}) as any

const defaultConfigRules = {
  defaultPassword: [{ min:6, message: '请录入至少6位的密码', trigger: 'blur' }],
}

onMounted(()=>{
  // 配置信息
  getConfig()
  // 渠道组列表
  getIsvList()
  // 服务商列表
  getAgentList()
})

function getAgentList() {
  req.list(API_URL_AGENT_LIST, { pageSize: -1, level: 1 }).then( res => {
    vdata.agentList = res.records
  })
}

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

function getConfig() {
  $getConfigs(vdata.groupKey).then(res => {
    res.forEach(item => vdata.configData[item.configKey] = item.configVal )

    vdata.configData.defaultPassword = '' // 清空密码， 默认为空，保存生效 。

    // 转换 提现手续费对象
    if(vdata.configData.castOutFeeRule){

        vdata.castOutFeeRule = JSON.parse(vdata.configData.castOutFeeRule)
        if(vdata.castOutFeeRule.fixFee){
          vdata.castOutFeeRule.fixFee = Number.parseFloat((vdata.castOutFeeRule.fixFee / 100).toFixed(2))
        }
        if(vdata.castOutFeeRule.feeRate){
          vdata.castOutFeeRule.feeRate = Number.parseFloat((vdata.castOutFeeRule.feeRate * 100).toFixed(2))
        }
        if(vdata.castOutFeeRule.freeLimit){
          vdata.castOutFeeRule.freeLimit = Number.parseFloat((vdata.castOutFeeRule.freeLimit / 100).toFixed(2))
        }
        if(vdata.castOutFeeRule.applyLimit){
          vdata.castOutFeeRule.applyLimit = Number.parseFloat((vdata.castOutFeeRule.applyLimit / 100).toFixed(2))
        }
    }
    // 时间数据回显
    if (vdata.configData.mchApplyTimeLimit) {
      vdata.mchApplyTimeLimit = JSON.parse(vdata.configData.mchApplyTimeLimit)
      if (vdata.mchApplyTimeLimit[0]) {
        vdata.mchApplyTimeLimit[0] = dayjs(vdata.mchApplyTimeLimit[0], 'HH:mm:ss')
      }
      if (vdata.mchApplyTimeLimit[1]) {
        vdata.mchApplyTimeLimit[1] = dayjs(vdata.mchApplyTimeLimit[1], 'HH:mm:ss')
      }
    }
    if (vdata.configData.agentApplyTimeLimit) {
      vdata.agentApplyTimeLimit = JSON.parse(vdata.configData.agentApplyTimeLimit)
      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')
      }
    }

    // 最大储值金额
    if(vdata.configData.mchMbrMaxBalance){
      vdata.configData.mchMbrMaxBalance = Number.parseFloat((vdata.configData.mchMbrMaxBalance / 100).toFixed(2))
    }
  })
}

// 更新配置
function confirm () {
  if(!vdata.configData.applymentImgUploadSize) return  $infoBox.message.error('图片上传配置不可为空')
  defaultConfigInfoFormModelRef.value.validate().then(valid => {


    // 转换 提现手续费对象
    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))
    }


    $infoBox.confirmPrimary('确认更新默认配置吗？', '', () => {
      vdata.btnLoading = true // 打开按钮上的 loading
      const reqData:any = Object.assign({}, vdata.configData)

      reqData.defaultPassword = (vdata.configData.defaultPassword ? Base64.encode(vdata.configData.defaultPassword) : '' )
      reqData.castOutFeeRule = JSON.stringify(castOutFeeRule)
      reqData.applymentImgUploadSize = reqData.applymentImgUploadSize.toString()

      // 最大储值金额
      if ($hasMemberEnt()) {
        const mchMbrMaxBalance = vdata.configData.mchMbrMaxBalance ? vdata.configData.mchMbrMaxBalance : 0
        reqData.mchMbrMaxBalance = Number.parseInt((mchMbrMaxBalance * 100).toFixed(0)).toString()
      }

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

            getConfig()
          }).catch(res => {
        vdata.btnLoading = false
      })
    })
  })
}

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

  // 勾选“不限制”按钮时的时间数据处理 -- 商户配置
function changeMchRange(value){
  if (value.target.checked) {
    vdata.mchApplyTimeLimit = ''
    vdata.configData.mchApplyTimeLimit = ''
  } else {
    vdata.mchApplyTimeLimit = initDateRange.value
    vdata.configData.mchApplyTimeLimit = JSON.stringify(['00:00:00', '23:59:59'])
  }
}

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

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

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

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