<template>
  <div class="p-6 bg-gray-50">
    <div
      class="received mx-auto bg-white rounded-xl shadow-sm overflow-hidden transition-all duration-300 hover:shadow-md">
      <!-- 表单标题区域 -->
      <div class="bg-gradient-to-r from-blue-500 to-blue-600 text-white p-6">
        <h2 class="text-2xl font-bold flex items-center"><i class="el-icon-user-circle mr-3"></i>收集资料清单</h2>
        <p class="text-blue-100 mt-2 opacity-90">请填写相关资料信息</p>
      </div>

      <!-- 表单内容区域 -->
      <el-form ref="mainFormRef" :model="form" :rules="mainRules" label-width="120px" class="p-6">
        <!-- 基本信息区域 -->
        <div class="bg-blue-50 p-4 rounded-lg mb-6">
          <h3 class="text-lg font-semibold text-blue-700 mb-4">基本信息</h3>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <el-form-item label="收资人" prop="userId" class="mb-4">
              <el-select :disabled="disabledAll" v-model="form.userId" placeholder="请选择收资人"
                class="w-full transition-all duration-300 border-gray-300 focus:border-blue-400 focus:ring-1 focus:ring-blue-400">
                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
              </el-select>
            </el-form-item>
            <el-form-item label="专业" prop="user_major" class="mb-4">
              <el-select :disabled="disabledAll" v-model="form.user_major" placeholder="请选择专业"
                class="transition-all duration-300 border-gray-300"
                :rules="{ required: true, message: '请选择专业', trigger: 'change' }">
                <el-option v-for="item in des_user_major" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="电话" prop="phone" class="mb-4">
              <el-input :disabled="disabledAll" placeholder="请输入电话" v-model="form.phone" autocomplete="off" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email" class="mb-4">
              <el-input :disabled="disabledAll" placeholder="请输入邮箱" v-model="form.email" autocomplete="off" />
            </el-form-item>
          </div>
        </div>
        <!-- 资料文件区域 -->
        <div class="mb-6">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-blue-700">资料文件清单</h3>
            <el-button type="primary" size="small" @click="addDocumentItem" v-if="!disabledAll" icon="Plus"> 添加资料
            </el-button>
          </div>
          <el-form ref="documentsFormRef" :model="form" class="space-y-4">
            <div v-for="(item, index) in form.documents" :key="item.id"
              class="bg-gray-50 p-4 rounded-lg transition-all duration-200 hover:shadow-sm">
              <div class="flex justify-between items-start mb-2">
                <span class="text-sm font-medium text-gray-600">资料 {{ index + 1 }}</span>
                <el-button type="text" size="small" text-color="#ff4d4f" @click="removeDocumentItem(index)"
                  icon="el-icon-delete" v-if="form.documents.length > 1 && !disabledAll">
                  删除
                </el-button>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <el-form-item label="文件目录名称" :prop="`documents.${index}.catalogueName`"
                  :rules="[{ required: true, message: '请输入文件目录名称', trigger: 'blur' }]" class="mb-4">
                  <el-input :disabled="disabledAll" placeholder="请输入文件目录名称" v-model="item.catalogueName"
                    autocomplete="off" />
                </el-form-item>
                <el-form-item label="备注" :prop="`documents.${index}.remark`" class="mb-4">
                  <el-input :disabled="disabledAll" placeholder="请输入备注" v-model="item.remark" autocomplete="off" />
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="flex justify-center gap-4 mt-8">
          <el-button type="primary" @click="submitForm" v-hasPermi="['design:collect:add']"
            v-if="!form.id || form.status == 'draft'" size="large">确认提交</el-button>
          <el-button type="primary" @click="update" v-hasPermi="['design:collect:query']"
            v-show="form.id && form.status == 'draft'" icon="Edit" size="large">审核</el-button>
          <el-button type="primary" @click="update" v-hasPermi="['design:collect:query']" v-show="form.status == 'back'"
            size="large" icon="Edit">重新发起审核</el-button>
          <el-button type="primary" @click="onView" v-hasPermi="['design:collect:query']"
            v-show="form.id && form.status != 'draft'" icon="view" size="large">查看流程</el-button>
          <el-button type="success" v-hasPermi="['design:collect:export']" @click="onLoad"
            v-show="form.id && form.status != 'draft'" icon="Download" size="large">导出</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup name="DataCollectionForm" lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useUserStoreHook } from '@/store/modules/user';
import { ElMessage, ElLoading } from 'element-plus';
import { systemUserList } from '@/api/design/appointment';
import { collectBatch, byProjectId, exportWord } from '@/api/design/received';
import { getUser } from '@/api/system/user';
// 用户状态管理
// 获取用户 store
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStoreHook();
// 从 store 中获取当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const { des_user_major } = toRefs<any>(proxy?.useDict('des_user_major'));
const userId = computed(() => userStore.userId);
// 表单引用
const mainFormRef = ref();
// 用户列表
const userList = ref([]);
const userMap = new Map();
const disabledAll = ref(false);
// 表单数据
const form = reactive({
  projectId: currentProject.value?.id,
  userId: '', // 收资人
  user_major: '', // 专业
  phone: '', // 电话
  email: '', // 邮箱
  id: '',
  status: '',
  documents: [
    {
      id: Date.now(),
      catalogueName: '', // 文件目录名称
      remark: '' // 备注
    }
  ] as Array<{
    id: number;
    catalogueName: string;
    remark: string;
  }>
});

