<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :destroyOnClose="true"
    :centered="true"
    :useWrapper="true"
    @cancel="handleCancel"
    @ok="handleSuccess"
    title="新增"
  >
    <a-layout>
      <a-layout-sider :width="leftWidth" :style="{ backgroundColor: '#fff', overflow: 'hidden', height: '80vh' }">
        <TaskLeft ref="refTaskLeft" @file-callback="fileCallback" @act-callback="actCallback" />
      </a-layout-sider>
      <a-layout-content>
        <div style="padding: 0 10px; height: 80vh; position: relative">
          <vxe-grid
            size="small"
            ref="tableRef"
            auto-resize
            height="auto"
            v-bind="gridOptions"
            :loading="loading"
            :check-config="{ highlight: true }"
            :column-config="{ resizable: true,useKey:true }"
            :row-config="{ isCurrent: true, isHover: true,useKey:true }"
          >
            <template #toolbar_buttons>
              <a-space wrap>
                <a-button type="link" block @click="clearAllFilterEvent()">刷新</a-button>
                <a-button type="link" block @click="handleAllocTask()">分配</a-button>
              </a-space>
            </template>
            <template #pager>
              <vxe-pager
                v-show="gridOptions.pagerConfig.enabled"
                :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
                v-model:current-page="tablePage.currentPage"
                v-model:page-size="tablePage.pageSize"
                v-model:page-sizes="tablePage.pageSizes"
                :total="tablePage.total"
                @page-change="handlePageChange"
              />
            </template>
          </vxe-grid>
          <a-drawer
            title="详情"
            placement="bottom"
            height="60%"
            :visible="showDrawer"
            :get-container="false"
            @close="closeInnerDrawer"
            :style="{ position: 'absolute' }"
          >
            <a-descriptions title="" bordered :column="1">
              <a-descriptions-item label="条目">{{ desData?.item }}</a-descriptions-item>
              <a-descriptions-item label="内容">{{ desData?.complineContent }}</a-descriptions-item>
              <a-descriptions-item label="控制项">{{ desData?.caNames }}</a-descriptions-item>
              <a-descriptions-item label="参考文件">
                <a @click="showFileContent(desData)">{{ desData?.fileName }}</a>
              </a-descriptions-item>
            </a-descriptions>
          </a-drawer>
        </div>
      </a-layout-content>
    </a-layout>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, nextTick, reactive } from 'vue';
  import { VXETable, VxeColumnPropTypes } from 'vxe-table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { saveProjectCheck, queryAllTask } from '/@/views/newlib/components/api/AuditTask.api';
  import { defHttp } from '/@/utils/http/axios';
  import TaskLeft from './TaskLeft.vue';
  const checkUrl = '/audit/auditCheckMethod/findAllChecks';

  const emit = defineEmits(['callback', 'success']);
  const curProject = ref({});

  interface Option {
    label: string;
    value: string;
  }

  const leftWidth = ref(600);
  const options = ref<Option[]>([]);
  const filteredOptions = ref<Option[]>(options.value);
  const cgrpList = ref([]);
  const tableData = ref([]);
  const oldData = ref([]);
  const tableRef = ref();
  const loading = ref(false);
  const showDrawer = ref(false);
  const fileList = ref([]);
  const refTaskLeft = ref();
  const projectid = ref('');

  const collapsed = ref();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // await resetFields();
    curProject.value = data;
    projectid.value = data.pid;
    iniLibData();
    refTaskLeft.value.iniData();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter, defaultFullscreen: true });
  });

  const cgrpFilterMethod: VxeColumnPropTypes.FilterMethod = ({ value, row }) => {
    return row['cgrp'] == value;
  };

  const fileFilterMethod = ({ value, row }) => {
    return row['fileId'] == value;
  };

  const nameFilterRender = {
    name: 'VxeInput',
  };

  function textFilterMethod({ option, row, column }) {
    if (option.data) {
      return `${row[column.field]}`.indexOf(option.data) > -1;
    }
    return true;
  }

  const desData = ref();
  const gridOptions = reactive({
    border: true,
    keepSource: true,
    showOverflow: true,
    loading: false,
    checkboxConfig: { checkStrictly: false },
    columnConfig: {
      useKey: false,
      resizable: true,
    },
    rowConfig:{
      useKey: true,
    },
    
    printConfig: {},
    importConfig: {},
    exportConfig: {},
    columns: [
      { type: 'checkbox', visible: true, width: '60', showOverflow: false },
      {
        field: 'cgrpPath',
        title: '分组',
        sortable: true,
        visible: true,
        width: '10%',
        filters: cgrpList,
        filterMethod: cgrpFilterMethod,
        filterMultiple: true,
      },
      {
        field: 'item',
        title: '合规条目',
        sortable: true,
        filters: [{ data: '' }],
        filterMethod: textFilterMethod,
        filterRender: nameFilterRender,
        width: '20%',
        visible: true,
      },
      { field: 'content', title: '检查项', sortable: true, filters: [{ data: '' }], filterMethod: textFilterMethod, filterRender: nameFilterRender },
      { field: 'caNames', title: '控制项', sortable: true, width: '15%', visible: false },
      {
        field: 'fileName',
        title: '参考文件',
        showOverflow: 'title',
        sortable: true,
        width: '15%',
        filters: fileList,
        filterMethod: fileFilterMethod,
        filterMultiple: true,
      },
    ],
    pagerConfig: {
      enabled: true,
      pageSize: 10,
    },
    toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true,
      export: true,
      print: true,
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
    scrollY: {
      enabled: true,
      gt: 50,
    },
    data: [],
  });
  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
    pageSizes: [10, 30, 50, 100, 300, 500, 1000],
  });
  const handlePageChange = async ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage || 1;
    tablePage.pageSize = pageSize || 10;
    tablePage.total = tableData.value.length;
    let st = (tablePage.currentPage - 1) * tablePage.pageSize;
    let end = st + tablePage.pageSize;
    gridOptions.data = tableData.value.slice(st, end);
  };
  async function iniLibData() {
    gridOptions.loading = false;
    await nextTick(async () => {
      let check = { content: null, fileId: null, isPublic: true, projectid: projectid.value };
      oldData.value = tableData.value = await defHttp.get({ url: checkUrl, params: check });
      gridOptions.loading = false;
      await handlePageChange({ currentPage: 1, pageSize: 10 });
      await setFileList();
      cgrpList.value = [...new Set(tableData.value.map((item) => item.cgrp))].map((cgrp) => ({
        value: cgrp,
        label: tableData.value.find((item) => item.cgrp === cgrp).cgrpPath, // 提取对应的 cgrpPath
      }));
      const $table = tableRef.value;
      if ($table) {
        $table.setFilter('fileName', fileList.value);
        $table.setFilter('cgrpPath', cgrpList.value);
      }
    });

    await clearAllFilterEvent();
  }
  async function setFileList() {
    const uniqueFileList = Array.from(new Map(tableData.value.map((item) => [item.fileId, { value: item.fileId, label: item.fileName }])).values());
    fileList.value = uniqueFileList;
  }
  async function handleAllocTask() {
    let ids = await getSelectIds();
    if (ids.length == 0) {
      VXETable.modal.message({ content: '请选择记录', status: 'warning' });
      return;
    }
    let task = {};
    task['projectid'] = curProject.value.id;
    task['checkids'] = await getSelectIds();
    await saveProjectCheck(task);
    await iniLibData(curProject.value);
  }

  async function getSelectIds() {
    let ids = [];
    const $table = tableRef.value;
    if ($table) {
      const selRecords = $table.getCheckboxRecords();
      selRecords.forEach(function (ele) {
        ids.push(ele.checkid);
      });
    }
    return ids;
  }

  async function fileCallback(file) {
    await filterFileEvent(file);
  }

  async function actCallback(act) {
    gridOptions.data = await queryAllTask({ actId: act.id });
  }

  const filterFileEvent = (file) => {
    const $table = tableRef.value;
    if ($table) {
      const column = $table.getColumnByField('fileName');
      if (column) {
        column.filters.forEach((element) => {
          element.checked = false;
        });

        const option = column.filters.find((item) => item.value === file.id);
        if (option) {
          option.checked = true;
        }
        $table.updateData();
      }
    }
  };

  const clearAllFilterEvent = async () => {
    const $table = tableRef.value;
    if ($table) {
      $table.clearFilter();
    }
  };

  async function refresh() {
    await iniLibData(curProject.value);
  }

  function closeInnerDrawer() {
    showDrawer.value = false;
  }

  function handleCancel() {
    closeModal();
    // emit('success', isUpdate.value);
  }
  function handleSuccess() {
    emit('success');
  }
  defineExpose({
    iniLibData,
    refresh,
    fileCallback,
    actCallback,
  });
</script>

<style scope>
  .layout {
    background: #fff;
    height: calc(90vh - 120px);
    margin: 0px 0px 0px 0px;
    overflow: hidden;
    min-height: 400px;
  }
  .ant-descriptions-item-label {
    width: 150px;
  }

  .cell-content {
    text-align: left;
    white-space: normal; /* 允许文本换行 */
    word-wrap: break-word; /* 按单词折行 */
    overflow-wrap: break-word; /* 按单词折行 */
    max-width: 100%; /* 根据需要设置最大宽度 */
    display: -webkit-box; /* 使元素成为一个伸缩盒子模型 */
    -webkit-box-orient: vertical; /* 设置伸缩盒子的排列方向为垂直 */
    -webkit-line-clamp: 10; /* 限制行数为 10 行 */
    overflow: hidden; /* 隐藏超出部分 */
  }
</style>
