<template>
  <el-drawer v-model="visible" :title="title" :size="'50%'" :before-close="handleClose" destroy-on-close :close-on-click-modal="true">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="项目编号" prop="projectNo">
        <el-input v-model="form.projectNo" placeholder="请输入项目编号" />
      </el-form-item>
      <el-form-item label="项目logo" prop="projectLogo">
        <div class="logo-upload" @click="showFileSelector = true">
          <img v-if="form.projectLogo" :src="form.projectLogo" alt="项目logo" class="logo-image" />
          <div v-else class="logo-placeholder">
            <el-icon :size="40"><Plus /></el-icon>
            <span>点击上传</span>
          </div>
        </div>
        <FileSelector v-model="showFileSelector" :allowed-types="[1]" @confirm="handleFileConfirm" />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="form.projectName" placeholder="请输入项目名称" />
      </el-form-item>
      <el-form-item label="负责人" prop="leaderId">
        <el-select v-model="form.leaderId" placeholder="请选择负责人" filterable @change="handleLeaderChange">
          <el-option v-for="staff in staffList" :key="staff.staffId" :label="staff.staffName" :value="staff.staffId" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { ProjectInfoForm } from '@/api/project/projectInfo/types';
import { addProjectInfo, updateProjectInfo } from '@/api/project/projectInfo';
import FileSelector from '@/components/FileSelector/index.vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { listComStaff } from '@/api/company/comStaff';
import { ComStaffVO } from '@/api/company/comStaff/types';

interface Props {
  modelValue: boolean;
  title?: string;
  formData?: ProjectInfoForm;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'success'): void;
}

const props = withDefaults(defineProps<Props>(), {
  title: '添加项目信息'
});

const emit = defineEmits<Emits>();

const formRef = ref();
const buttonLoading = ref(false);
const visible = ref(false);
const showFileSelector = ref(false);
const staffList = ref<ComStaffVO[]>([]);

const initFormData: ProjectInfoForm = {
  id: undefined,
  projectNo: undefined,
  projectLogo: undefined,
  projectName: undefined,
  projectType: undefined,
  leaderId: undefined,
  leaderName: undefined,
  status: undefined,
  remark: undefined
};

const form = ref<ProjectInfoForm>({ ...initFormData });

const rules = {};

watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val && props.formData) {
      form.value = { ...props.formData };
    } else if (val) {
      form.value = { ...initFormData };
    }
  }
);

watch(visible, (val) => {
  emit('update:modelValue', val);
});

const handleClose = () => {
  visible.value = false;
  formRef.value?.resetFields();
};

const handleFileConfirm = (files: any[]) => {
  if (files && files.length > 0) {
    form.value.projectLogo = files[0].url;
  }
};

const handleLeaderChange = (value: string | number) => {
  const selectedStaff = staffList.value.find((staff) => staff.staffId === value);
  if (selectedStaff) {
    form.value.leaderName = selectedStaff.staffName;
  }
};

const loadStaffList = async () => {
  try {
    const res = await listComStaff({ pageNum: 1, pageSize: 1000 });
    staffList.value = res.rows || [];
  } catch (error) {
    console.error('加载员工列表失败:', error);
  }
};

onMounted(() => {
  loadStaffList();
});

const handleSubmit = async () => {
  await formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateProjectInfo(form.value);
        } else {
          await addProjectInfo(form.value);
        }
        ElMessage.success('操作成功');
        visible.value = false;
        emit('success');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};
</script>

<style scoped lang="scss">
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.logo-upload {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
  }

  .logo-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .logo-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #8c939d;
    font-size: 12px;

    span {
      margin-top: 8px;
    }
  }
}
</style>
