<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import dayjs, { type Dayjs } from 'dayjs';
import { VxeUI } from 'vxe-pc-ui';
import { useRequest } from 'alova/client';
import { searchTagsFromSelectableMethod } from '@/request/api/patient.api';
import { list2Groups } from '@/tools/data';
import { educationMethod } from '@/request/api/education.api';
import { editNotifyMethod, getNotifyDetailMethod } from '@/request/api/notify.api';
import { notification } from 'ant-design-vue';
import type { NotifyModel } from '@/model/notify.model';
const props = defineProps<{
  data?: any;
}>();

const emits = defineEmits<{
  submit: [data?: any];
  back: [];
}>();

const formRef = ref<FormInstance>();

// 表单数据
const form = reactive<Partial<Omit<NotifyModel, 'sendTime'>> & { sendTime: Dayjs | undefined }>({
  isSwitch: true, // 是否启用
  name: '', // 名称
  status: '0', // 启用状态
  pushType: '0' as '0' | '1', // 通知渠道：1-企业微信
  sendTime: undefined as Dayjs | undefined, // 发送时间
  content: '', // 发送内容
  popularScienceArticleTitle: '', // 宣教文章标题
  popularScienceArticleId: undefined, //宣教id
  tagIds: [] as string[], // 用户标签ID
  tagNameStr: '',
  tagNames: [] as string[],
  isExpire: false, // 是否定期
  days: 0, // 定期天数
});
// 新增或者修改
const { loading: updating, send: submitUpdate } = useRequest(editNotifyMethod, { immediate: false });
// 获取用户标签
const { data: selectable, loading: tagsLoading } = useRequest(searchTagsFromSelectableMethod, { initialData: [] });
// 用户标签选项（分组）
const tagOptions = computed(() =>
  list2Groups(
    selectable.value.filter((tag: any) => !tag.disabled),
    'category',
    (key) => ({ 1: '系统标签', 2: '个人标签' })[key]!
  )
);

// 获取宣教列表（不传page和size，获取全部数据）
const educationList = ref<any[]>([]);
const { loading: educationLoading, onSuccess: onEducationSuccess } = useRequest(() => educationMethod(undefined, undefined, {}), {
  initialData: { data: [], total: 0 },
  immediate: true,
});
onEducationSuccess(({ data: { data } }) => {
  educationList.value = data || [];
});

// 通知渠道选项
const notificationChannelOptions = [
  // { label: '企业微信', value: '1' },
  { label: '站内', value: '0' },
];
// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  enabled: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
  notificationChannel: [{ required: true, message: '请选择通知渠道', trigger: 'change' }],
  sendTime: [{ required: true, message: '请选择发送时间', trigger: 'change' }],
  sendContent: [{ required: true, message: '请输入发送内容', trigger: 'blur' }],
  isExpire: [
    { required: true, message: '请选择查阅时长', trigger: 'change' },
    {
      validator: () => {
        if (form.isExpire && (!form.days || form.days <= 0)) {
          return Promise.reject('请输入天数');
        }
        return Promise.resolve();
      },
      trigger: 'change',
    },
  ],
  days: [
    {
      validator: () => {
        if (form.isExpire && (!form.days || form.days <= 0)) {
          return Promise.reject('请输入天数');
        }
        return Promise.resolve();
      },
      trigger: 'blur',
    },
  ],
};

const sendTimeDate = computed({
  get: () => {
    return form.sendTime ? form.sendTime.toDate() : undefined;
  },
  set: (value: Date | undefined) => {
    form.sendTime = value ? dayjs(value) : undefined;
  },
});

const getNotifyDetail = async (id?: string) => {
  const res: any = await getNotifyDetailMethod(id || '');
  if (res) {
    Object.assign(form, res);
    form.isSwitch = form.status === '0' ? true : false;
    if (form.sendTime) {
      form.sendTime = typeof form.sendTime === 'string' ? dayjs(form.sendTime) : form.sendTime;
    }
    // 如果标签为空，则清空标签
    if (!form.tagIds || form.tagIds.length === 0) {
      form.tagIds = [];
      form.tagNames = [];
      form.tagNameStr = '';
    }
  }
};
// 初始化数据
onMounted(() => {
  console.log(props.data, 'props.data');
  if (props.data && props.data.id) {
    getNotifyDetail(props.data.id);
  }
});

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    
    // 验证发送时间不能早于当前时间
    if (form.sendTime && form.sendTime.isBefore(dayjs())) {
      notification.error({
        message: '发送时间不能早于现在',
      });
      return;
    }
    
    updating.value = true;
    const tagIdsArray = Array.isArray(form.tagIds) ? form.tagIds : form.tagIds ? [form.tagIds] : [];
    const tagNames = tagIdsArray.map((id: string) => selectable.value.find((option: any) => option.id === id)?.name || '');
    const status = form.isSwitch ? '0' : '1';
    const submitData: Partial<NotifyModel> = {
      ...form,
      status: status,
      sendTime: form.sendTime ? form.sendTime.format('YYYY-MM-DD HH:mm:ss') : undefined,
      tagNameStr: tagNames.join(',') || '',
      tagNames: tagNames,
    };
    submitUpdate({
      ...submitData,
    }).then(() => {
      // 保存成功后，同步更新 form 的 status，保持 isSwitch 不变
      if (submitData.status) {
        form.status = submitData.status;
      }
      notification.success({
        message: '保存成功',
      });
      emits('submit', { ...form });
    });
  } catch (error) {
    updating.value = false;
    console.error('表单验证失败', error);
  } finally {
    updating.value = false;
  }
};

