<template>
  <div style="background: #fff">
    <div class="account-settings-info-view">
      <a-form ref="redConfigInfoFormModelRef" :rules="defaultConfigRules" :model="vdata.configData" layout="vertical">


        <a-divider orientation="left">初始配置</a-divider>
          <a-row justify="space-between" type="flex">
            <a-col :span="6" style="margin-left:2% ">
              <a-form-item>
                <a-button type="primary" @click="addDomain"><PlusOutlined />新增</a-button>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-for="(item, index) in vdata.deviceList" :key="index" justify="space-between" type="flex">
            <a-col :span="4" :offset="1">
              <a-form-item  layout="vertical" label="贴牌名称">
                <a-input v-model:value="item.name" placeholder="请输入贴牌名称" />
              </a-form-item>
            </a-col>
            <a-col :span="4" :offset="1">
              <a-form-item label="选择小程序平台" name="type">
                <a-select show-search  :value="item.type" placeholder="选择小程序平台" @change="changeFunc"    >
                  <a-select-option v-for="(value) in vdata.typeList" :key="index" :value="value.key">
                    {{ value.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4" :offset="1">
              <a-form-item label="小程序appid">
                <a-input v-model:value="item.appid" placeholder="请输入小程序appid" />
              </a-form-item>
            </a-col>
            <a-col :span="4" :offset="1">
              <a-form-item label="贴牌域名">
                <a-input v-model:value="item.domain" placeholder="请输入贴牌域名" />
              </a-form-item>
            </a-col>
            <a-button v-if="index >= 1" danger type="link" @click="removeDomain(item)"><MinusCircleOutlined class="delete-button" /></a-button>
          </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 redConfigInfoFormModelRef = ref()

const vdata = reactive ({
  isEdit:$access('ENT_PUSH_CONFIG_EDIT'),
  btnLoading: false,
  groupKey: 'oemDomainConfig',
  deviceList: [{ appid: '', name: '',domain:"",type:"" ,platformType:""}] as any, // 配置对象
  configData: {} as any, // 配置保存对象
  mchApplyTimeLimit: '', // 商户进件时间限制
  agentApplyTimeLimit: '', // 服务商进件时间限制
  castOutFeeRule: { feeType: 'FIX', fixFee: 0, feeRate: 0, freeLimit: 0, applyLimit: 0 },
  isvList: [],
  typeList:[{name:'微信',key:"weChat"},{name:'支付宝',key:"Alipay"}],
  platformList:[{name:'商家',key:"store"},{name:'服务商',key:"service"},{name:'支付',key:"pay"}],
  agentList: [],
}) as any

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

onMounted(()=>{
  // 配置信息
  getConfig()
})


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

  })
}

// 更新配置
function confirm () {
  redConfigInfoFormModelRef.value.validate().then(valid => {

    $infoBox.confirmPrimary('确认更新默认配置吗？', '', () => {
      // vdata.btnLoading = true // 打开按钮上的 loading
      const oemContent = {};
      // const obj = vdata.deviceList.reduce((accumulator, currentValue) => ({ ...accumulator, ...currentValue }), {});

      for (let i=0;i<vdata.deviceList.length;i++){
        oemContent[vdata.deviceList[i].appid] = {}
        oemContent[vdata.deviceList[i].appid] = vdata.deviceList[i];
      }
      vdata.configData.oemContent = JSON.stringify(oemContent)
      const reqData:any = Object.assign({}, vdata.configData)

      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)
}

function addDomain() {
  vdata.deviceList.push({  appid: '', name: '',domain:"",type:"" ,platformType:"" })
}
function removeDomain(item) {
  const index = vdata.deviceList.indexOf(item)
  if (index != -1) {
    vdata.deviceList.splice(index, 1)
  }
}
function changePayFunc(value, selectedOptions){
  vdata.deviceList[selectedOptions.key].platformType = value
  // vdata.noticeDate.typeName = value
  // vdata.noticeDate.packageType = selectedOptions.key
}
function changeFunc(value, selectedOptions){
  vdata.deviceList[selectedOptions.key].type = value
  // vdata.noticeDate.typeName = value
  // vdata.noticeDate.packageType = selectedOptions.key
}
</script>
<style lang="less" scoped>
.bottom-btn{
  /deep/ div{
    display: flex;
    justify-content: center;
  }
}
/deep/ .ant-col-offset-1{
  margin-left:2% !important;
}
</style>
