<template>
  <a-card style="width: 100%;height: 100%;padding:0px 20px"
    :tab-list="tabList"
    :bodyStyle="{height:'90%',padding:'0px'}"
    @tabChange="key => onTabChange(key)"
  >  
    <vxe-grid v-bind="gridOptions">
      <template #toolbarButtons>
        <vxe-button size="small" icon="vxe-icon-add" status="primary" @click="handleAdd()">添加</vxe-button>
        <span style="margin-left: 200px;width: 500px;display: inline;">
          <vxe-input v-model="srhForm.content" type="search" placeholder="全表搜索" clearable @keyup.enter="handleSearch()" style="width: 70%;margin: 0px" size="small"/>
          <a-button type="link" @click="handleSearch()">搜索</a-button>
          <a-button type="link" @click="refresh()">刷新</a-button>
        </span>
      </template>
      <template #toolbarTools>
        切换不同模板：
        <vxe-select v-model="srhForm.tplid" :options="tplDatas" clearable @change="handleSearchFromLib()" style="width: 150px;margin:0px 10PX"></vxe-select>
      </template>
      <template #action="{ row }">
        <vxe-button mode="text" status="primary" @click="handleEdit(row)">编辑</vxe-button>
        <vxe-button mode="text" status="primary" @click="handleDelete(row)">删除</vxe-button>
      </template>v-if=
    </vxe-grid>

  </a-card>

  <BaosongTplItemYear ref="refBaosongTplItemYear" @success="handleSuccess" v-if="actiiveKey=='4'" ></BaosongTplItemYear>
  <BaosongTplItem ref="refBaosongTplItem" @success="handleSuccess" v-else></BaosongTplItem>
  
</template>

<script lang="ts" setup>
import { ref,nextTick,reactive,onMounted,onBeforeUnmount,onBeforeMount } from 'vue'
import type { VxeGridProps, VxeColumnPropTypes } from 'vxe-table'
import { VxeUI, VxeFormInstance,VxeTreeSelectProps } from 'vxe-pc-ui'

import BaosongTplItemYear from './components/BaosongTplItemYear.vue'

import BaosongTplItem from './components/BaosongTplItem.vue'
import {queryAllList,deleteOne } from './BaosongDataValid.api';
import {allTplItems } from './BaosongTplItem.api';
import { allTpls } from './BaosongTpl.api'

const loading = ref(false)
const actiiveKey = ref('1');

const allData = ref([]);

const tplDatas = ref()
const srhForm = reactive({
  content:'',
  tplid:''
})

const refBaosongTplItem = ref()
const refBaosongTplItemYear = ref()

const selectRow = ref<any>()

const isVisible = ref(false)

 const drawerTitle= ref();
 const curTpl = ref()


const regionEditRender = reactive<VxeColumnPropTypes.EditRender<any, VxeTreeSelectProps>>({
  name: 'VxeTreeSelect',
  props: {
    multiple: true,
    clearable:true
  },
  options: [
  ]
})

const gridOptions = reactive<VxeGridProps<any>>({
  border: true,
  height: "auto",
  showOverflow: false,
  customConfig: {
    mode: 'drawer'
  },
  columnConfig:{
    resizable: true
  },
  rowConfig:{
    resizable: true
  },

  toolbarConfig: {
    custom: true,
    zoom: true,
    slots: {
      buttons: 'toolbarButtons',
      tools: 'toolbarTools'
    }
  },

  editConfig: {
    trigger: 'click',
    mode: 'cell'
  },

  columns: [
    { type: 'seq', width: 70 },
    // { field: 'code', title: '公式编号',width:"10%",rowResize: true,editRender: { name: 'input'  }},
    //  { field: 'name', title: '校验对象',width:"20%",rowResize: true,editRender: { name: 'input'  }},
    { field: 'params', title: '相关变量', width:"20%",rowResize: true ,visible:false},
    { field: 'des', title: '验证规则描述',type:"html", rowResize: true,editRender: { name: 'VxeTextarea'}
    ,cellRender:
     { name: 'VxeTextEllipsis',
        props: {
          lineClamp: 2
        }
      }
    },
    { field: 'formula', title: '验证公式',width:"30%",type:"html", rowResize: true,editRender: { name: 'input'} },
    { field: 'action', title: '操作', width: 110, slots: { default: 'action' },fixed:'right' }
  ],
  data: []
})


async function setIniData(Tpl) {
   drawerTitle.value="模板【"+Tpl.nm+"】"
   curTpl.value = Tpl
   isVisible.value = true
   regionEditRender.options = await  buildTree(Tpl)
   onTabChange("tab1")
 }


 async function buildTree(Tpl) {
  const data = await allTplItems({ tplid: Tpl.id });
  const map = {};
  const tree = [];
  data.forEach(item => {
    map[item.code] = {
      label: item.title,
      value: item.code,
      children: []
    };
  });
  data.forEach(item => {
    const node = map[item.code];
    if (!item.pcode || !map[item.pcode]) {
      tree.push(node);
    } else {
      map[item.pcode].children.push(node);
    }
  });

  return tree;
}

const onTabChange = async (value: string) => {
  actiiveKey.value = value
  await onSearch()
}

const onSearch = async () => {
  loading.value =true
  let params = {tp:actiiveKey.value,tplid:srhForm.tplid}
  gridOptions.data  = allData.value = await queryAllList(params);
  loading.value =false
}

const tabList = [
  {
    key: '1',tab: '校验关系-表内校验',
  },{
    key: '2',tab: '校验关系-表间校验',
  // },{
  //   key: '3',tab: '自动计算',
  // },{
  //   key: '4',tab: '往年报告-校验规则',
  },
];

const handleAdd = async () => {
  if(actiiveKey.value=='4') {
    refBaosongTplItemYear.value.setData(actiiveKey.value)
  } else {
    refBaosongTplItem.value.setData(actiiveKey.value)
  }

}

const handleEdit = (row) => {
  selectRow.value = row
  if(actiiveKey.value=='4') {
    refBaosongTplItemYear.value.setData(actiiveKey.value,row)
  } else {
    refBaosongTplItem.value.setData(actiiveKey.value,row)
  }
}

const handleDelete = async (row) => {
  await deleteOne(row,handleSuccess);
}

const handleSuccess = async () => {
  onSearch()
}

onMounted(async () => {
   srhForm.content = ""
  const allTplDatas = await allTpls({});
  tplDatas.value = allTplDatas.map(item => ({
      label: item.code,
      value: item.id,
    }));

    onSearch()
});


function handleSearchFromLib() {
  srhForm.content = ""
  onSearch();
}

function refresh() {
   srhForm.content = ""
   onSearch();
}


const handleSearch = () => {
  const filterVal = String(srhForm.content).trim().toLowerCase()
  if (filterVal) {
    const filterRE = new RegExp(filterVal, 'gi')
    const searchProps = ['des', 'formula']
    // 搜索为克隆数据，不会污染源数据
    const rest = allData.value.filter(item => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1))
    gridOptions.data = rest.map(row => {
      const item = Object.assign({}, row)
      searchProps.forEach(key => {
        item[key] = String(item[key]).replace(filterRE, match => `<span style='color:red'">${match}</span>`)
      })
      return item
    })
  } else {
    gridOptions.data = allData.value
  }
}
 
</script>

<style scoped>
.gutter-box {
  text-align: center;
  background:#FFF;
  height: 88vh;
}
</style>