<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="68px"
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="项目编号" prop="projectCode">
          <el-input
            v-model="queryParams.projectCode"
            placeholder="请输入项目编号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </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-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="projectName" />
        <el-table-column label="项目编号" align="center" prop="projectCode" />
        <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>

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

    <!-- 表单弹窗：添加/修改 -->
    <ProjectForm ref="formRef" @success="getList" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { dateFormatter } from '@/utils/formatTime'
import { ProjectApi, ProjectVO } from '@/api/contract/project'
import ProjectForm from './ProjectForm.vue'
import { useMessage } from '@/hooks/web/useMessage'
const message = useMessage()
const props = defineProps({
  modelValue: { // 控制显示隐藏
    type: Boolean,
    default: false
  },
  title: { // 弹窗标题
    type: String,
    default: '选择项目'
  },
  multiple: { // 是否多选
    type: Boolean,
    default: false
  },
  selected: { // 已选中的值
    type: Array as () => ProjectVO[],
    default: () => []
  }
})

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

const visible = ref(false)
const loading = ref(true)
const list = ref<ProjectVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  projectName: undefined,
  projectCode: undefined,
  createTime: []
})
const queryFormRef = ref()
const selectedRows = ref<ProjectVO[]>([])
const formRef = ref()

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

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

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProjectApi.getProjectPage(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,
    projectName: undefined,
    projectCode: undefined,
    createTime: []
  })
  handleQuery()
}

/** 行选择变化 */
const handleSelectionChange = (rows: ProjectVO[]) => {
  if (!props.multiple && rows.length > 1) {
    // 如果是单选模式且选择了多行，则只保留最后选择的那个
    selectedRows.value = [rows[rows.length - 1]]
  } else {
    selectedRows.value = rows
  }
}

/** 行点击事件 */
const handleRowClick = (row: ProjectVO) => {
  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 openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProjectApi.deleteProject(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 弹窗关闭后回调 */
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: Partial<typeof queryParams>) => {
    Object.assign(queryParams, params)
    getList()
  }
})
</script>
