<script setup lang="ts">
import {
  Storehouse_Stock_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 loading = ref(false)
const autoSelect = ref('')
const selectTable = ref()
const globalStore = GlobalStore()
const classOptions = ref<any[]>([])
const modelOptions = ref<any[]>([])
const NameOptions = ref<any[]>([])
const tableProductData = ref<any[]>([])
const drawerProductRef = ref<InstanceType<typeof Drawer> | null>(null)

const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_product_name: '',
  T_product_model: '',
  T_product_class: '',
  page: 0,
  page_z: 20
})
const callbackProductDrawer = (done: Fn) => done()
const querySearchAsync = async (queryString: string) => {
  if (queryString) {
    loading.value = true
    globalStore.SET_isloading(true)
    const results = await getNameAsync(queryString)
    NameOptions.value = results
    globalStore.SET_isloading(false)
    loading.value = false
  }
}

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_product_name = item
  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_product_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_Stock_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_product_img', label: '产品图片', name: 'T_product_img' },
  { prop: 'T_product_name', label: '产品名称' },
  { prop: 'T_product_class_name', label: '产品分类' },
  { prop: 'T_product_model', label: '产品型号', ellipsis: true },
  { prop: 'T_product_spec', label: '产品规格' },
  { prop: 'T_product_relation_sn', label: '关联SN', name: 'T_product_relation_sn' }
]

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_product_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-select
                v-model="autoSelect"
                filterable
                remote
                reserve-keyword
                placeholder="按产品名称搜索"
                remote-show-suffix
                :remote-method="querySearchAsync"
                :loading="loading"
                @change="handleSelect"
              >
                <el-option v-for="item in NameOptions" :key="item.value" :label="item.value" :value="item.value" />
              </el-select>
            </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_product_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" align="center">
            <template #default="{ row }">
              <span v-if="item.prop === 'T_product_relation_sn'">
                <el-tag v-if="row.T_product_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_product_img'"
                fit="cover"
                style="width: 50px; height: 50px"
                :src="row.T_product_img"
                :preview-src-list="[row.T_product_img]"
                :preview-teleported="true"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </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;
    }
  }
}
.image-slot .el-icon {
  font-size: 30px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
</style>
