<template>
  <a-layout>
    <a-layout-sider width="500" :style="{ backgroundColor: '#fff', overflow: 'hidden', height: '80vh' }">
      <TaskLeft ref="refTaskLeft"  @fileCallback="fileCallback"  @actCallback="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 }"
          :columnConfig="{ resizable: true }"
          :row-config="{ isCurrent: true, isHover: true }"
        >
      <template #toolbar_buttons>
        <div style="margin: 5px; background-color:;width: 200px;text-align: center;">
          <vxe-button status="primary" @click="handleAllocTask()"> 分配任务</vxe-button>
       </div>
        <div style="margin: 5px; background-color:;width: 200px;text-align: center;">
            <vxe-button  mode="text" icon="vxe-icon-refresh" @click="clearAllFilterEvent()"></vxe-button>
        </div>
      </template>
  
        <template #item_default="{ row }">
            <vxe-button mode="text" status="primary" @click="handleShowDrawer(row)">
              <div class="cell-content">{{ row.item }}</div>
            </vxe-button>
          </template>
        </vxe-grid>
        <a-drawer title="详情" placement="bottom" height="60%" :visible="showDrawer" :get-container="false" @close="closeDrawer" :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>
  <UserList ref="refUserList" @callBack="onAllocTask"/>
  <FileViewerModal @register="registerShowFileContentModal" :useStaticPrefixForDocx="true" />
</template>

<script lang="ts" setup>
  import { ref, nextTick, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { VXETable } from 'vxe-table';
  import { useModal } from '/@/components/Modal';
  import { VxeSelectEvents, VxeTablePropTypes, VxeColumnPropTypes, VxeTableInstance, VxeTableEvents } from 'vxe-table';

  import { saveProjectCheck,queryAllTask } from './components/api/AuditTask.api';
  import { getAllCheckMethodFiles } from './components/api/AuditCheckMethodItem.api';
  import UserList from './components/UserList.vue';
  import TaskLeft from './components/TaskLeft.vue';
  import FileViewerModal from '/@/components/onlinePreview/FileViewerModal.vue';


  const [registerShowFileContentModal, { openModal: openFileContentModel }] = useModal();

  function showFileContent(data) {
    if (data) {
      openFileContentModel(true, { record: data });
    }
  }
  
  const refUserList = ref();
  const tableRef = ref()
  const loading = ref(false);
  const showDrawer = ref(false);
  const fileList = ref([])

  const refTaskLeft = ref()
  const realNameList = ref([])
  interface FormDataVO {
    content: string;
    fileId: string;
  }

  const srhFormData = reactive<FormDataVO>({
    content: '',
    fileId: '',
  });

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

  const nameFilterRender: VxeColumnPropTypes.FilterRender = {
    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,
    },
    printConfig: {},
    importConfig: {},
    exportConfig: {},
    columns: [
      { type: 'checkbox', visible: true, width: '60', showOverflow: false },
      { field: 'item', title: '合规条目', showOverflow: 'title', sortable: true, filters: [{ data:''}], filterMethod:textFilterMethod,filterRender: nameFilterRender,width:"20%", slots: { default: 'item_default' },visible:true},
      { field: 'content', title: '检查项', sortable: true,filters: [{ data:''}], filterMethod:textFilterMethod,filterRender: nameFilterRender },
      { field: 'fileName', title: '参考文件', showOverflow: 'title', sortable: true, width:"15%", filters:fileList,filterMethod:fileFilterMethod,filterMultiple:true},
      { field: 'caNames', title: '控制项', sortable: true, width:"15%",visible:false},
      { field: 'realname', title: '填报人', sortable: true, width:"10%",visible:true,filters:realNameList,filterMultiple:true},
      { field: 'itemNum', title: '项目数', sortable: true, width:"10%",visible:true},
    ],
    toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true,
      export: true,
      print: true,
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
    scrollY: {
      enabled: true,
      gt: 50,
    },
    data: [],
  });


  const emit = defineEmits(['callBackAct']);  
  
  function handleSearch() {

  }

  async function iniData() {
    refTaskLeft.value.iniData()
    const retData = await queryAllTask({});
    gridOptions.data = retData;
    fileList.value = await getAllCheckMethodFiles({});
    const $table = tableRef.value;
    if($table) {
      $table.setFilter('fileName',fileList.value)
      await setUserFilterOptions(retData)
    }
    await clearAllFilterEvent()
  }

  async function handleShowDrawer(row) {
    desData.value = {
      item: row.item,
      content: row.content,
      caNames: row.caNames,
      fileName: row.fileName,
      filePath: row.filePath,
      fileId: row.fileId,
      fileTp: row.fileTp,
    };
    showDrawer.value = true;
  }

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

  
  async function handleAllocTask() {
    let ids = await getSelectIds();
    if(ids.length==0) {
      VXETable.modal.message({ content: '请选择记录', status: 'warning' });
      return 
    }
    refUserList.value.iniData()
  }

  async function onAllocTask(user) {
    let task = {userid:user.id}
    task["checkids"] = await getSelectIds();
    if(task["checkids"].length==0) {
      VXETable.modal.message({ content: '请选择记录', status: 'warning' });
      return 
    }
    await saveProjectCheck(task)
    await iniData()
  }

  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 setUserFilterOptions(data) {
    const names = await data.map(item => item.realname);  
    if(!names||names.length==0) return;
    const uniqueNames = [...new Set(names)]; 
    let filterUserOptions = []
    uniqueNames.forEach(function (ele) {
      let options = {label:ele,value:ele}
      filterUserOptions.push(options)
    });
    const $table = tableRef.value;
    $table.setFilter('realname',filterUserOptions)
  }


  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 iniData()

  }

  defineExpose({
    iniData,
    handleSearch,
    refresh,
  });
</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>
