<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <PermissionBtn @btnEvent="buttonClick"></PermissionBtn>
      </template>
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'isExternal'">
          <a-tag color="green" v-if="record.isExternal">外部链接</a-tag>
          <a-tag color="blue" v-else>系统功能</a-tag>
        </template>
        <template v-if="column.key === 'isShow'">
          <a-switch
            v-model:checked="record.isShow"
            checkedChildren="启用"
            unCheckedChildren="停用"
            @change="changeIsShow(record)"
          />
        </template>
        <template v-if="column.key === 'isDevelop'">
          <a-tag color="yellow" v-if="record.isDevelop">开放</a-tag>
          <a-tag color="gray" v-else>不开放</a-tag>
        </template>
        <template v-if="column.key === 'appShow'">
          <a-tag color="orange" v-if="record.appShow">显示</a-tag>
          <a-tag color="gray" v-else>不显示</a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-button
            v-if="(nowPage - 1) * nowLimit + index != 0"
            type="dashed"
            @click="sortUp(index, record)"
          >
            <template #icon>
              <Icon icon="bi:arrow-up-circle" :size="20" />
            </template>
          </a-button>
          <a-button
            v-if="(nowPage - 1) * nowLimit + index + 1 != total"
            type="dashed"
            @click="sortdown(index, record)"
          >
            <template #icon>
              <Icon icon="bi:arrow-down-circle" :size="20" />
            </template>
          </a-button>
        </template>
      </template>
    </BasicTable>
    <SpecialModal ref="modalForm" @register="registerModal" @submit="submit" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, watch, createVNode, unref } from 'vue';
  import { Modal, message } from 'ant-design-vue';
  import { useModal } from '@/components/Modal';
  import { BasicTable, useTable } from '@/components/Table';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import SpecialModal from './Modal/index.vue';
  import {
    LoadDataBaseInfo,
    AddOrUpdateForm,
    DeleteEntity,
    UpdateIsShow,
  } from '@/api/sys/specialcolumn';
  import { columns, searchFormSchema } from './index.data';
  import Icon from '@/components/Icon/Icon.vue';

  const { createMessage } = useMessage();

  // 弹窗的数据
  const modalForm = ref();
  // 默认数据
  const modalData = reactive({
    title: '',
    data: {
      id: '' as string,
      title: '' as string,
      logoTitle: '' as string,
      isShow: false as boolean,
      isDevelop: false as boolean,
      appShow: false as boolean,
      isExternal: false as boolean,
      linkOrApi: '' as string,
      sort: 0 as number,
      imgUrl: '' as string,
    } as any,
  });
  // 分页信息
  let nowPage = 0;
  let nowLimit = 0;
  let total = 0;
  // 表格数据
  const registerTableData = ref([]);

  // 弹窗
  const [registerModal, { openModal, closeModal }] = useModal();
  // 表格
  const [registerTable, { reload, getSelectRows, getPaginationRef }] = useTable({
    api: LoadDataBaseInfo,
    columns: columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    showIndexColumn: false,
    rowSelection: {
      type: 'radio',
    },
    useSearchForm: true,
    bordered: true,
    showTableSetting: true,
    handleSearchInfoFn(info) {
      return info;
    },
    afterFetch: (res) => {
      let pagination: any = getPaginationRef();
      // 分页信息
      nowPage = pagination.current;
      nowLimit = pagination.pageSize || pagination.defaultPageSize;
      total = pagination.total;
      // 表格数据
      registerTableData.value = res;
    },
  });
  // 修改是否显示状态
  const changeIsShow = (record) => {
    UpdateIsShow({ id: record.id, isshow: record.isShow })
      .then((res) => {
        if (res) {
          createMessage.success(`修改表单状态成功`);
        } else {
          createMessage.error(`修改表单状态失败`);
        }
      })
      .catch(() => {
        createMessage.error('修改表单状态失败');
      });
  };
  // 按键分类
  const buttonClick = async (type) => {
    switch (type) {
      case 'btnAdd':
        let temp_add = cloneDeep(modalData);
        temp_add.title = '添加';
        temp_add.data = {
          id: '',
          title: '',
          logoTitle: '',
          isShow: false,
          isDevelop: false,
          appShow: false,
          isExternal: false,
          linkOrApi: '',
          sort: total + 1,
          imgUrl: '',
        };
        openModal(true, temp_add);
        break;
      case 'btnEdit':
        if (getSelectRows().length !== 1) {
          message.warning('请选择一条数据');
          return;
        }
        let temp_edit = cloneDeep(modalData);
        temp_edit.title = '编辑';
        temp_edit.data = cloneDeep(getSelectRows()[0]);
        openModal(true, temp_edit);
        break;
      case 'btnDelete':
        if (getSelectRows().length !== 1) {
          message.warning('请选择一条数据');
          return;
        }
        await DeleteEntity({ id: getSelectRows()[0].id });
        closeModal();
        reload();
        break;
    }
  };
  // 提交
  async function submit(data) {
    await AddOrUpdateForm(data);
    closeModal();
    reload();
  }
  // 向上排序
  async function sortUp(index, record) {
    let beforeSort = 0;
    let record_before_temp: any = {};

    if (nowPage != 1 && index == 0) {
      let params = { page: nowPage - 1, limit: nowLimit };
      record_before_temp = (await LoadDataBaseInfo(params)).items[nowLimit - 1];
      beforeSort = record_before_temp.sort;
    } else {
      registerTableData.value.forEach((item: any, index) => {
        if (item.id == record.id) {
          record_before_temp = registerTableData.value[index - 1];
          beforeSort = record_before_temp.sort;
        }
      });
    }
    record_before_temp.sort = record.sort;
    record.sort = beforeSort;
    await AddOrUpdateForm(record);
    await AddOrUpdateForm(record_before_temp);
    reload();
  }
  // 向下排序
  async function sortdown(index, record) {
    let afterSort = 0;
    let record_after_temp: any = {};

    if (index == nowLimit - 1) {
      let params = { page: nowPage + 1, limit: nowLimit };
      record_after_temp = (await LoadDataBaseInfo(params)).items[0];
      afterSort = record_after_temp.sort;
    } else {
      registerTableData.value.forEach((item: any, index) => {
        if (item.id == record.id) {
          record_after_temp = registerTableData.value[index + 1];
          afterSort = record_after_temp.sort;
        }
      });
    }
    record_after_temp.sort = record.sort;
    record.sort = afterSort;
    await AddOrUpdateForm(record);
    await AddOrUpdateForm(record_after_temp);
    reload();
  }
</script>
