<template>
  <div class="main-container">
    <div class="detail-head">
      <!--      <div class="left" @click="back()">-->
      <!--        <span class="iconfont iconxiangzuojiantou !text-xs"></span>-->
      <!--        <span class="ml-[1px]">{{ t('returnToPreviousPage') }}</span>-->
      <!--      </div>-->
      <!--      <span class="adorn">|</span>-->
      <span class="right">{{ pageName }}</span>
    </div>
    <el-card class="box-card !border-none" shadow="never">
      <el-form :model="formData" label-width="270px" ref="formRef" :rules="formRules" class="page-form">
        <!--
                <el-form-item :label="t('weChatPayAppid')">
                  <el-input v-model="formData.we_chat_pay_appid" clearable :placeholder="t('weChatPayAppidPlaceholder')"
                            class="input-width"/>
                </el-form-item>
                -->

        <el-form-item :label="t('weChatPayAppId')" prop="we_chat_pay_app_id">
          <el-input v-model="formData.we_chat_pay_app_id" clearable :placeholder="t('weChatPayAppIdPlaceholder')"
                    class="input-width"/>
        </el-form-item>
        <!--
                <el-form-item :label="t('weChatPayMiniappId')">
                  <el-input v-model="formData.we_chat_pay_miniapp_id" clearable
                            :placeholder="t('weChatPayMiniappIdPlaceholder')" class="input-width"/>
                </el-form-item>
        -->
        <el-form-item :label="t('weChatPayMchId')" prop="we_chat_pay_mch_id">
          <el-input v-model="formData.we_chat_pay_mch_id" clearable :placeholder="t('weChatPayMchIdPlaceholder')"
                    class="input-width"/>
        </el-form-item>

        <el-form-item :label="t('weChatPayKey')" prop="we_chat_pay_key">
          <el-input v-model="formData.we_chat_pay_key" clearable :placeholder="t('weChatPayKeyPlaceholder')"
                    class="input-width"/>
        </el-form-item>
        <!--
                <el-form-item :label="t('weChatPayMiniappSecret')">
                  <el-input v-model="formData.we_chat_pay_miniapp_secret" clearable
                            :placeholder="t('weChatPayMiniappSecretPlaceholder')" class="input-width"/>
                </el-form-item>
        -->
        <el-form-item :label="t('weChatPayNotifyUrl')" prop="we_chat_pay_notify_url">
          <el-input disabled="true" v-model="formData.we_chat_pay_notify_url" clearable
                    :placeholder="t('weChatPayNotifyUrlPlaceholder')" class="input-width"/>
        </el-form-item>

        <el-form-item :label="t('上传微信商户私钥(apiclient_key.pem)')" prop="we_chat_pay_mch_secret_cert">
          <el-input v-model="formData.we_chat_pay_mch_secret_cert" clearable
                    :placeholder="t('请上传商户私钥')" class="input-width"/>
          <div>
            <input type="file"
                   @change="handleFileUpload($event,'we_chat_pay_mch_secret_cert','config_we_chat_pay_mch_secret_cert')">
          </div>
        </el-form-item>


        <el-form-item :label="t('上传微信商户公钥(apiclient_cert.pem)')" prop="we_chat_pay_mch_public_cert_path">
          <el-input v-model="formData.we_chat_pay_mch_public_cert_path" clearable
                    :placeholder="t('请上传商户公钥')" class="input-width"/>
          <input type="file"
                 @change="handleFileUpload($event,'we_chat_pay_mch_public_cert_path','config_we_chat_pay_mch_public_cert_path')">
        </el-form-item>

        <!--
                <el-form-item :label="t('alipayAppId')">
                  <el-input v-model="formData.alipay_appId" clearable :placeholder="t('alipayAppIdPlaceholder')"
                            class="input-width"/>
                </el-form-item>



                <el-form-item :label="t('alipayRsaPrivateKey')">
                  <el-input v-model="formData.alipay_rsa_private_key" clearable
                            :placeholder="t('alipayRsaPrivateKeyPlaceholder')" class="input-width"/>
                </el-form-item>

                <el-form-item :label="t('alipayPublicKey')">
                  <el-input v-model="formData.alipay_public_key" clearable :placeholder="t('alipayPublicKeyPlaceholder')"
                            class="input-width"/>
                </el-form-item>

                <el-form-item :label="t('alipayNotifyUrl')" prop="alipay_notify_url">
                  <el-input v-model="formData.alipay_notify_url" clearable :placeholder="t('alipayNotifyUrlPlaceholder')"
                            class="input-width"/>
                </el-form-item>
        -->
        <el-form-item :label="t('H5站点地址')" prop="h5_site_url">
          <el-input disabled="true" v-model="formData.h5_site_url" clearable
                    :placeholder="t('H5站点地址')"
                    class="input-width"/>
        </el-form-item>

        <el-form-item :label="t('H5站点二维码')" prop="h5_qrcode_url">
          <el-input disabled="true" v-model="formData.h5_qrcode_url" clearable :placeholder="t('H5站点二维码')"
                    class="input-width"/>
          <el-button style="margin-left: 15px;" type="primary" @click="resetQrCode()">{{ t('重新生成二维码') }}</el-button>
        </el-form-item>

        <el-form-item v-if="formData.ol_h5_qrcode_url" :label="t('原始H5站点二维码')" prop="h5_qrcode_url">
          <div>
            <p style="color: red;">重新生成二维码后->点击"保存"将替换此二维码</p>
            <img :src="formData.ol_h5_qrcode_url" alt="">
            <a :href="formData.ol_h5_qrcode_url" target="downloadFile" download="h5_qrcode.png">
              <el-button type="primary">打开二维码</el-button>
            </a>
          </div>
        </el-form-item>


      </el-form>

    </el-card>
    <div class="fixed-footer-wrap">
      <div class="fixed-footer">
        <el-button type="primary" @click="onSave(formRef)">{{ t('save') }}</el-button>
        <!--        <el-button @click="back()">{{ t('cancel') }}</el-button>-->
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, computed, watch} from 'vue'
import {t} from '@/lang'
import {useDictionary} from '@/app/api/dict'
import type {FormInstance} from 'element-plus'
import {getConfigInfo, addConfig, editConfig, getConfigList, resetH5SiteQRCode,} from '@/addon/hygl/api/config';
import {useRoute} from 'vue-router'
import {ElMessage} from 'element-plus'
import {uploadFile} from "@/addon/hygl/api/common";

