<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="80%"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            v-model="queryParams.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="物料编号" prop="materialCode">
          <el-input
            v-model="queryParams.materialCode"
            placeholder="请输入物料编号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </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-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column
          v-if="multiple"
          type="selection"
          width="55"
        />
        <el-table-column label="物料名称" align="center" prop="materialName"/>
        <el-table-column label="物料编号" align="center" prop="materialCode"/>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180"
        />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { dateFormatter } from '@/utils/formatTime'
import { QualityMaterialApi, QualityMaterialVO } from '@/api/contract/qualitymaterial'
const message = useMessage() // 消息弹窗
const props = defineProps({
  modelValue: { // 控制显示隐藏
    type: Boolean,
    default: false
  },
  title: { // 弹窗标题
    type: String,
    default: '选择物料'
  },
  multiple: { // 是否多选
    type: Boolean,
    default: false
  },
  selected: { // 已选中的值
    type: Array as () => QualityMaterialVO[],
    default: () => []
  },
  defaultQueryParams: { // 默认查询参数
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = ref(false)
const loading = ref(true)
const list = ref<QualityMaterialVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  materialName: undefined,
  materialCode: undefined,
  ...props.defaultQueryParams
})
const queryFormRef = ref()
const selectedRows = ref<QualityMaterialVO[]>([])

// 监听visible变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    selectedRows.value = [...props.selected]
    getList()
  }
})

// 监听visible变化同步到父组件
watch(visible, (val) => {
  emit('update:modelValue', val)
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await QualityMaterialApi.getQualityMaterialPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  Object.assign(queryParams, {
    pageNo: 1,
    pageSize: 10,
    materialName: undefined,
    materialCode: undefined,
    ...props.defaultQueryParams
  })
  handleQuery()
}

/** 行选择变化 */
const handleSelectionChange = (rows: QualityMaterialVO[]) => {
  if (!props.multiple && rows.length > 1) {
    selectedRows.value = [rows[rows.length - 1]]
  } else {
    selectedRows.value = rows
  }
}

/** 行点击事件 */
const handleRowClick = (row: QualityMaterial) => {
  if (props.multiple) {
    const index = selectedRows.value.findIndex(item => item.id === row.id)
    if (index >= 0) {
      selectedRows.value.splice(index, 1)
    } else {
      selectedRows.value.push(row)
    }
  } else {
    selectedRows.value = [row]
  }
}

/** 弹窗关闭后回调 */
const handleClosed = () => {
  selectedRows.value = []
}

/** 确认选择 */
const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请至少选择一条数据')
    return
  }
  emit('confirm', props.multiple ? selectedRows.value : selectedRows.value[0])
  visible.value = false
}

// 暴露方法供外部调用
defineExpose({
  refresh: getList,
  setQueryParams: (params: Object) => {
    Object.assign(queryParams, params)
    getList()
  }
})
</script>
