<script setup lang="ts">
import {
  Verifyltem_List
} from '@/api/mypercentage/index'
import { ElMessage } from 'element-plus'
import { GlobalStore } from '@/stores/index'
import Drawer from '@/components/Drawer/index.vue'
import { ref, reactive, onMounted, nextTick } from 'vue'
import { default as vElTableInfiniteScroll } from 'el-table-infinite-scroll'
import ImageCom from '@/components/Image/index.vue'

let total = 0
const selectTable = ref()
const globalStore = GlobalStore()
const tableProductData = ref<any[]>([])
const drawerProductRef = ref<InstanceType<typeof Drawer> | null>(null)

const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  page: 1,
  page_z: 20,
  T_type: 1
})
const callbackProductDrawer = (done: () => void) => done()
// 搜索模型
const searchModelHandle = () => {
  total = 0
  initParam.page = 1
  tableProductData.value = []
  getProductList()
}

// 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
const getRowKey = (row: any) => {
  return row.T_id
}

// 加载第二个抽屉数据
const load = () => {
  if (initParam.page && total === tableProductData.value.length) {
    ElMessage.warning('没有更多数据了！！')
    return
  }
  initParam.page++
  getProductList()
}
// 勾选产品
const ProductselectionChange = (selection: any[], row: any) => emit('ontableData', row)



//函数
const selectFun = async (val: any) => {
  // console.log('选中1111', val,selectTable.value,selectProductData.value)
  if (val?.length) {//已经选中的传值项
    // 设置产品的选中
    tableProductData.value.forEach((row: any) => {
      const matchedIndex = val?.findIndex((item: any) => item.T_id == row.T_id)
      selectTable.value?.toggleRowSelection(row, matchedIndex != -1)
    })
  }
}
const ProductSelectionAllChange = (selection: any[]) => emit('ontableDataAll', selection)
// 获取产品的列表
const getProductList = async () => {
  const res: any = await Verifyltem_List(initParam)
  let arr = [...res.Data.Data]
  arr.forEach((item:any)=>{
    item.T_id = item.Id
  })
  tableProductData.value.push(...arr)
  total = res.Data.Num
  console.log('设置选中',selectProductData.value,tableProductData.value)
  if (selectProductData.value?.length) {//已经选中的传值项
    // 设置产品的选中
    tableProductData.value.forEach((row: any) => {
      const matchedIndex = selectProductData.value?.findIndex((item: any) => item.T_id == row.T_id)
      selectTable.value?.toggleRowSelection(row, matchedIndex != -1)
    })
  }
}

const productColumns = [
  { type: 'selection', width: 80 },
  // { prop: 'T_img', label: '产品图片', name: 'T_img' },
  { prop: 'T_name', label: '验证项目' },
  { prop: 'T_price', label: '单价（元）' },
  
  // { prop: 'T_class_name', label: '产品分类' },
  // { prop: 'T_model', label: '产品型号', ellipsis: true },
  // { prop: 'T_spec', label: '产品规格' },
  // { prop: 'T_relation_sn', label: '关联SN', name: 'T_relation_sn' },
  // { prop: 'T_remark', label: '备注', ellipsis: true }
]

const openDrawer = () => drawerProductRef.value?.openDrawer()
const clearSelection = () => {
  initParam.page = 1
  tableProductData.value = []
  selectTable.value?.clearSelection()
}
const selectTableChange = (row: any) => {
  nextTick(() => {
    console.log('删除取消选中',row)
    selectTable.value?.toggleRowSelection(row, false)
  })
}

// props
const props = defineProps<{ selectProductData?: any[]}>()
const selectProductData = ref(props.selectProductData)

const emit = defineEmits<{ (event: 'ontableData', value: any): void; (event: 'ontableDataAll', value: any[]): void }>()

interface User {
  T_id: number
  T_name: string
  T_num: number
  count: number
}

const toggleSelectionFun = (rows?: User[]) => {
  // console.log('selectTable.value',selectTable.value,rows)
  if (rows) {
    rows.forEach((row) => {
      selectTable.value!.toggleRowSelection(row, undefined)
    })
  }
}

defineExpose({
  openDrawer,
  clearSelection,
  selectTableChange,
  searchModelHandle,
  getProductList,
  initParam,
  tableProductData,
  selectTable,
  toggleSelectionFun,
  selectFun
})

</script>

<template>
  <Drawer ref="drawerProductRef" :handleClose="callbackProductDrawer">
    <template #header="{ params }">
      <h4 :id="params.titleId" :class="params.titleClass">选择</h4>
    </template>
    <el-card class="box-card" shadow="never">
      <el-table @selection-change="selectFun" ref="selectTable" :row-key="getRowKey" :expand-row-keys="[0]"
        :data="tableProductData" style="width: 100%; height: 99%" :header-cell-style="{
          background: '#dedfe0',
          height: '50px'
        }" v-el-table-infinite-scroll="load" :infinite-scroll-immediate="false" infinite-scroll-distance="'50px'"
        @select="ProductselectionChange" @select-all="ProductSelectionAllChange">
        <template v-for="item in productColumns" :key="item">
          <el-table-column show-overflow-tooltip v-if="item.type === 'index' || item.type === 'selection'" align="center" v-bind="item" />
          <el-table-column show-overflow-tooltip v-if="item.prop" v-bind="item">
            <template #default="{ row }">
              <span v-if="item.prop === 'T_relation_sn'">
                <el-tag v-if="row.T_relation_sn === 1" effect="dark">是</el-tag>
                <el-tag v-else type="success" effect="dark">否</el-tag>
              </span>
              <ImageCom v-if="item.prop === 'T_img'" :src="row.T_img" />
            </template>
          </el-table-column>
          <!-- <el-table-column v-if="item.ellipsis && item.prop === 'T_model'" align="center" v-bind="item">
            <template #default="{ row }">
              <el-tooltip effect="dark" :content="row.T_model" placement="bottom">
                {{ row.T_model }}
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column v-if="item.ellipsis && item.prop === 'T_remark'" align="center" v-bind="item">
            <template #default="{ row }">
              <el-tooltip effect="customized" placement="left">
                <template #content>
                  <div class="tooltip-content">{{ row.T_remark }}</div>
                </template>
                {{ row.T_remark }}
              </el-tooltip>
            </template>
          </el-table-column> -->
        </template>
      </el-table>
    </el-card>
  </Drawer>
</template>

<style scoped lang="scss">
.tooltip-content {
  max-width: 500px;
  overflow-y: auto;
}

.box-card {
  height: 100%;

  :deep(.el-card__body) {
    height: calc(100% - 70px);
  }

  .sn-header {
    display: flex;
    justify-content: end;
  }

  .input-suffix {
    width: 100%;

    .inline-flex {
      white-space: nowrap;
    }

    .d-flex {
      display: flex;
    }
  }
}
</style>