// 主表单验证规则
const mainRules = reactive({
  userId: [{ required: true, message: '请输入收资人', trigger: 'blur' }],
  user_major: [{ required: true, message: '请选择专业', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
});

// 添加资料项
const addDocumentItem = () => {
  form.documents.push({
    id: Date.now(),
    catalogueName: '',
    remark: ''
  });
};

// 删除资料项
const removeDocumentItem = (index: number) => {
  form.documents.splice(index, 1);
};
// 查询数据 再次回显
const byProjectIdAll = async () => {
  // 调用接口获取数据
  const res = await byProjectId(currentProject.value?.id);
  console.log(res);
  form.documents = [
    {
      id: Date.now(),
      catalogueName: '',
      remark: ''
    }
  ];
  disabledAll.value = false;
  if (res.code === 200 && res.data) {
    const data = res.data;
    // 回显基本信息
    form.userId = data.userId || '';
    form.user_major = data.userMajor || '';
    form.phone = data.phone || '';
    form.email = data.email || '';
    form.id = data.id || '';
    form.status = data.status || '';
    if (form.status == 'finish') {
      // 表单全部禁用
      disabledAll.value = true;
    }
    // 回显资料文件列表
    if (data.catalogueList && data.catalogueList.length > 0) {
      // 清空现有列表
      form.documents = [];
      // 填充新数据
      data.catalogueList.forEach((item: any, index: number) => {
        form.documents.push({
          id: item.id || Date.now() + index, // 确保id唯一
          catalogueName: item.catalogueName || '',
          remark: item.remark || ''
        });
      });
    } else {
      console.log(11111111);

      // 如果没有资料，保持一个空项
      form.documents = [
        {
          id: Date.now(),
          catalogueName: '',
          remark: ''
        }
      ];
      console.log(form.documents);


    }
  }
};
// 提交表单
const submitForm = async () => {
  if (!mainFormRef.value) return;
  try {
    const valid = await mainFormRef.value.validate();
    if (valid) {
      // 这里可以添加提交逻辑
      form.documents.map((item, i) => {
        item.num = i + 1;
      });
      let body = {
        desCollectBo: {
          projectId: currentProject.value?.id,
          userId: form.userId, // 收资人
          userMajor: form.user_major, // 专业
          id: form.id,
          phone: form.phone, // 电话
          email: form.email, // 邮箱
          userName: userMap.get(form.userId)
        },
        catalogueList: form.documents
      };
      let res = await collectBatch(body);
      if (res.code == 200) {
        byProjectIdAll();
        ElMessage.success('表单提交成功');
      } else {
        ElMessage.success(res.msg);
      }
    }
  } catch (error) {
    ElMessage.error('请完善表单信息后再提交');
  }
};
// 重置表单
const resetForm = () => {
  if (mainFormRef.value) {
    mainFormRef.value.resetFields();
  }
  // 重置资料列表，保留一个空项
  form.documents = [
    {
      id: Date.now(),
      catalogueName: '',
      remark: ''
    }
  ];
};
/** 查询当前部门的所有用户 */
const getDeptAllUser = async (deptId: any) => {
  try {
    const res = await systemUserList({ deptId });
    // 实际项目中使用接口返回的数据
    userList.value = res.rows;
    userList.value.forEach((user) => {
      userMap.set(user.userId, user.nickName);
    });
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  }
};
const update = () => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/approval/received/indexEdit`,
    query: {
      id: form.id,
      type: 'update'
    }
  });
};
const onView = () => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/approval/received/indexEdit`,
    query: {
      id: form.id,
      type: 'view'
    }
  });
};
/** 获取当前用户详情 */
const getUserDetail = async () => {
  try {
    const res = await getUser(userId.value);
    // userInfo.value = res.data.user;
    form.userId = res.data.user.userId;
    form.phone = res.data.user.phonenumber;
    form.email = res.data.user.email;
  } catch (err) {
    ElMessage.error('获取用户信息失败');
  }
};

// 页面挂载时初始化数据
onMounted(() => {
  // 可以在这里添加初始化逻辑
  getUserDetail();
  getDeptAllUser(userStore.deptId).then(() => {
    byProjectIdAll();
  });

});
const onLoad = async () => {
  // 导出接口
  proxy?.download(
    'design/collect/exportWord',
    {
      id: form.id
    },
    `收资清单.zip`
  );
};
//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid, oid) => {
    getUserDetail();
    getDeptAllUser(userStore.deptId).then(() => {
      byProjectIdAll();
    });
  }
);

onUnmounted(() => {
  listeningProject();
});
</script>

<style lang="scss">
.received {
  width: 90%;
  max-width: 1000px;
}

// 全局样式调整，使界面更柔和
::v-deep .el-input__inner,
::v-deep .el-select__input {
  border-radius: 6px;
  border-color: #dcdfe6;
  transition: all 0.2s ease;
}

::v-deep .el-input__inner:focus,
::v-deep .el-select__input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

::v-deep .el-button {
  border-radius: 6px;
  transition: all 0.2s ease;
}

::v-deep .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

// 响应式调整
@media (max-width: 768px) {
  .received {
    width: 95%;
  }

  ::v-deep .el-form-item {
    margin-bottom: 16px;
  }

  ::v-deep .el-form-item__label {
    width: 100px;
  }
}
</style>
