<template>
  <div>
    <el-dialog
      v-model="projectDialog.visible.value"
      :title="projectDialog.title.value"
      width="80%"
      append-to-body
    >
      <el-card shadow="never" class="mb-2">
        <el-form
          ref="queryFormRef"
          :model="queryParams"
          :inline="true"
          label-width="90px"
        >
          <el-form-item label="项目编号" prop="projectCode">
            <el-input
              v-model="queryParams.projectCode"
              placeholder="请输入项目编号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="项目状态" prop="projectStatus">
            <el-select
              v-model="queryParams.projectStatus"
              placeholder="请选择项目状态"
              clearable
            >
              <el-option
                v-for="dict in project_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目类别" prop="projectCategory">
            <el-select
              v-model="queryParams.projectCategory"
              placeholder="请选择项目类别"
              clearable
            >
              <el-option
                v-for="dict in project_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="业务方向" prop="businessDirection">
            <el-select
              v-model="queryParams.businessDirection"
              placeholder="请选择业务方向"
              clearable
            >
              <el-option
                v-for="dict in business_direction"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card shadow="never">
        <el-table
          v-loading="loading"
          border
          :data="projectList"
          @selection-change="handleSelectionChange"
          @row-dblclick="handleRowDblClick"
        >
          <el-table-column
            v-if="multiple"
            type="selection"
            width="55"
            align="center"
          />
          <el-table-column
            label="项目编号"
            prop="projectCode"
            width="140"
            align="center"
          />
          <el-table-column
            label="项目名称"
            prop="projectName"
            min-width="180"
            align="center"
          />
          <el-table-column
            label="业务方向"
            prop="businessDirection"
            width="110"
            align="center"
          >
            <template #default="scope">
              <dict-tag
                :options="business_direction"
                :value="scope.row.businessDirection"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="项目类别"
            prop="projectCategory"
            width="120"
            align="center"
          >
            <template #default="scope">
              <dict-tag
                :options="project_category"
                :value="scope.row.projectCategory"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="项目经理"
            prop="managerId"
            width="120"
            align="center"
          >
            <template #default="scope">
              <span>{{ (scope.row as any).managerName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="部门负责人"
            prop="chargeId"
            width="120"
            align="center"
          >
            <template #default="scope">
              <span>{{ (scope.row as any).chargeName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="分管副总"
            prop="deputyId"
            width="120"
            align="center"
          >
            <template #default="scope">
              <span>{{ (scope.row as any).deputyName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="项目状态"
            prop="projectStatus"
            width="110"
            align="center"
          >
            <template #default="scope">
              <dict-tag
                :options="project_status"
                :value="scope.row.projectStatus"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="流程状态"
            prop="flowStatus"
            width="110"
            align="center"
          >
            <template #default="scope">
              <dict-tag
                :options="wf_business_status"
                :value="scope.row.flowStatus"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            prop="amount"
            width="120"
            align="center"
          />
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listProjectInfo } from '@/api/oa/erp/projectInfo'
import type {
  ProjectInfoVO,
  ProjectInfoQuery
} from '@/api/oa/erp/projectInfo/types'
import useDialog from '@/hooks/useDialog'

interface PropType {
  /** 当前已选项目（单选或多选） */
  modelValue?: ProjectInfoVO | ProjectInfoVO[] | undefined
  /** 是否多选，默认单选 */
  multiple?: boolean
}

const props = withDefaults(defineProps<PropType>(), {
  multiple: false,
  modelValue: undefined
})

const emit = defineEmits<{
  (e: 'update:modelValue', val: ProjectInfoVO | ProjectInfoVO[] | undefined): void
  (e: 'confirm', val: ProjectInfoVO | ProjectInfoVO[] | undefined): void
}>()

const { proxy } = getCurrentInstance() as any
const {
  business_direction,
  project_status,
  project_category,
  wf_business_status
} = toRefs<any>(
  proxy?.useDict('business_direction', 'project_status', 'project_category', 'wf_business_status')
)

const projectDialog = useDialog({
  title: '项目选择'
})

const loading = ref(false)
const total = ref(0)
const projectList = ref<ProjectInfoVO[]>([])
const selectedRows = ref<ProjectInfoVO[]>([])

const queryFormRef = ref<ElFormInstance>()

const queryParams = reactive<ProjectInfoQuery>({
  pageNum: 1,
  pageSize: 10,
  projectCode: undefined,
  projectName: undefined,
  businessDirection: undefined,
  projectCategory: undefined,
  projectStatus: undefined,
  flowStatus: undefined,
  activeFlag: '1',
  params: {}
})

const multiple = computed(() => props.multiple)

const initFromModelValue = () => {
  selectedRows.value = []
  if (!props.modelValue) return
  if (Array.isArray(props.modelValue)) {
    selectedRows.value = [...props.modelValue]
  } else {
    selectedRows.value = [props.modelValue]
  }
}

const getList = async () => {
  loading.value = true
  try {
    const res = await listProjectInfo(queryParams)
    projectList.value = res.rows || []
    total.value = res.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleSelectionChange = (selection: ProjectInfoVO[]) => {
  if (!multiple.value) {
    // 单选模式下 selection 只是辅助，真正选中通过双击
    selectedRows.value = selection.slice(0, 1)
  } else {
    selectedRows.value = selection
  }
}

const handleRowDblClick = (row: ProjectInfoVO) => {
  if (multiple.value) {
    return
  }
  selectedRows.value = [row]
  confirm()
}

const confirm = () => {
  const value: ProjectInfoVO | ProjectInfoVO[] | undefined = multiple.value
    ? selectedRows.value
    : selectedRows.value[0]
  emit('update:modelValue', value)
  emit('confirm', value)
  close()
}

const close = () => {
  projectDialog.closeDialog()
}

watch(
  () => projectDialog.visible.value,
  async (val) => {
    if (val) {
      initFromModelValue()
      await getList()
    } else {
      selectedRows.value = []
    }
  }
)

// 暴露给父组件使用：open / close
const open = () => {
  projectDialog.openDialog()
}

defineExpose({
  open,
  close
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