// 返回
const handleBack = () => {
  emits('back');
  VxeUI.modal.close(`edit-notify-modal`);
};

// 监听查阅时长类型切换，切换为长期时清除天数
watch(
  () => form.isExpire,
  (newVal) => {
    if (!newVal) {
      form.days = undefined;
    }
  }
);
</script>

<template>
  <div class="notify-form-container">
    <!-- 顶部按钮 -->
    <div class="header-actions">
      <vxe-button type="primary" content="返回" @click="handleBack"></vxe-button>
      <vxe-button type="submit" status="primary" content="保存" @click="handleSave" :loading="updating"></vxe-button>
    </div>

    <!-- 表单内容 -->
    <div class="form-content">
      <a-form ref="formRef" :model="form" :rules="rules" layout="horizontal" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <!-- 名称、用户标签、启用 - 一行排列 -->
        <div class="form-row">
          <a-form-item label="名称" name="name" required class="form-row-item">
            <a-input v-model:value="form.name" placeholder="请输入" />
          </a-form-item>

          <a-form-item label="用户标签" name="tagIds" class="form-row-item mr-10 ml-10">
            <vxe-select
              v-model="form.tagIds"
              :options="tagOptions"
              placeholder="请选择"
              style="width: 100%"
              multiple
              filterable
              clearable
              :optionProps="{ value: 'id', label: 'name' }"
              :optionGroupProps="{ options: 'groups' }"
            />
          </a-form-item>

          <a-form-item label="启用" name="status" required class="form-row-item">
            <a-switch v-model:checked="form.isSwitch" />
          </a-form-item>
        </div>
        <!-- 通知渠道 -->
        <a-form-item label="通知渠道" name="pushType" required class="form-row-item">
          <a-radio-group v-model:value="form.pushType">
            <a-radio v-for="option in notificationChannelOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </a-radio>
          </a-radio-group>
        </a-form-item>

        <!-- 微信内容标签 -->
        <div class="mb-4 font-bold">{{ form.pushType === '1' ? '微信内容' : '内容' }}</div>

        <!-- 发送时间 -->
        <a-form-item label="发送时间" name="sendTime" required class="form-row-item">
          <vxe-date-picker v-model="sendTimeDate" type="datetime" placeholder="请输入" format="yyyy-MM-dd HH:mm:ss" :time-format="'HH:mm:ss'" style="width: 100%" />
        </a-form-item>
        <!--  查阅时长-->
        <a-form-item label="查阅时长" name="isExpire" required class="form-row-item">
          <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap">
            <a-radio-group v-model:value="form.isExpire">
              <a-radio :value="false">长期</a-radio>
              <a-radio :value="true">定期</a-radio>
            </a-radio-group>
            <template v-if="form.isExpire">
              <a-input-number v-model:value="form.days" :min="1" placeholder="请输入" style="width: 120px" @change="() => formRef?.validateFields(['readTimeType', 'days'])" />
              <span>天</span>
            </template>
          </div>
        </a-form-item>
        <!-- 发送内容 -->
        <a-form-item label="发送内容" name="sendContent" required class="form-row-item" v-if="form.pushType === '1'">
          <a-textarea v-model:value="form.content" placeholder="请输入" allow-clear />
        </a-form-item>

        <!-- 宣教文章链接 -->
        <a-form-item label="宣教文章链接" name="articleLink" class="form-row-item">
          <vxe-select
            v-model="form.popularScienceArticleId"
            :options="educationList"
            placeholder="请输入搜索"
            :loading="educationLoading"
            clearable
            filterable
            :optionProps="{ value: 'id', label: 'title' }"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.notify-form-container {
  padding: 24px;
  background: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.form-content {
  flex: 1;
  overflow: auto;
}

.form-row {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  // margin-bottom: 24px;
}

.form-row-item {
  flex: 1;
  margin-bottom: 0;
}

.form-row-item :deep(.ant-form-item) {
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
}

.form-row-item :deep(.ant-form-item-label) {
  flex: 0 0 auto;
  width: auto;
  min-width: 80px;
  text-align: left;
  padding-right: 8px;
  padding-bottom: 0;
}

.form-row-item :deep(.ant-form-item-control) {
  flex: 1;
  width: 100%;
}

.wechat-content-label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
}

:deep(.ant-form-item-label > label.ant-form-item-required:not(.ant-form-item-required-mark-optional)) {
  &::before {
    display: inline-block;
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
    content: '*';
  }
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-input),
:deep(.ant-select-selector),
:deep(.ant-picker) {
  border-color: #d9d9d9;
}

:deep(.ant-radio-group) {
  display: flex;
  gap: 16px;
}
</style>
