<template>
  <a-card :bordered="false">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 3, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="styleResponsive ? { md: 9, sm: 19, xs: 24 } : { flex: '1' }"
    >
      <a-form-item label="短信平台" name="smsType">
        <a-radio-group v-model:value="form.smsType">
          <a-radio :value="1">阿里云</a-radio>
          <a-radio :value="2">腾讯云</a-radio>
          <a-radio :value="3">七牛云</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="AccessKeyId" name="accessKeyId">
        <a-input
          v-model:value="form.accessKeyId"
          placeholder="请输入 AccessKeyId"
          allow-clear
          :maxlength="100"
        />
      </a-form-item>
      <a-form-item label="AccessKeySecret" name="accessKeySecret">
        <a-input-password
          v-model:value="form.accessKeySecret"
          placeholder="请输入 AccessKeySecret"
          allow-clear
          :maxlength="200"
        />
      </a-form-item>
      <a-form-item label="短信签名" name="smsSign">
        <a-input
          v-model:value="form.smsSign"
          placeholder="请输入短信签名"
          allow-clear
          :maxlength="20"
        />
      </a-form-item>

      <a-divider orientation="left">短信验证码（通知用户）</a-divider>
      <a-form-item label="是否开启" name="smsNoticeUser">
        <a-radio-group v-model:value="form.smsNoticeUser">
          <a-radio :value="1">开启</a-radio>
          <a-radio :value="0">关闭</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="模板内容">
        <span class="ele-text-secondary">
          验证码 ${code}，您正在进行身份验证，请勿泄露给他人！
        </span>
      </a-form-item>
      <a-form-item label="模板ID" name="smsUserTemplateId">
        <a-input
          v-model:value="form.smsUserTemplateId"
          placeholder="请输入用户验证码模板ID"
          allow-clear
          :maxlength="100"
        />
      </a-form-item>

      <a-divider orientation="left">新订单通知（通知商家）</a-divider>
      <a-form-item label="是否开启" name="smsNoticeMerchant">
        <a-radio-group v-model:value="form.smsNoticeMerchant">
          <a-radio :value="1">开启</a-radio>
          <a-radio :value="0">关闭</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="模板ID" name="smsMerchantTemplateId">
        <a-input
          v-model:value="form.smsMerchantTemplateId"
          placeholder="请输入商家通知模板ID"
          allow-clear
          :maxlength="100"
        />
      </a-form-item>
      <a-form-item label="接收手机号" name="smsMerchantMobiles">
        <a-input
          v-model:value="form.smsMerchantMobiles"
          placeholder="多个手机号用英文逗号分隔"
          allow-clear
          :maxlength="200"
        />
        <div class="ele-text-secondary" style="font-size: 12px">
          新订单将向以上手机号发送短信通知
        </div>
      </a-form-item>

      <a-form-item label="保存">
        <a-button type="primary" :loading="loading" @click="save">保存</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useThemeStore } from '@/store/modules/theme';
import { storeToRefs } from 'pinia';
import { FormInstance } from 'ant-design-vue/es/form';
import useFormData from '@/utils/use-form-data';
import { batchSaveShopSetting, getShopSettingCategoryValues } from '@/api/shop/shopSetting';
import type { ShopSetting } from '@/api/shop/shopSetting/model';

const category = 'sms';

const themeStore = useThemeStore();
const { styleResponsive } = storeToRefs(themeStore);

const loading = ref(false);
const formRef = ref<FormInstance | null>(null);

const { form, assignFields } = useFormData<ShopSetting>({
  smsType: 1,
  accessKeyId: '',
  accessKeySecret: '',
  smsSign: '',
  smsNoticeUser: 1,
  smsUserTemplateId: '',
  smsNoticeMerchant: 1,
  smsMerchantTemplateId: '',
  smsMerchantMobiles: ''
});

const rules = reactive({
  accessKeyId: [
    {
      required: true,
      message: '请输入 AccessKeyId',
      type: 'string',
      trigger: 'blur'
    }
  ],
  accessKeySecret: [
    {
      required: true,
      message: '请输入 AccessKeySecret',
      type: 'string',
      trigger: 'blur'
    }
  ],
  smsSign: [
    {
      required: true,
      message: '请输入短信签名',
      type: 'string',
      trigger: 'blur'
    }
  ]
});

const toBool = (val: any): number =>
  val === true || val === 'true' || val === '1' || val === 1 ? 1 : 0;

const load = async () => {
  try {
    const values = await getShopSettingCategoryValues(category);
    if (values && Object.keys(values).length > 0) {
      assignFields(values);
      // 数字/布尔值转换
      form.smsNoticeUser = toBool((values as any).smsNoticeUser);
      form.smsNoticeMerchant = toBool((values as any).smsNoticeMerchant);
    }
  } catch (e: any) {
    // 未配置时忽略
  }
};

const save = () => {
  if (!formRef.value) return;
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      batchSaveShopSetting(category, form as Record<string, unknown>)
        .then(() => {
          message.success('保存成功');
        })
        .catch((e) => {
          message.error(e.message);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {});
};

onMounted(load);
</script>
