<template>
  <div style="height: 80vh;margin: 5px;">
    <vxe-grid  
        v-bind="baseGridOptions" 
        ref="gridRef" 
        @checkbox-change="handleShowDrawer" 
        style="height: 100%;"
      >
      <template #toolbarButtons>
         指标列表
      </template>
    </vxe-grid>
  </div>
</template>

<script lang="ts" setup>
import { ref,reactive,onMounted } from 'vue'
import { defHttp } from '/@/utils/http/axios';
import type { VxeGridPropTypes,VxeGridProps } from 'vxe-table'

const emit = defineEmits(['callback','success']);

const refFormulaDrawer = ref();
const gridRef = ref()

const mtrcCtpOptions = ref([
  { label: '原子指标', value: 1 },
  { label: '初级指标', value: 2},
  { label: '高阶指标', value: 3},
]);

const baseGridOptions = reactive<VxeGridProps<any>>({
  border: true,
  height:"auto",
  columnConfig: {
    resizable: true
  },
  columns: [
    { type: 'seq', width: "5%" },
    { type: 'checkbox', width: "5%" },
    { field: 'mtrcName', title: '名称'},
    { field: 'mtrcNo', title: '编码' ,width:"25%",},
    { field: 'mtrcCtp', title: '类型' ,width:"10%", 
      formatter ({ cellValue }) {
        const item = mtrcCtpOptions.value.find(item => item.value === cellValue)
        return item ? item.label : cellValue
      }
    },
    { field: 'unit', title: '单位' ,width:"10%" },
    // { field: 'des', title: '说明'},
  ],
  editConfig: {
    trigger: 'dblclick',
    mode: 'row'
  },
  toolbarConfig: {
    zoom: false,
    slots: {
      buttons: 'toolbarButtons',
      tools:"toolsButtons"
    },
  },
 
  data: []
})


const setBaseMetric= async (params) =>{
  const queryAll = '/metric/metricMonitorSet/queryAllMetricNoPage'
  const list =  await defHttp.get({url: queryAll, params})
  baseGridOptions.data = list
}

const handleShowDrawer = async() => {
  const selDatas = await getSelectDatas()
  //refFormulaDrawer.value.iniData(selDatas);
  emit("callback",selDatas)
}


async function getSelectDatas() {
  const $table = gridRef.value;
  const selRecords = $table?.getCheckboxRecords();
  return selRecords;
}

const findObjectsByMtrcNo = (datas, mtrcNoArray, mtrcNoKey = 'mtrcNo') => {
  if (!Array.isArray(datas) || !Array.isArray(mtrcNoArray)) {
    console.warn('参数必须是数组');
    return [];
  }

  return datas.filter(item => 
    item && 
    typeof item === 'object' && 
    mtrcNoArray.includes(item[mtrcNoKey])
  );
};



const iniData = async (codes) => {
  if(!codes) {
    await setBaseMetric({})
  } else {
    const codeAry = codes.split(",")
    await setBaseMetric({mtrcCtp:2})
  }
 
  const datas = await findObjectsByMtrcNo( baseGridOptions.data,codeAry)
  emit("callback",datas)
}

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