<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="查看时间" prop="viewTime">
              <el-date-picker clearable v-model="queryParams.viewTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择查看时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="noticeList">
        <el-table-column type="index" label="序号" width="80" align="center" />
        <!-- <el-table-column label="接收通知的用户" align="center" prop="recipientId" />
        <el-table-column label="发送通知的用户" align="center" prop="senderId" /> -->
        <el-table-column label="通知内容" align="center" prop="msg" />
        <el-table-column label="查看状态" align="center" prop="viewStatus">
          <template #default="scope">
            <el-tag :type="scope.row.viewStatus === 0 ? 'danger' : 'success'">{{ scope.row.viewStatus === 0 ? '未读' : '已读' }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="查看时间" align="center" prop="viewTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.viewTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope"> <el-button link type="primary" @click="handleRoute(scope.row)">查看</el-button></template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改消息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="noticeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="接收通知的用户ID" prop="recipientId">
          <el-input v-model="form.recipientId" placeholder="请输入接收通知的用户ID" />
        </el-form-item>
        <el-form-item label="发送通知的用户ID" prop="senderId">
          <el-input v-model="form.senderId" placeholder="请输入发送通知的用户ID" />
        </el-form-item>
        <el-form-item label="配置id" prop="configId">
          <el-input v-model="form.configId" placeholder="请输入配置id" />
        </el-form-item>
        <el-form-item label="详情id" prop="detailId">
          <el-input v-model="form.detailId" placeholder="请输入详情id" />
        </el-form-item>
        <el-form-item label="通知内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="查看时间" prop="viewTime">
          <el-date-picker clearable v-model="form.viewTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择查看时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Notice" lang="ts">
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from '@/api/message/notice';
import { NoticeVO, NoticeQuery, NoticeForm } from '@/api/message/notice/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { useUserStoreHook } from '@/store/modules/user';

const noticeList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);

const queryFormRef = ref<ElFormInstance>();
const noticeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: NoticeForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  recipientId: undefined,
  senderId: undefined,
  configId: undefined,
  detailId: undefined,
  content: undefined,
  viewStatus: undefined,
  viewTime: undefined,
  remark: undefined
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    userId: userStore.userId,
    recipientId: undefined,
    senderId: undefined,
    configId: undefined,
    detailId: undefined,
    content: undefined,
    viewStatus: undefined,
    viewTime: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
    recipientId: [{ required: true, message: '接收通知的用户ID不能为空', trigger: 'blur' }],
    senderId: [{ required: true, message: '发送通知的用户ID不能为空', trigger: 'blur' }],
    configId: [{ required: true, message: '配置id不能为空', trigger: 'blur' }],
    detailId: [{ required: true, message: '详情id不能为空', trigger: 'blur' }],
    content: [{ required: true, message: '通知内容不能为空', trigger: 'blur' }],
    viewStatus: [{ required: true, message: '查看状态(0未读 1已读)不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询消息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNotice(queryParams.value);
  noticeList.value = res.rows;
  if (noticeList.value.length > 0) {
    noticeList.value.forEach((item) => {
      let obj = JSON.parse(item.content);
      item.route = obj.type;
      item.msg = obj.content;
    });
  }
  total.value = res.total;
  loading.value = false;
};
// 跳转到指定路由
const handleRoute = (row) => {
  proxy.$router.push({ path: row.route });
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  noticeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: NoticeVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加消息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: NoticeVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getNotice(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改消息';
};

/** 提交按钮 */
const submitForm = () => {
  noticeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateNotice(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addNotice(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: NoticeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除消息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delNotice(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'message/notice/export',
    {
      ...queryParams.value
    },
    `notice_${new Date().getTime()}.xlsx`
  );
};

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