const route = useRoute()
const id: number = parseInt(route.query.id);
const loading = ref(false)
const pageName = route.meta.title


/**
 * 表单数据
 */
const initialFormData = {
  id: 0,
  we_chat_pay_appid: '',
  we_chat_pay_app_id: '',
  we_chat_pay_miniapp_id: '',
  we_chat_pay_mch_id: '',
  we_chat_pay_key: '',
  we_chat_pay_miniapp_secret: '',
  we_chat_pay_notify_url: '',
  alipay_appId: '',
  alipay_rsa_private_key: '',
  alipay_public_key: '',
  alipay_notify_url: '',
  we_chat_pay_mch_secret_cert: '',
  we_chat_pay_mch_public_cert_path: '',
  h5_site_url:'',
  h5_qrcode_url:'',
  ol_h5_qrcode_url:'',
}
const formData: Record<string, any> = reactive({...initialFormData})

const setFormData = async (id: number = 0) => {
  Object.assign(formData, initialFormData)
  const data = await (await getConfigInfo(id)).data
  Object.keys(formData).forEach((key: string) => {
    if (data[key] != undefined) formData[key] = data[key]
  })
}
setFormData();

const formRef = ref<FormInstance>()
// 选中数据
const selectData = ref<any[]>([])

// 字典数据


