<template>
  <div style="height: calc(90vh - 80px)">
    <vxe-grid v-bind="gridOptions" v-loading="loading"  class="mytable-scrollbar" 
     :style="{
        '--vxe-ui-table-border-color': borderColor,
        '--vxe-ui-table-border-width': borderWidth
      }">

      <template #toolbar_buttons>
        <a-space wrap style="margin-left: 10px;">
          <vxe-radio-group v-model="srcParms.tp" @change="handleSearch">
            <vxe-radio-button label=1 content="年报"></vxe-radio-button>
            <vxe-radio-button label=2 content="季报"></vxe-radio-button>
            <vxe-radio-button label=3 content="月报"></vxe-radio-button>
          </vxe-radio-group> 
          <vxe-select v-model="srcParms.taskid" placeholder="请选择报告" clearable style="width:230px" @change="handleSearch">
            <template v-for="(item,ind) in tasks" :key="ind">
              <vxe-option :value="item.id" :label="item.name"></vxe-option>
            </template>
          </vxe-select>

          <vxe-select v-model="srcParms.tplid" placeholder="请选择模板" clearable style="width:230px" @change="handleSearch">
            <template v-for="(item,ind) in tpls" :key="ind">
              <vxe-option :value="item.id" :label="item.code + '【' + item.nm +'】'"></vxe-option>
            </template>
          </vxe-select>

          <span>
            <vxe-input v-model="srhContent" type="search" placeholder="请输入" clearable @keyup.enter="handleAllSearch()" style="width:300px; margin-left: 100px" />
            <a-button type="link" @click="handleAllSearch()">搜索</a-button>
            <a-button type="link" @click="refresh()">刷新</a-button>
          </span>

        </a-space>
      </template>
      <template #empty>
        <div style="padding: 20px 0;">
          <a-empty :description="loading ? '数据加载中...' : '暂无数据'"/>
        </div>
      </template>
    </vxe-grid>
  </div>

</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { VxeTreeProps } from 'vxe-pc-ui'
import XEUtils from 'xe-utils'
import { findFilledlist } from './BaosongTaskRecord.api';
import { allTpls } from '../tpl/BaosongTpl.api';
import { queryAllTasks } from '../task/BaosongTask.api';
import type { VxeGridProps, VxeFormInstance } from 'vxe-table';

interface TableDataItem {
  id: string;
  treepathName: string;
  content: string;
  tplName: string;
  taskName: string;
  createBy?: string;
  createTime?: string;
}

interface SearchParams {
  treepathName?: string;
  content?: string;
  taskid?:string;
  tp?:string;
  tplid?:string;
}

const loading = ref(false);
const srcParms = ref<SearchParams>({tp:"1"});
const tableDatas = ref<TableDataItem[]>([]);

const iniDatas = ref<TableDataItem[]>([]);

const srhContent = ref();

const borderColor = ref('')
const borderWidth = ref('1px')

// 获取数据方法
const findData = async () => {
  try {
    loading.value = true;
    const response = await findFilledlist(srcParms.value);
    tableDatas.value = iniDatas.value = response || [];
  } catch (error) {
    console.error('获取数据失败:', error);
    tableDatas.value = [];
  } finally {
    loading.value = false;
  }
};

const handleSearch = async () => {
  try {
    await findData();
  } catch (error) {
    console.error('表单验证失败:', error);
    // 添加错误提示
    alert('请正确填写搜索条件');
  }
};

// 重置方法
const handleReset = (event: { $form: VxeFormInstance }) => {
  event.$form.reset();
  srcParms.value = {};
  findData();
};

const gridOptions = reactive<VxeGridProps>({
  showOverflow: true,
  border: true,
  height: 'auto',
  loading: false,
  rowConfig: {
    keyField: 'id',
    isHover: true
  },
  columnConfig: {
    resizable: true
  },
  scrollbarConfig: {
    width: 16,
    height: 32
  },
  toolbarConfig: {
    refresh: true,
    zoom: true,
    custom: true,
    export: false,
    print: false,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  columns: [
    { type: 'seq', width: 70, fixed: 'left' },
    { field: 'treepathName', title: '填报项目', minWidth: 150,type:'html' },
    { field: 'content', title: '填报值', width: 150 ,type:'html'},
    { field: 'tplName', title: '模板名称', width: 200,type:'html'},
    { field: 'taskName', title: '报告名称', width: 200 ,type:'html'},
    { field: 'createBy', title: '填报人', visible: false, width: 150 ,type:'html'},
    { field: 'createTime', title: '填报时间', visible: false, width: 180 ,type:'html'}
  ],
  data: tableDatas
});

const tpls = ref([]);
const setTpls = async () => {
  tpls.value = await allTpls({});
};

const tasks = ref([]);
const setTasks = async () => {
  tasks.value = await queryAllTasks({});
};


const handleAllSearch = () => {
   
    if (srhContent.value) {
      const filterSrhTxt = String(srhContent.value).trim().toLowerCase();
      const filterRE = new RegExp(filterSrhTxt, 'gi');
      const searchProps = ["treepathName","content","createTime","createBy"];
      let rest = iniDatas.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterSrhTxt) > -1));
      tableDatas.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 {
      tableDatas.value = iniDatas.value;
    }
  };

  const refresh = () => {
    srhContent.value = ""
    tableDatas.value = iniDatas.value;
  }
  
setTpls();
setTasks();
findData();
</script>

<style scoped lang="scss">

.vxe-grid {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.mytable-scrollbar {
  ::-webkit-scrollbar {
    width: 16px;
    height: 32px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 4px;
  }
}


</style>