<script setup lang="ts">
import {
  Storehouse_Product_List,
  Storehouse_ProductClass_List,
  Storehouse_Product_Model_List,
  Storehouse_Product_Name_List
} from '@/api/storehouse/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'

type Fn = () => void

let total = 0
const autoSelect = ref('')
const selectTable = ref()
let timeout: NodeJS.Timeout
const globalStore = GlobalStore()
const classOptions = ref<any[]>([])
const modelOptions = ref<any[]>([])
const tableProductData = ref<any[]>([])
const drawerProductRef = ref<InstanceType<typeof Drawer> | null>(null)

const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_model: '',
  T_class: '',
  page: 0,
  page_z: 20
})
const callbackProductDrawer = (done: Fn) => done()
const querySearchAsync = async (queryString: string, cb: (arg: any) => void) => {
  clearTimeout(timeout)
  globalStore.SET_isloading(true)
  timeout = setTimeout(async () => {
    const results = await getNameAsync(queryString)
    cb(results)
    globalStore.SET_isloading(false)
  }, 2000)
}

const getProductModelList = async () => {
  globalStore.SET_isloading(true)
  const res: any = await Storehouse_Product_Model_List({ T_name: autoSelect.value })
  modelOptions.value = res.Data.map((item: any, index: number) => {
    return {
      value: item,
      index: index
    }
  })
  globalStore.SET_isloading(false)
}
const handleSelect = (item: any) => {
  initParam.T_name = item.value
  getProductModelList()
}
// 搜索模型
const searchModelHandle = () => {
  total = 0
  initParam.page = 1
  tableProductData.value = []
  getProductList()
}

// 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
const getRowKey = (row: any) => {
  return row.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 ProductSelectionAllChange = (selection: any[]) => emit('ontableDataAll', selection)

const getNameAsync = async (str: string): Promise<any> => {
  const res: any = await Storehouse_Product_Name_List({ T_name: str, T_class: initParam.T_class })
  if (!res.Data) return
  return res.Data.map((item: any, index: number) => {
    return {
      value: item,
      index: index
    }
  })
}

const getProductList = async () => {
  const res: any = await Storehouse_Product_List({ ...initParam, T_name: autoSelect.value })
  tableProductData.value.push(...res.Data.Data)
  total = res.Data.Num
}

// 获取产品分类
const getProductClassList = async () => {
  const res: any = await Storehouse_ProductClass_List({ page: 1, page_z: 999 })
  classOptions.value = res.Data.Data
}

onMounted(() => {
  !classOptions.value.length && getProductClassList()
})

const productColumns = [
  { type: 'selection', width: 80 },
  { prop: 'T_img', label: '产品图片', name: 'T_img' },
  { prop: 'T_name', 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 = () => selectTable.value?.clearSelection()
const selectTableChange = (row: any) => {
  nextTick(() => {
    selectTable.value?.toggleRowSelection(row, false)
  })
}
const emit = defineEmits<{ (event: 'ontableData', value: any): void; (event: 'ontableDataAll', value: any[]): void }>()

defineExpose({
  openDrawer,
  clearSelection,
  selectTableChange
})
</script>

<template>
  <Drawer ref="drawerProductRef" :handleClose="callbackProductDrawer" size="70%">
    <template #header="{ params }">
      <h4 :id="params.titleId" :class="params.titleClass">选择产品</h4>
    </template>
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
            <el-col :xl="5" :lg="8" :md="10" class="d-flex">
              <span class="inline-flex items-center">产品分类：</span>
              <el-select v-model="initParam.T_class" clearable placeholder="请选择分类~">
                <el-option v-for="item in classOptions" :key="item.Id" :label="item.T_name" :value="item.Id" />
              </el-select>
            </el-col>
            <el-col :xl="7" :lg="8" :md="10" class="d-flex">
              <span class="inline-flex items-center">产品名称：</span>
              <el-autocomplete
                v-model="autoSelect"
                clearable
                :fetch-suggestions="querySearchAsync"
                placeholder="按产品名称搜索"
                :debounce="2000"
                :trigger-on-focus="false"
                @select="handleSelect"
              />
            </el-col>
            <el-col :xl="7" :lg="8" :md="12" class="d-flex">
              <span class="inline-flex items-center">产品型号：</span>
              <el-select v-model="initParam.T_model" clearable placeholder="请选择型号~">
                <el-option v-for="item in modelOptions" :key="item.index" :label="item.value" :value="item.value" />
              </el-select>
              <el-button type="primary" @click="searchModelHandle">搜索</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
      <el-table
        ref="selectTable"
        :row-key="getRowKey"
        :data="tableProductData"
        style="width: 100%; height: 99%"
        :header-cell-style="{
          background: '#dedfe0',
          height: '50px'
        }"
        v-el-table-infinite-scroll="load"
        @select="ProductselectionChange"
        @select-all="ProductSelectionAllChange"
      >
        <template v-for="item in productColumns" :key="item">
          <el-table-column v-if="item.type === 'index' || item.type === 'selection'" align="center" v-bind="item" />
          <el-table-column v-if="!item.ellipsis && 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>
              <el-image v-if="item.prop === 'T_img'" style="height: 50px" :src="row.T_img" fit="cover" />
            </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>