// 表单验证规则
const formRules = computed(() => {
  return {
    we_chat_pay_appid: [
      {required: true, message: t('weChatPayAppidPlaceholder'), trigger: 'blur'},

    ],
    we_chat_pay_app_id: [
      {required: true, message: t('weChatPayAppIdPlaceholder'), trigger: 'blur'},

    ]
    ,
    we_chat_pay_miniapp_id: [
      {required: true, message: t('weChatPayMiniappIdPlaceholder'), trigger: 'blur'},

    ]
    ,
    we_chat_pay_mch_id: [
      {required: true, message: t('weChatPayMchIdPlaceholder'), trigger: 'blur'},

    ]
    ,
    we_chat_pay_key: [
      {required: true, message: t('weChatPayKeyPlaceholder'), trigger: 'blur'},

    ]
    ,
    we_chat_pay_miniapp_secret: [
      {required: true, message: t('weChatPayMiniappSecretPlaceholder'), trigger: 'blur'},

    ]
    ,
    we_chat_pay_notify_url: [
      {required: true, message: t('weChatPayNotifyUrlPlaceholder'), trigger: 'blur'},

    ]
    ,
    we_chat_pay_mch_secret_cert: [
      {required: true, message: t('商户私钥必传'), trigger: 'blur'},
    ],
    we_chat_pay_mch_public_cert_path: [
      {required: true, message: t('商户公钥必传'), trigger: 'blur'},
    ],

    alipay_appId: [
      {required: true, message: t('alipayAppIdPlaceholder'), trigger: 'blur'},
    ],
    alipay_rsa_private_key: [
      {required: true, message: t('alipayRsaPrivateKeyPlaceholder'), trigger: 'blur'},

    ]
    ,
    alipay_public_key: [
      {required: true, message: t('alipayPublicKeyPlaceholder'), trigger: 'blur'},

    ]
    ,
    alipay_notify_url: [
      {required: true, message: t('alipayNotifyUrlPlaceholder'), trigger: 'blur'},

    ]
    ,
  }
})

const onSave = async (formEl: FormInstance | undefined) => {
  if (loading.value || !formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      let data = formData

      const save = editConfig
      save(data).then(res => {
        loading.value = false
        setFormData()//刷新页面
        // history.back()
      }).catch(err => {
        loading.value = false
      })

    }
  })
}

// 验证手机号格式
const mobileVerify = (rule: any, value: any, callback: any) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error(t('generateMobile')))
  } else {
    callback()
  }
}

// 验证身份证号
const idCardVerify = (rule: any, value: any, callback: any) => {
  if (value && !/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)) {
    callback(new Error(t('generateIdCard')))
  } else {
    callback()
  }
}

// 验证邮箱号
const emailVerify = (rule: any, value: any, callback: any) => {
  if (value && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
    callback(new Error(t('generateEmail')))
  } else {
    callback()
  }
}


// 验证请输入整数
const numberVerify = (rule: any, value: any, callback: any) => {
  if (!Number.isInteger(value)) {
    callback(new Error(t('generateNumber')))
  } else {
    callback()
  }
}
const back = () => {
  history.back()
}

//重新生成二维码
const resetQrCode = async () => {

  let data = formData
  if (!data.id) {
    ElMessage({
      message: '请先填写必要信息并点击保存后再试',
      type: 'warning',
    })
    return
  }

  let aa = resetH5SiteQRCode(data.id).then(res => {
    if (res.code){
      formData.h5_qrcode_url = res.data.url
    }
    // history.back()
  }).catch(err => {
    console.log(err)
  })

}

//上传文件(单文件上传)
const handleFileUpload = (event: Event, name: string, path: string) => {
  const fileInput = event.target as HTMLInputElement;
  if (!fileInput.files || fileInput.files.length === 0) {
    return;
  }

  const file = fileInput.files[0];
  let form_data = new FormData();

  form_data.append('file', file); // 使用正确的 file 变量
  form_data.append('path', path); // 使用正确的 path 变量
  uploadFile(form_data).then(res => {
    console.log(222, res)
    if (res.code) {
      formData[name] = res.data.file_path
    }
    // loading.value = false
    // history.back()
  }).catch(err => {
    // loading.value = false
  })
};
</script>

<style lang="scss" scoped></style>