<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth">
        <el-form-item :label="t('modules.notification.messageTitle')">
          <el-input v-model="templateTitle" readonly />
        </el-form-item>

        <el-form-item :label="t('modules.notification.messageContent')">
          <el-input v-model="templateMessage" type="textarea" :rows="3" readonly />
        </el-form-item>

        <el-form-item :label="t('modules.notification.pagePath')" v-if="templatePages">
          <el-input v-model="templatePages" readonly />
        </el-form-item>

        <el-form-item :label="t('modules.notification.receivingUsers')" prop="uids">
          <el-button type="primary" @click="openUserSelect" plain>
            <el-icon>
              <Plus />
            </el-icon>
            {{ t('modules.notification.selectUsers') }} ({{ form.model.uids.length }})
          </el-button>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button type="primary" @click="confirm" :loading="sending">{{ sending ? t('modules.notification.sending') :
        t('modules.notification.sendingMessage') }}</el-button>
    </el-footer>
  </el-container>
</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useModal } from '@/sheep/hooks';
import { api } from '../content.service';
import UserSelect from '@/app/shop/admin/user/list/select.vue';

const { t } = useI18n();

// 使用表单配置hooks
const { formLabelWidth } = useFormConfig({ enWidth: '160px' });

const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
  },
});

const formRef = ref(null);
const sending = ref(false);

// 模板数据计算属性
const templateTitle = computed(() => props.modal.params.templateData?.title || '');
const templateMessage = computed(() => props.modal.params.templateData?.message || '');
const templatePages = computed(() => props.modal.params.templateData?.pages || '');

const form = reactive({
  model: {
    id: props.modal.params.id,
    uids: [],
  },
  rules: {
    uids: [
      { required: true, message: t('modules.notification.selectUsersRequired'), trigger: 'blur' },
      {
        validator: (_, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error(t('modules.notification.selectAtLeastOneUser')));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
  },
});

// 打开用户选择弹窗
function openUserSelect() {
  useModal(
    UserSelect,
    {
      title: '选择用户',
      multiple: true,
      ids: form.model.uids
    },
    {
      confirm: (data) => {
        if (data && Array.isArray(data)) {
          form.model.uids = data.map(user => user.id);
        }
      }
    }
  );
}

// 发送消息
async function confirm() {
  formRef.value.validate(async (valid) => {
    if (!valid) return;

    sending.value = true;
    try {
      const { code, message } = await api.notification.sendNotice({
        id: form.model.id,
        uids: form.model.uids,
      });

      if (code == 200) {
        ElMessage.success(t('modules.notification.sendSuccess'));
        emit('modalCallBack', { event: 'confirm' });
      }
    } catch (error) {
      console.error('发送失败:', error);
      ElMessage.error(t('modules.notification.sendFailed'));
    }
    sending.value = false;
  });
}
</script>

<style lang="scss" scoped>
.el-main {
  .el-form {
    max-width: 100%;
  }
}
</style>
