<template>
  <vxe-drawer
    show-footer
    show-confirm-button
    show-cancel-button
    v-model="showLinkDrawer"
    title="条目关联"
    width="70%"
    :loading="loading"
    @confirm="save2Submit"
    
  >
    <a-row style="height: 100%;background-color: lightgray;">
      <a-col :span="12" style="height: 100%;">
          <div  class="gutter-box">
            <vxe-toolbar>
              <template #buttons>
                <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;"/>
                    </template>
                  </vxe-form-item>
                </vxe-form>
                <vxe-button  mode="text" status="primary" @click="handleSearch()">搜索</vxe-button>
                <vxe-button  mode="text" status="primary" @click="handleReset()">重置</vxe-button>
              </template>
            </vxe-toolbar>
          <vxe-table
              ref="tableRef"
              show-overflow
              :loading="loading"
              height="86%"
              :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 }"
            >
              <vxe-column type="checkbox" width="70" />
              <vxe-column field="item" type="html" title="条目" />
              <vxe-column field="fileName" type="html" title="文件名称" />
              <vxe-column field="fileTp" type="html" title="类型" />
              <vxe-column field="id" title="" :visible="false" />
          </vxe-table>
        </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% - 80px)', overflow: 'auto' }"
            style="height: 30%;margin-bottom: 6px;"
          >
            <template #title>
              <p style="font-weight: bold;">当前条目</p>
            </template>
            <div style="margin: 3px;">
             文件名称：<span v-html="curSelectFile.fileName"></span> 
            </div>
            <div style="margin: 3px;">
             当前条目： <span v-html="curSelectItem.item"></span>
            </div>
          </a-card>
          <a-card 
            :bordered="true"
            :headStyle="{ padding: '5px 10px' }"
            :bodyStyle="{ height: 'calc(100% - 90px)', overflow: 'auto'}"
            style="height: 70%;"
          >
            <template #title>
              <p style="font-weight: bold;">关联条目</p>
            </template>

            <div style="margin-bottom:5px;" v-for="(item,ind) in selectDatas" :key="ind">
              {{ (ind+1) }}.&nbsp;
              文件名称：<span v-html="item.fileName"></span><br>
              &nbsp;&nbsp;&nbsp;&nbsp;条目：<span v-html="item.item"></span>
            </div>

          </a-card>
        </div>
      </a-col>
    </a-row>
  </vxe-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue';
 
  import { saveFileLink,findLinkFile } from './api/AuditItemLink.api';

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

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

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

  const selectDatas = ref([]);

  async function iniData(item,file,dataList) {
    selectDatas.value = []
    curSelectItem.value = item
    curSelectFile.value = file
    showLinkDrawer.value = true

    loading.value = true;
    listData.value = tableData.value = dataList;
    loading.value = false;
    const selIdAry = await findLinkFile({sid:item.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);
      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','item'];
      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;
    }
  };

  

  async function handleReset() {
    formData.fileName = ""
    tableData.value = listData.value;
    const $table = tableRef.value;
    $table.clearCheckboxRow()
    selectDatas.value = []
  }

  async function handleSubmit() {
    const $table = tableRef.value;
    const selRecords = $table.getRadioRecord();
    emit('selectFileDoc', selRecords);
  }

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

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

  const closeDrawer = () => {
    showLinkDrawer.value = false
  }

  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"] = curSelectItem.value.id;
    await saveFileLink(params);
  }

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

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

