<template>
  <a-drawer
      title="关联文件"
      placement="right"
      :closable="true"
      width="60%"
      :open="showDrawer"
      :get-container="false"
      :loading="loading"
      @close="closeDrawer"
    >

    <template #extra>
      <a-button style="margin-right: 8px" @click="save2Submit">保存</a-button>
      <a-button style="margin-right: 8px" @click="closeDrawer">关闭</a-button>
    </template>
    <a-row style="height: 100%;" :gutter="[10,10]">
      <a-col :span="12" style="height: 100%;">
        <div style="height: 100%; display: flex; flex-direction: column;border:1px;"  class="gutter-box">
          <a-card 
            :bordered="true"
            :headStyle="{ padding: '0px 10px' }"
            :bodyStyle="{ height: 'calc(100% - 57px)', padding: '10px', overflow: 'hidden' }"
            style="height: 100%;"
          >
            <template #title>
              <vxe-form :data="formData">
                  <vxe-form-item title="文件列表" field="fileName" :item-render="{}">
                    <template #default="{ data }">
                      <vxe-input v-model="data.fileName" placeholder="请输入名称" clearable @keyup="handleSearch" style="width: 300px;"/>
                      <vxe-button mode="text" status="primary" @click="handleSearch()">搜索</vxe-button>
                    </template>
                  </vxe-form-item>
              </vxe-form>
            </template>
            <vxe-table
                :border="true"
                ref="tableRef"
                show-overflow
                :loading="loading"
                height="auto"
                :data="tableData"
                @checkbox-change="checkBoxChangeEvent" 
                @current-change="currentChangeEvent" 
                :row-config="{ isCurrent: true, isHover: true }"
                :columnConfig="{ resizable: true }"
                :scroll-y="{ enabled: true, gt: 50 }"
                :checkbox-config="{ labelField: 'name', highlight: true }"
                auto-resize
              >
                <vxe-column type="checkbox" width="70" />
                <vxe-column field="fileName" type="html" title="文件名称" />
                <vxe-column field="fileTp" type="html" title="类型" :filters="filtTpOptions" :filter-multiple="false" :formatter="formatterFileTp"/>
                <vxe-column field="id" title="" :visible="false" />
            </vxe-table>
          </a-card>
        </div>
      </a-col>
      <a-col :span="12" style="height:100%;">
        <div style="height: 100%; display: flex; flex-direction: column;"  class="gutter-box">
          <a-card 
            :bordered="true"
            :headStyle="{ padding: '0px 10px' }"
            :bodyStyle="{ height: 'calc(100% - 57px)', padding: '10px', overflow: 'auto' }"
            style="height: 30%;margin-bottom: 10px;"
          >
            <template #title>
              <p style="font-weight: bold; margin: 0;">当前文件</p>
            </template>
            <div style="padding: 5px;">
              <span style="word-break: break-all; line-height: 1.5;">
                {{ curSelectFile.fileName }}
              </span>
            </div>
          </a-card>
          <a-card 
            :bordered="true"
            :headStyle="{ padding: '0px 10px' }"
            :bodyStyle="{ height: 'calc(100% - 57px)', padding: '10px', overflow: 'auto'}"
            style="height: 70%;"
          >
            <template #title>
              <p style="font-weight: bold; margin: 0;">关联到文件</p>
            </template>
            <div style="padding: 5px;">
              <div style="margin-bottom: 8px; padding: 5px; background: #f5f5f5; border-radius: 4px;" 
                   v-for="(item,ind) in selectDatas" 
                   :key="ind">
                {{ (ind+1) }}.&nbsp;{{ item.fileName }}
              </div>
              <div v-if="selectDatas.length === 0" style="text-align: center; color: #999; padding: 20px;">
                暂无关联文件
              </div>
            </div>
          </a-card>
        </div>
      </a-col>
    </a-row>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue';
 import { VxeColumnPropTypes } from 'vxe-table'
  import { queryAllList,saveFileLink,findLinkFile } from '/@/views/doc/DocFiles.api';

  const emit = defineEmits(['selectFileDoc', 'closeDrawer']);
  const formData = reactive({
    fileName: '',
  });

  const tableData = ref([]);
  const listData = ref([]);
  const loading = ref(false)

  const tableRef = ref();
  const showDrawer = ref(false)
  const curSelectFile = ref<Recordable>({})


  const selectDatas = ref([]);

  async function iniData(file) {
    selectDatas.value = []
    curSelectFile.value = file
    showDrawer.value = true
    nextTick(async ()=>{
      loading.value = true;
      listData.value = tableData.value = await queryAllList({});
      loading.value = false;

      const selIdAry = await findLinkFile({sid:file.id});

      const $table = tableRef.value;
     
      for(let i=0;i<selIdAry.length;i++) {
        const tRow = tableData.value.find(item => item.id*1 == selIdAry[i]*1);
        if (tRow) {
          selectDatas.value.push(tRow)
          $table.toggleCheckboxRow(tRow)
        }
      }
      
    })
  
  }

  const handleSearch = () => {
    const filterFileName = String(formData.fileName).trim().toLowerCase();
    if (filterFileName) {
      const filterRE = new RegExp(filterFileName, 'gi');
      const searchProps = ['fileName', 'fileTp'];
      const rest = listData.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterFileName) > -1));
      tableData.value = rest.map((row) => {
        const item = Object.assign({}, row);
        searchProps.forEach((key) => {
          item[key] = String(item[key]).replace(filterRE, (match) => `<span class="keyword-lighten" style="color:red">${match}</span>`);
        });
        return item;
      });
    } else {
      tableData.value = listData.value;
    }
  };

  const checkBoxChangeEvent = () => {
    const $table = tableRef.value;
    selectDatas.value = $table?.getCheckboxRecords();
  }

  const currentChangeEvent = ({ row }) => {
    const $table = tableRef.value;
    $table.toggleCheckboxRow(row)
    checkBoxChangeEvent();
  };

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

  const save2Submit = async () => {
    const params = {}
    const ids = getSelectIds();
    params["tids"] = ids;
    params["sid"] = curSelectFile.value.id;
    await saveFileLink(params);
    closeDrawer();
  }

  const closeDrawer = async() => {
    showDrawer.value = false
  }

  const filtTpOptions = ref([
    { label: 'pdf', value: "pdf" },
    { label: 'docx', value: "docx" },
    { label: 'doc', value: "docx" }
  ])

  const formatterFileTp: VxeColumnPropTypes.Formatter<any> = ({ cellValue }) => {
    const item = filtTpOptions.value.find(item => item.value === cellValue)
    return item ? item.label : ''
  }


  defineExpose({
    iniData,
  });
</script>

<style lang="less" scoped>
.gutter-box {
  padding: 0;
  height: 100%;
}

// 确保抽屉内容区域高度正确
:deep(.ant-drawer-body) {
  padding: 16px;
  height: calc(100% - 55px);
}

// 调整表格容器高度
:deep(.vxe-table) {
  height: 100%;
}
</style>