
<template>
  <el-dialog v-model="dialogTableVisible" title="选择产品" width="800">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="品种名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入品种名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="包装信息" prop="packageName">
          <el-input
            v-model="queryParams.packageName"
            placeholder="请输入包装信息"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input
            v-model="queryParams.specification"
            placeholder="请输入规格"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button @click="sendToParent" type="success" plain> 确认</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table  :reserve-selection="true" ref="tableRef" v-loading="loading"  row-key="id" :data="list" :stripe="true" :show-overflow-tooltip="true"  @selection-change="handleSelectionChange">
        <el-table-column type="selection"  width="55" />
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="品种名称" align="center" prop="productName" />
        <el-table-column label="包装信息" align="center" prop="packageName" />
        <el-table-column label="规格" align="center" prop="specification" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

  </el-dialog>

</template>
<script setup lang="ts">

import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import {ProductApi, ProductVO} from '@/api/visit/product'
import {defineEmits} from 'vue';

const dialogTableVisible = ref(false)
/** 产品 列表 */
defineOptions({ name: 'Product' })

//接受参数ids
const props = defineProps({
  ids: {
    type: String,
    required: false,
    default: () => ''
  }
})
const tableRef = ref();//表单
// 定义事件名和参数类型（可选）
const emit = defineEmits<{
  (e: 'updateProduct', ids: string,  names: string): void;
}>();

const sendToParent = () => {
  const joinedIds = multipleSelection.value.join(','); // ✅ 转为 "101,203,305"
  const joinedNames = multipleSelectionName.value.join(','); // ✅ 转为 "阿莫西林，银翘片"
  emit('updateProduct', joinedIds,joinedNames);              // ✅ 传 string 给父组件
  dialogTableVisible.value = false;              // ✅ 关闭弹窗
};

const loading = ref(true) // 列表的加载中
const list = ref<ProductVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productName: undefined,
  packageName: undefined,
  specification: undefined,
  status: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const multipleSelection = ref<any[]>([])  //存储多选内容
const multipleSelectionName = ref<any[]>([])  //存储多选内容
// 打开弹窗
const open = () => {
  dialogTableVisible.value = true
  //先清除勾选，再重新匹配勾选的反显
  tableRef.value?.clearSelection();
  if (props.ids && props.ids.trim() !== '') {
    multipleSelection.value = props.ids.split(',').map(item => Number(item)) //将父组件传递过来的ids转为数组
  }
  getList().then(() => {
    toggleDefaultSelection();
  });
}
/** 多选操作**/
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map(item=>item.id)
  multipleSelectionName.value = val.map(item=>item.productName)
  console.log(val)
  console.log("=========")
  console.log(multipleSelectionName)
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductApi.getProductPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 回显已选择 */
const toggleDefaultSelection = () => {
  nextTick(() => {
    multipleSelection.value.forEach(id => {
      const row = list.value.find(item => item.id === id);
      if (row) {
        tableRef.value?.toggleRowSelection(row, true);
      }
    });
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 初始化 **/
onMounted(() => {

})
// 暴露函数
defineExpose({ open });
</script>


<style scoped lang="scss">

</style>
