<template>
  <div class="project-field">
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="taskId"
      :columns="columns"
      :customRow="customRow"
      :datasource="datasource"
    >
      <template #toolbar>
        <ProjectFieldSearch @add="openEdit" @search="reload" @remove="removeBatch" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'comments'">
          <MdPreview v-if="record.comments" :id="id" :modelValue="decrypt(record.comments)" />
        </template>
        <template v-if="column.key === 'status'">
          <CheckCircleOutlined v-if="!record.status" :style="`color: #16a34a`" @click="updateForStatus(record)" />
          <CloseCircleOutlined v-else :style="`color: #ff0000`" @click="updateForStatus(record)" />
        </template>
        <template v-if="column.key === 'name'">
          <span class="text-gray-400">{{ record.name || '-' }}</span>
        </template>
        <template v-if="column.key === 'userId'">
          <a-space direction="vertical">
            <a-tooltip>
              <template #title>
                <div class="flex flex-col text-left">
                  <span>发布人：{{ record.nickname }}</span>
                  <span>发布时间：{{ record.createTime }}</span>
                  <span v-if="record.updateUserName">更新时间：{{ record.updateTime }}</span>
                </div>
              </template>
              <a-avatar :src="record.avatar" size="small" />
            </a-tooltip>
          </a-space>
        </template>
        <template v-if="column.key === 'action'">
          <a @click="openEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
            <a class="ele-text-danger">删除</a>
          </a-popconfirm>
        </template>
      </template>
    </ele-pro-table>
    <!-- 编辑弹窗 -->
    <ProjectFieldEdit
      v-model:visible="showEdit"
      :app-id="data.appId"
      :data="current"
      @done="reload"
    />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined, CheckCircleOutlined,CloseCircleOutlined } from '@ant-design/icons-vue';
  import { EleProTable } from 'ele-admin-pro';
  import type { DatasourceFunction } from 'ele-admin-pro/es/ele-pro-table/types';
  import ProjectFieldSearch from './app-field-search.vue';
  import { decrypt } from '@/utils/common';
  import { MdPreview } from 'md-editor-v3';
  import 'md-editor-v3/lib/preview.css';
  import { Project } from '@/api/project/project/model';
  import ProjectFieldEdit from './app-field-edit.vue';
  import { ProjectField, ProjectFieldParam } from '@/api/project/projectField/model';
  import {
    pageProjectField,
    removeProjectField,
    removeBatchProjectField,
    updateProjectField
  } from '@/api/project/projectField';
  import gfm from '@bytemd/plugin-gfm';
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  import highlight from '@bytemd/plugin-highlight';

  const props = defineProps<{
    appId: any;
    data: Project;
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  const selection = ref<ProjectField[]>([]);
  // 当前编辑数据
  const current = ref<ProjectField | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  const id = 'preview-only';

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 搜索条件
    where.appId = props.appId;
    return pageProjectField({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<any[]>([
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 90,
      align: 'center'
    },
    {
      title: '标题',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      align: 'center',
      ellipsis: true
    },
    {
      title: '内容',
      dataIndex: 'comments',
      key: 'comments',
      ellipsis: true
    },
    {
      title: '发布人',
      dataIndex: 'userId',
      key: 'userId',
      align: 'center',
      width: 90,
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center',
      hideInSetting: true
    }
  ]);

  const updateForStatus = (row?: ProjectField) => {
    updateProjectField({
      id: row?.id,
      status: row?.status == 0 ? 1 : 0
    }).then(() => {
      message.success('操作成功');
      reload();
    });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: ProjectField) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 搜索 */
  const reload = (where?: ProjectFieldParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  /* 删除单个 */
  const remove = (row: ProjectField) => {
    const hide = message.loading('请求中..', 0);
    removeProjectField(row.id)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value?.length) {
      message.error('请至少选择一条数据');
      return;
    }
    if (selection.value?.length) {
      Modal.confirm({
        title: '提示',
        content: '确定要删除选中的记录吗?',
        icon: createVNode(ExclamationCircleOutlined),
        maskClosable: true,
        onOk: () => {
          const hide = message.loading('请求中..', 0);
          removeBatchProjectField(selection.value.map((d) => d.id))
            .then((msg) => {
              hide();
              message.success(msg);
              reload();
            })
            .catch((e) => {
              hide();
              message.error(e.message);
            });
        }
      });
    }
  };

  /* 自定义行属性 */
  const customRow = (record: ProjectField) => {
    return {
      // 行双击事件
      onDblclick: () => {
        openEdit(record)
      }
    };
  };

  // 插件
  const plugins = ref([
    gfm({
      locale: zh_HansGfm
    }),
    highlight()
  ]);

  watch(
    () => props.appId,
    (appId) => {
      if (appId) {
        reload();
      }
    },
    { immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'ProjectFieldIndex'
  };
</script>
