<template>
  <BasicDrawer 
    v-bind="$attrs" 
    :title="pageTitle" 
    @close="closeDrawer" 
    @register="registerDrawer"  
    width="100%" 
    destroyOnClose
  >  
    <div class="drawer-content">
      <vxe-grid 
          ref="tableRef" 
          v-bind="gridOptions" 
          keep-source 
          :radio-config="{highlight:true}"  
          size="small"
          height="100%"
        >

        <template #mtrcCtp_default="{ row }">
            <span>
              {{ row.mtrcCtp==1?'基本指标':'计算指标' }}
            </span>
        </template>

        <template #toolbar_buttons>
          <vxe-button status="primary" @click="handleAddMtricClick">添加指标</vxe-button>
          <vxe-button status="error" @click="handleBatchDelete">批量删除</vxe-button>
          <vxe-input v-model="srhContent" type="search" placeholder="请输入" clearable @keyup.enter="handleSearch()" style="width: 35%; margin-left: 100px" />
          <a-button type="link" @click="handleSearch()">搜索</a-button>
          <a-button type="link" @click="handleRefresh()">刷新</a-button>
        </template>
        <template #operate="{ row }">
          <vxe-button  size="small" content="详情" @click="handleDetail(row)" />
          <vxe-button  size="small" content="删除" @click="handleDelete(row)" />
        </template>
      </vxe-grid>
      <vxe-modal
        resize
        destroy-on-close
        show-confirm-button
        show-cancel-button
        v-model="showWindow"
        title="外包风险管理-选择风险指标"
        width="85vw"
        height="95vh"
        :confirm-closable="false"
      >
        <MetricMonitorSetList @save="saveMetrics" ></MetricMonitorSetList>
      </vxe-modal>

      <MetricMonitorSetModal @register="registerMetricModal" @success="handleSuccess"></MetricMonitorSetModal>

    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from 'vue';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { alllist, deleteOne,batchDelete,saveBatch} from '../WbCheckItem.api';
import { VxeUI,VxeTableInstance, VxeGridProps } from 'vxe-table';
import MetricMonitorSetList  from './MetricMonitorSetList.vue';

import MetricMonitorSetModal  from '/@/views/metric/components/MetricMonitorSetModal.vue';  
import {useModal} from '/@/components/Modal';
import { defHttp } from '/@/utils/http/axios';


interface RowVO {
  id: number;
  auditName: string;
  name: string;
  method: string;
  des: string;
  mtrcIds?: string;
}

const tp=2
const pageTitle = ref("");
const wbCheck = ref<{ id: number; name: string }>();
const loading = ref(false);
const showWindow = ref(false);

const allData = ref<RowVO[]>([]);
const tableData = ref<RowVO[]>([]);

const srhContent = ref();
const tableRef = ref<VxeTableInstance>();

const emit = defineEmits(['rowChangeEvent']);


const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  height: "100%",
  columnConfig: {
    resizable: true
  },
  columns: [
    { type: 'checkbox', visible: true, width: '50', showOverflow: false }, 
    {
      field: 'mtrcCtp',
      title: '分类',
      width: '10%',
      sortable: true,
      slots: { default: 'mtrcCtp_default' }
    },
    {
      field: 'domainNo',
      title: '领域编码',
      editRender: { name: 'input' },
      type:"html",
      sortable: true,
      width: '30%',
      visible:false
    },
    {
      field: 'domainName',
      title: '领域名称',
      editRender: { name: 'input' },
      type:"html",
      sortable: true,
      width: '30%',
    },
    {
      field: 'tname',
      title: '指标名称',
      editRender: { name: 'input' },
      type:"html",
      sortable: true,
      width: '20%',
    },
    {
      field: 'mtrcDes',
      title: '说明',
      editRender: { name: 'input' },
      minWidth: '10%',
      type:"html",
      sortable: true
    },
    {
      field: 'createBy',
      title: '创建人',
      visible: false,
      minWidth: '10%',
    },
    {
      field: 'createTime',
      title: '创建时间',
      visible: false,
      minWidth: '10%',
    },
    {
      field: 'id',
      title: 'id',
      visible: false,
      minWidth: '10%',
    },
    {
      field: '指标ID',
      title: 'tid',
      visible: false,
      minWidth: '10%',
    },
    { 
      title: '操作', 
      align: 'center',
      width: '10%',
      visible: true,
      fixed: 'right', 
      slots: { default: 'operate' } 
    },
  ],
  toolbarConfig: {
    refresh: true,
    zoom: true,
    custom: true,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  data: []
});

const [registerDrawer] = useDrawerInner(async (data) => {
  wbCheck.value = data;
  pageTitle.value = `${data.name}-添加指标`;
  await Promise.all([
    iniData(),
    //setMetricDatas()
  ]);
});



const closeDrawer = () => {
  // Handle drawer close if needed
};

const iniData = async () => {
  loading.value = true;
  try {
    if (!wbCheck.value?.id) return;
    
    const checkId = wbCheck.value.id;
    const data = await alllist({ checkId:checkId,tp:tp });
    allData.value = data;
    tableData.value = data;
    gridOptions.data = data;
  } finally {
    loading.value = false;
  }
};


const handleSuccess = async () => {
  await iniData();
};



const handleDelete = async (row: RowVO) => {
  try {
    await deleteOne({id: row.id },handleSuccess);
  } catch (error) {
    VxeUI.modal.message({ content: '删除失败', status: 'error' });
  }
};

const handleBatchDelete = async () => {
  const ids = getSelectIds();
  if (ids.length === 0) {
    VxeUI.modal.message({ content: "请选择记录！", status: 'warning' });
    return;
  }
  try {
    batchDelete({ ids: ids.join(",") },handleSuccess);
  } catch (error) {
    VxeUI.modal.message({ content: '批量删除失败', status: 'error' });
  }
};

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


const saveMetrics = async (idAry) => {
  try {
    const params = idAry.map(id => ({
      tid: id,
      checkId: wbCheck.value.id,
      tp:tp
    }));

    await saveBatch(params);
    showWindow.value = false;
    await handleSuccess();
  } catch (error) {
    VxeUI.modal.message({ content: '保存失败', status: 'error' });
  }
};



const handleSearch = () => {
    let srhTxt =  srhContent.value
    const filterSrhTxt = String(srhTxt).trim().toLowerCase();
    if (filterSrhTxt) {
      const filterRE = new RegExp(filterSrhTxt, 'gi');
      const searchProps = ["tname","mtrcDes",'domainName'];
      let rest = allData.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterSrhTxt) > -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;
    }
  };

  const handleRefresh = async() => {
    srhContent.value = ""
    //gridOptions.data = allData.value;
    await iniData()
  }


  const handleAddMtricClick = async () => {
    showWindow.value = true;
  };




  const [registerMetricModal, {openModal}] = useModal();
   

  const handleDetail = async (record) => {
    const queryByIdUrl = '/metric/metricMonitorSet/queryById';
    let params = { id: record.tid };
    const data = await defHttp.get({ url: queryByIdUrl, params });
  
     openModal(true, {
       record:data,
       isUpdate: true,
       showFooter: false,
     });
   }

</script>

<style scoped>
.drawer-content {
  height: calc(100vh - 100px); 
  margin: 0; 
  background-color: #fff;
}
</style>