<template>
  <div class="app-task">
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="taskId"
      :columns="columns"
      :datasource="datasource"
      tool-class="ele-toolbar-form"
      class="sys-org-table"
    >
      <template #toolbar>
        <ProductTabsSearch @add="openEdit" @remove="removeBatch" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'comments'">
          <byte-md-viewer
            :value="decrypt(record.comments)"
            :plugins="plugins"
          />
        </template>
        <template v-if="column.key === 'action'">
          <a @click="moveUp(record)">上移<ArrowUpOutlined /></a>
          <a-divider type="vertical" />
          <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>
    <!-- 编辑弹窗 -->
    <ProductTabsEdit
      v-model:visible="showEdit"
      :product-id="productId"
      :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 } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type { DatasourceFunction } from 'ele-admin-pro/es/ele-pro-table/types';
  import ProductTabsSearch from './product-tabs-search.vue';
  import { decrypt } from '@/utils/common';
  import ProductTabsEdit from './product-tabs-edit.vue';
  import { AppField, AppFieldParam } from '@/api/oa/app/field/model';
  import {
    pageAppField,
    removeAppField,
    removeBatchAppField,
    updateAppField
  } from '@/api/oa/app/field';
  import { ArrowUpOutlined } from '@ant-design/icons-vue';
  import gfm from '@bytemd/plugin-gfm';
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  import highlight from '@bytemd/plugin-highlight';
  import { ProductTabs } from '@/api/oa/product/tabs/model';

  const props = defineProps<{
    productId: any;
    productTabs: ProductTabs[];
  }>();

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

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

  // 表格列配置
  const columns = ref<any[]>([
    {
      title: '名称',
      dataIndex: 'name',
      width: 180
    },
    {
      title: '内容',
      dataIndex: 'comments',
      key: 'comments',
      ellipsis: true
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      sorter: true,
      width: 100,
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center',
      hideInSetting: true
    }
  ]);

  const moveUp = (row?: AppField) => {
    updateAppField({
      id: row?.id,
      sortNumber: Number(row?.sortNumber) + 1
    }).then((msg) => {
      message.success(msg);
      reload();
    });
  };

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

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

  /* 删除单个 */
  const remove = (row: AppField) => {
    const hide = message.loading('请求中..', 0);
    removeAppField(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);
          removeBatchAppField(selection.value.map((d) => d.id))
            .then((msg) => {
              hide();
              message.success(msg);
              reload();
            })
            .catch((e) => {
              hide();
              message.error(e.message);
            });
        }
      });
    }
  };

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

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

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

<style lang="less" scoped>
  .user-box {
    display: flex;
    align-items: center;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
      margin-right: 7px;
    }
    .last-time {
      margin-left: 12px;
    }
    .content {
      .text {
        max-width: 90%;
      }
    }
  }
  .nickname {
    .ele-text-heading {
      font-weight: bold;
    }
  }
</style>
