<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-divider orientation="left">小程序基础信息</a-divider>
      <a-form-item label="AppID" name="miniAppId">
        <a-input
          allow-clear
          :maxlength="50"
          placeholder="请输入微信小程序 AppID"
          v-model:value="form.miniAppId"
        />
        <div class="ant-form-item-explain">微信公众平台 → 开发管理 → 开发设置 → AppID</div>
      </a-form-item>
      <a-form-item label="AppSecret" name="miniAppSecret">
        <a-input-password
          allow-clear
          :maxlength="100"
          placeholder="请输入微信小程序 AppSecret"
          v-model:value="form.miniAppSecret"
        />
        <div class="ant-form-item-explain">用于服务端接口调用（登录、支付等），请妥善保管</div>
      </a-form-item>

      <a-divider orientation="left">小程序页面配置</a-divider>
      <a-form-item label="首页路径" name="miniHomePath">
        <a-input
          allow-clear
          :maxlength="200"
          placeholder="如 pages/index/index"
          v-model:value="form.miniHomePath"
        />
      </a-form-item>
      <a-form-item label="分享标题" name="miniShareTitle">
        <a-input
          allow-clear
          :maxlength="50"
          placeholder="默认分享到好友/朋友圈的标题"
          v-model:value="form.miniShareTitle"
        />
      </a-form-item>
      <a-form-item label="分享图片" name="miniShareImage">
        <SelectFile
          :placeholder="'请选择分享图片'"
          :limit="1"
          :data="shareImageList"
          @done="chooseShareImage"
          @del="onDeleteShareImage"
        />
        <div class="ant-form-item-explain">建议尺寸：500x400 像素，不超过 1MB</div>
      </a-form-item>

      <a-divider orientation="left">客服与联系</a-divider>
      <a-form-item label="客服开关" name="miniKfEnabled">
        <a-switch
          v-model:checked="form.miniKfEnabled"
          checked-children="开"
          un-checked-children="关"
        />
      </a-form-item>
      <a-form-item label="客服类型" name="miniKfType">
        <a-radio-group v-model:value="form.miniKfType">
          <a-radio value="button">悬浮按钮</a-radio>
          <a-radio value="menu">菜单入口</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="联系客服" name="miniContactPhone">
        <a-input
          allow-clear
          :maxlength="30"
          placeholder="联系电话或客服微信号"
          v-model:value="form.miniContactPhone"
        />
      </a-form-item>

      <a-divider orientation="left">订阅消息</a-divider>
      <a-form-item label="订阅开关" name="miniSubscribeEnabled">
        <a-switch
          v-model:checked="form.miniSubscribeEnabled"
          checked-children="开"
          un-checked-children="关"
        />
      </a-form-item>
      <a-form-item label="模板ID" name="miniSubscribeTemplateIds">
        <a-textarea
          :rows="3"
          :maxlength="500"
          placeholder="多个模板ID用英文逗号分隔"
          v-model:value="form.miniSubscribeTemplateIds"
        />
        <div class="ant-form-item-explain">微信公众平台 → 功能 → 订阅消息 → 公共模板库</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';
import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
import { FileRecord } from '@/api/system/file/model';

const category = 'miniprogram';

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

const loading = ref(false);
const formRef = ref<FormInstance | null>(null);
const shareImageList = ref<ItemType[]>([]);

const { form, assignFields } = useFormData<ShopSetting>({
  miniAppId: '',
  miniAppSecret: '',
  miniHomePath: '',
  miniShareTitle: '',
  miniShareImage: '',
  miniKfEnabled: false,
  miniKfType: 'button',
  miniContactPhone: '',
  miniSubscribeEnabled: false,
  miniSubscribeTemplateIds: ''
});

const rules = reactive({
  miniAppId: [
    {
      required: true,
      message: '请输入微信小程序 AppID',
      type: 'string',
      trigger: 'blur'
    }
  ]
});

const toBool = (val: any): boolean =>
  val === true || val === 'true' || val === '1' || val === 1;

// 选择分享图片
const chooseShareImage = (data: FileRecord) => {
  shareImageList.value.push({ uid: data.id, url: data.path, status: 'done' });
  form.miniShareImage = data.path;
};

// 删除分享图片
const onDeleteShareImage = (index: number) => {
  shareImageList.value.splice(index, 1);
  form.miniShareImage = '';
};

const load = async () => {
  try {
    const values = await getShopSettingCategoryValues(category);
    if (values && Object.keys(values).length > 0) {
      assignFields(values);
      // 布尔值转换
      form.miniKfEnabled = toBool((values as any).miniKfEnabled);
      form.miniSubscribeEnabled = toBool((values as any).miniSubscribeEnabled);
      // 回显分享图片
      shareImageList.value = [];
      if (form.miniShareImage) {
        shareImageList.value.push({ uid: 1, url: form.miniShareImage as string, status: '' });
      }
    }
  } 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>
