<template>
  <div class="company-task">
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="fieldId"
      :columns="columns"
      :datasource="datasource"
      tool-class="ele-toolbar-form"
      class="sys-org-table"
    >
      <template #toolbar>
        <CompanyFieldSearch @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>
    <!-- 编辑弹窗 -->
    <CompanyFieldEdit
      v-model:visible="showEdit"
      :company-id="data.companyId"
      :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 CompanyFieldSearch from './company-field-search.vue';
  import { decrypt } from '@/utils/common';
  import { Company } from '@/api/oa/company/model';
  import CompanyFieldEdit from './company-field-edit.vue';
  import {
    CompanyField,
    CompanyFieldParam
  } from '@/api/oa/company/field/model';
  import {
    pageCompanyField,
    removeCompanyField,
    removeBatchCompanyField,
    updateCompanyField
  } from '@/api/oa/company/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';

  const props = defineProps<{
    companyId: any;
    data: Company;
  }>();

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

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 搜索条件
    where.companyId = props.companyId;
    return pageCompanyField({
      ...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?: CompanyField) => {
    updateCompanyField({
      id: row?.id,
      sortNumber: Number(row?.sortNumber) + 1
    }).then((msg) => {
      message.success(msg);
      reload();
    });
  };

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

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

  /* 删除单个 */
  const remove = (row: CompanyField) => {
    const hide = message.loading('请求中..', 0);
    removeCompanyField(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);
          removeBatchCompanyField(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.companyId,
    (companyId) => {
      if (companyId) {
        reload();
      }
    },
    { immediate: true }
  );
</script>

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