<template>
  <el-container v-loading="loading" :element-loading-text="t('modules.adv.loading')">
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth">
        <el-form-item :label="t('modules.adv.advType')" prop="advType">
          <el-select v-model="form.model.advType" :placeholder="t('modules.adv.selectAdvType')" style="width: 100%">
            <el-option :label="t('modules.adv.indexPage')" value="INDEX" />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('modules.adv.advTitle')" prop="title">
          <el-input v-model="form.model.title" :placeholder="t('modules.adv.enterAdvTitle')"></el-input>
        </el-form-item>

        <el-form-item :label="t('modules.adv.advImage')" prop="advImage">
          <sa-upload-image v-model="imageArray" :max-count="1" :accept="['jpg', 'jpeg', 'png']" :max-size="5"
            :direct-upload="true" :width="375" :height="200" :placeholder="t('modules.adv.uploadImage')" />
        </el-form-item>

        <el-form-item :label="t('modules.adv.linkType')" prop="linkType">
          <el-radio-group v-model="form.model.linkType">
            <el-radio label="IN">{{ t('modules.adv.internalLink') }}</el-radio>
            <el-radio label="OUT">{{ t('modules.adv.externalLink') }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="t('modules.adv.link')" prop="link">
          <el-input v-model="form.model.link" :placeholder="t('modules.adv.enterLink')"></el-input>
        </el-form-item>

        <el-form-item :label="t('modules.adv.serialNo')" prop="serialNo">
          <el-input-number v-model="form.model.serialNo" :min="0" :max="999" style="width: 100%" />
        </el-form-item>

        <el-form-item :label="t('modules.adv.status')" prop="statusFlag">
          <el-radio-group v-model="form.model.statusFlag">
            <el-radio :label="true">{{ t('modules.adv.enabled') }}</el-radio>
            <el-radio :label="false">{{ t('modules.adv.disabled') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="modal.params.type == 'add'" type="primary" @click="confirm">{{ t('modules.adv.save')
        }}</el-button>
      <el-button v-if="modal.params.type == 'edit'" type="primary" @click="confirm">{{ t('modules.adv.update')
        }}</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
import { cloneDeep } from 'lodash';
import { onMounted, reactive, ref, unref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { useFormConfig } from '@/hooks/useFormConfig';
import { api } from '../content.service';

const { t } = useI18n();

// 使用表单配置hooks
const { formLabelWidth } = useFormConfig({ enWidth: '140px' });
const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
  },
});

// 添加 编辑 form
let formRef = ref(null);
const loading = ref(false);

// 图片数组和字符串的双向绑定
const imageArray = computed({
  get() {
    return form.model.advImage ? [form.model.advImage] : [];
  },
  set(value) {
    form.model.advImage = value.length > 0 ? value[0] : '';
  },
});

const form = reactive({
  model: {
    advType: 'INDEX',
    title: '',
    advImage: '',
    linkType: 'IN',
    link: '',
    serialNo: 0,
    statusFlag: true,
  },
  rules: {
    advType: [{ required: true, message: t('modules.adv.advTypeRequired'), trigger: 'change' }],
    title: [{ required: true, message: t('modules.adv.advTitleRequired'), trigger: 'blur' }],
    advImage: [{ required: true, message: t('modules.adv.advImageRequired'), trigger: 'change' }],
    linkType: [{ required: true, message: t('modules.adv.linkTypeRequired'), trigger: 'change' }],
    serialNo: [{ required: true, message: t('modules.adv.serialNoRequired'), trigger: 'blur' }],
  },
});

// 获取详情
async function getDetail(id) {
  loading.value = true;
  try {
    const { code, data } = await api.adv.detail(id);
    if (code == 200) {
      form.model = {
        advType: data.advType || 'INDEX',
        title: data.title || '',
        advImage: data.advImage || '',
        linkType: data.linkType || 'IN',
        link: data.link || '',
        serialNo: data.serialNo || 0,
        statusFlag: data.statusFlag ?? true,
      };
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error(t('modules.adv.getDetailFailed'));
  }
  loading.value = false;
}

// 表单关闭时提交
async function confirm() {
  unref(formRef).validate(async (valid) => {
    if (!valid) return;

    let submitForm = cloneDeep(form.model);
    try {
      const { code } =
        props.modal.params.type == 'add'
          ? await api.adv.add(submitForm)
          : await api.adv.edit(props.modal.params.id, submitForm);
      if (code == 200) {
        ElMessage.success(t('message.saveSuccess'));
        emit('modalCallBack', { event: 'confirm' });
      }
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error(t('message.submitFailed'));
    }
  });
}

async function init() {
  if (props.modal.params.id) {
    await getDetail(props.modal.params.id);
  }
}

onMounted(() => {
  init();
});
</script>
