<template>
  <div class="app-container tenant-detail-container">
    <div v-if="!showAddEmployee">
      <!-- 公司认证信息卡片 -->
      <el-card class="info-card shadow-none">
        <h3 class="page-title">公司认证信息</h3>
        
        <el-row :gutter="40" class="top-info-section">
          <!-- 左侧：公司信息 -->
          <el-col :lg="12" :md="24">
            <div class="info-block">
              <h4 class="block-title">公司信息</h4>
              <div class="info-item">
                <span class="label">企业名称：</span>
                <span class="value">{{ companyInfo.companyName || 'XXXXX公司' }}</span>
                <el-button type="primary" link class="copy-btn">复制</el-button>
              </div>
              <div class="info-item">
                <span class="label">官方邮箱：</span>
                <span class="value">{{ companyInfo.email || '2423@162.com' }}</span>
              </div>
              <div class="info-item">
                <span class="label">办公地址：</span>
                <span class="value">{{ companyInfo.address || '上海市XXXXX' }}</span>
              </div>
              <div class="info-item">
                <span class="label">统一社会信用代码：</span>
                <span class="value">{{ companyInfo.licenseNumber || '234752364' }}</span>
              </div>
              <div class="info-item proof-item">
                <span class="label">委托招聘证明：</span>
                <div class="proof-display">
                   <file-upload v-model="companyInfo.companyEntrustProof" :disabled="true" :is-show-tip="false" />
                   <div v-if="!companyInfo.companyEntrustProof" class="placeholder-img">未上传证件</div>
                </div>
              </div>
            </div>
          </el-col>

          <!-- 右侧：联系人信息 -->
          <el-col :lg="12" :md="24">
            <div class="info-block">
              <h4 class="block-title">联系人信息</h4>
              <div class="contact-vertical-style">
                <el-avatar :size="80" :src="avatarUrl || companyInfo.avatar" class="avatar-grey">头像</el-avatar>
                <div class="info-list-cell mt20">
                  <div class="info-li">
                    <span class="label">联系人：</span>
                    <span class="value">{{ companyInfo.contactUserName || '张 三' }}</span>
                  </div>
                  <div class="info-li">
                    <span class="label">手机号：</span>
                    <span class="value">{{ companyInfo.contactPhone || '183274342' }}</span>
                  </div>
                  <div class="info-li mt20">
                    <span class="label">提交时间：</span>
                    <span class="value">{{ companyInfo.createTime || '2019-09-09 10:40' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 下方 Tab 表格部分 -->
      <el-card class="table-card shadow-none mt20">
        <el-tabs v-model="activeTab" class="custom-tabs">
          <el-tab-pane label="岗位信息" name="positions">
            <!-- 搜索与操作栏 -->
            <div class="table-ops">
              <el-input v-model="queryParams.jobName" placeholder="请输入岗位" style="width: 200px">
                <template #append>
                  <el-button :icon="Search" class="search-inner-btn" />
                </template>
              </el-input>
              <el-select v-model="queryParams.jobType" placeholder="岗位类型" style="width: 120px; margin-left: 10px;">
                <el-option label="全职" value="1" />
                <el-option label="实习" value="2" />
              </el-select>
              <el-select v-model="queryParams.jobLevel" placeholder="岗位级别" style="width: 120px; margin-left: 10px;">
                <el-option label="A1" value="A1" />
              </el-select>
              
              <div class="right-ops">
                <el-button type="primary" :icon="Plus" round @click="handleAdd">添加</el-button>
              </div>
            </div>

            <el-table :data="positionList" style="width: 100%" :header-cell-style="{ background: '#f8f9fb', color: '#666', fontWeight: 'bold' }">
              <el-table-column type="selection" width="55" />
              <el-table-column label="岗位名称" prop="postName" />
              <el-table-column label="岗位编码" prop="postCode" />
              <el-table-column label="岗位类别" prop="postCategory" />
              <el-table-column label="岗位排序" prop="postSort" />
              <el-table-column label="部门" prop="deptName">
                <template #default="scope">
                  <span class="link-text" @click="handleApplicantList(scope.row)">{{ scope.row.applyNum }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态">
                <template #default="scope">
                  <el-switch v-model="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="添加时间" prop="createTime" width="180" />
              <el-table-column label="操作" width="150" align="right">
                <template #default>
                  <el-button type="primary" link :icon="Edit" @click=ha>编辑</el-button>
                  <el-button type="primary" link :icon="Delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="员工信息" name="employees">
            <!-- 搜索与操作栏 -->
            <div class="table-ops">
              <el-input v-model="employeeQueryParams.name" placeholder="请输入" style="width: 200px">
                <template #append>
                  <el-button :icon="Search" class="search-inner-btn" />
                </template>
              </el-input>
              <el-select v-model="employeeQueryParams.postType" placeholder="岗位类型" style="width: 120px; margin-left: 10px;">
                <el-option label="全职" value="1" />
                <el-option label="实习" value="2" />
              </el-select>
              <el-select v-model="employeeQueryParams.postLevel" placeholder="岗位级别" style="width: 120px; margin-left: 10px;">
                <el-option label="A1" value="A1" />
              </el-select>
              
              <div class="right-ops">
                <el-button type="primary" :icon="Plus" round @click="handleAddEmployee">添加</el-button>
              </div>
            </div>

            <el-table :data="employeeList" style="width: 100%" :header-cell-style="{ background: '#f8f9fb', color: '#666', fontWeight: 'bold' }">
              <el-table-column type="selection" width="55" />
              <el-table-column label="员工姓名" prop="nickName" />
              <el-table-column label="登录账号" prop="userName" />
              <el-table-column label="用户类型" prop="userType" />
              <el-table-column label="状态">
                <template #default="scope">
                  <el-switch v-model="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="部门" prop="deptName" />
              <el-table-column label="添加时间" prop="createTime" width="180" />
              <el-table-column label="操作" width="150" align="right">
                <template #default>
                  <el-button type="primary" link :icon="Edit" @click="handleEditPost"></el-button>
                  <el-button type="primary" link :icon="Delete"></el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-area mt20">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                :total="100"
                :current-page="1"
                :page-size="10"
                :page-sizes="[10, 20, 30, 50]"
              />
            </div>
          </el-tab-pane>
        </el-tabs>

        <div class="footer-back-fixed">
          <el-button @click="goBack" plain size="large">返回</el-button>
        </div>
      </el-card>
    </div>

    <!-- 添加员工视图 -->
    <div v-else class="form-view-container animated fadeIn">
      <el-card class="form-card shadow-none">
        <div class="form-header">
          <h3 class="page-title">添加员工</h3>
        </div>
        
        <el-form :model="employeeForm" :rules="employeeRules" label-width="120px" class="employee-form mt20">
          <el-row justify="center">
            <el-col :lg="14" :md="18" :sm="24">
              <el-form-item label="员工姓名" prop="employeeName">
                <el-input v-model="employeeForm.employeeName" placeholder="请输入" />
              </el-form-item>
              
              <el-form-item label="登录账号" prop="userName">
                <el-input v-model="employeeForm.userName" placeholder="请输入有效手机号码" />
              </el-form-item>

              <el-form-item label="员工头像" prop="avatar">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handleAvatarChange"
                  accept="image/jpeg,image/png"
                >
                  <div class="upload-placeholder-wrapper">
                    <img v-if="localAvatarUrl" :src="localAvatarUrl" class="avatar-preview" />
                    <div v-else class="upload-placeholder">
                      <el-icon class="upload-icon"><Picture /></el-icon>
                      <div class="upload-text">点击上传</div>
                    </div>
                  </div>
                  <template #tip>
                    <div class="upload-tip">建议尺寸640*320，小于10M的JPG、PNG格式图片</div>
                  </template>
                </el-upload>
              </el-form-item>

              <el-form-item label="员工部门" prop="deptId">
                <el-select v-model="employeeForm.deptId" placeholder="请选择" class="w100">
                  <el-option label="部门A" value="A" />
                  <el-option label="部门B" value="B" />
                </el-select>
              </el-form-item>

              <el-form-item label="角色" prop="roleId">
                <el-select v-model="employeeForm.roleId" placeholder="请选择" class="w100">
                  <el-option label="系统管理员" value="1" />
                  <el-option label="普通员工" value="2" />
                </el-select>
              </el-form-item>

              <el-form-item label="微信" prop="wechat">
                <el-input v-model="employeeForm.wechat" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="QQ" prop="qq">
                <el-input v-model="employeeForm.qq" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="邮箱" prop="email">
                <el-input v-model="employeeForm.email" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="员工介绍" prop="remark">
                <el-input v-model="employeeForm.remark" type="textarea" :rows="4" placeholder="请输入" />
              </el-form-item>

              <div class="form-ops mt40">
                <el-button type="primary" size="large" @click="submitEmployeeForm">提交</el-button>
                <el-button size="large" @click="showAddEmployee = false">返回</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup name="TenantDetail">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getTenant } from "@/api/system/tenant";
import { Search, Plus, Picture, Edit, Delete, UserFilled, Iphone, Clock, User } from '@element-plus/icons-vue';
import { listUser, addUser } from "@/api/system/user";
import { listPost, getPost, addPost, updatePost, delPost } from "@/api/system/post";
import {watch} from 'vue'
import { uploadOss, listByIds } from "@/api/system/oss";
import { ElMessage } from 'element-plus';

const uploadedFile = ref(null);
const route = useRoute();
const router = useRouter();
const activeTab = ref('employees'); // 默认切换到员工信息标签
const companyInfo = ref({});
const avatarUrl = ref('');
const localAvatarUrl = ref(''); // 新增：本地上传预览地址
const showAddEmployee = ref(false);

const positionList = ref([
   
]);

const employeeList = ref([
 
]);

const queryParams = ref({ jobName: '', jobType: '', jobLevel: '' });
const employeeQueryParams = ref({ name: '', postType: '', postLevel: '' });

const employeeForm = ref({
  employeeName: '',
  userName: '',
  avatar: '',
  deptId: '',
  roleId: '',
  wechat: '',
  qq: '',
  email: '',
  remark: ''
});

const employeeRules = {
  employeeName: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  avatar: [{ required: true, message: '请上传员工头像', trigger: 'change' }]
};

// 统一的数据加载函数
const loadData = () => {
  const tenantId = route.query.tenantId;

  // 获取公司信息
  getTenant(tenantId).then(res => {
    if (res.data) {
      companyInfo.value = res.data;
      if (res.data.avatar) {
        listByIds(res.data.avatar).then(ossRes => {
          if (ossRes.data && ossRes.data.length) {
            const rawUrl = ossRes.data[0].url;
            avatarUrl.value = rawUrl.startsWith('http') ? rawUrl : import.meta.env.VITE_APP_BASE_API + rawUrl;
          }
        });
      }
    }
  }).catch(() => { /* 模拟数据 */ });

  // 获取岗位列表
  listPost({ tenantId: tenantId, platformId: 1 }).then(res => {
    if (res.rows) positionList.value = res.rows;
  });

  // 获取员工列表
  listUser({ tenantId: tenantId, platformId: 1 }).then(res => {
    if (res.rows) employeeList.value = res.rows;
  });
};

// 监听路由参数变化，重新加载数据
watch(() => route.query.tenantId, (newTenantId) => {
  if (newTenantId) {
    loadData();
  }
}, { immediate: true });
onMounted(() => {

  loadData();
  
});

const goBack = () => router.back();

/** 新增岗位操作 */
const handleAdd = () => {
  router.push('/system/post-add/index');
};

/** 查看报名列表 */
const handleApplicantList = (row) => {
  router.push({
    path: '/system/tenant/applicant-list/index',
    query: { jobId: row.postId }
  });
};

// 删除岗位
const handleDeletePost = (row) => {
  ElMessageBox.confirm('确定删除该岗位吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delPost(row.postId).then(() => {
      ElMessage.success('删除成功');
      loadPositionList();
    });
  }).catch(() => {});
};

const handleEditPost = (row) => {
  router.push({
    path: '/system/post-add/index',
    query: { postId: row.postId }
  });
};


const handleAvatarChange = (file) => {
  console.log("函数被执行：",file);
  uploadedFile.value = file.raw;
  employeeForm.value.avatar = file.name;
  localAvatarUrl.value = URL.createObjectURL(file.raw); // 创建本地预览链接
};

const handleEditUser = (row) => {
  router.push({
    path: '/system/user/add/index',
    query: { userId: row.userId }
  });
};

/** 新增员工操作 */
const handleAddEmployee = () => {
  showAddEmployee.value = true;
};




/** 提交员工表单 */
const submitEmployeeForm = async () => {
  try {
    if (uploadedFile.value) {
      const res = await uploadOss(uploadedFile.value);
      
      employeeForm.value.avatar = res.data.ossId;
    }

    await addUser(employeeForm.value);

    ElMessage.success('提交成功');
    showAddEmployee.value = false;
    uploadedFile.value = null;
    loadData();
  } catch (error) {
    ElMessage.error('提交失败');
  }
};
</script>

<script>
// 兼容性保留
export default {
  name: "TenantDetail"
};
</script>

<style lang="scss" scoped>
.tenant-detail-container {
  background-color: #f8f9fb;
  min-height: calc(100vh - 84px);
  padding: 24px;

  .page-title { margin-bottom: 24px; font-size: 20px; color: #333; font-weight: 600; }
  
  .info-card { border-radius: 8px; border: none; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.02); }
  .table-card { border-radius: 8px; border: none; box-shadow: 0 4px 12px rgba(0,0,0,0.02); }

  .info-block {
    .block-title { color: #333; margin-bottom: 24px; font-weight: 600; font-size: 16px; }
    .info-item {
      margin-bottom: 18px; font-size: 14px; display: flex; align-items: flex-start;
      .label { color: #888; width: 140px; }
      .value { color: #333; flex: 1; line-height: 1.4; }
      .copy-btn { margin-left: 10px; color: #1890ff; padding: 0; font-size: 14px; height: auto; }
    }
    .proof-item { align-items: flex-start; }
    .proof-images { display: flex; gap: 12px; 
      .proof-img { width: 90px; height: 64px; border-radius: 4px; border: 1px solid #f0f0f0; background: #fff; }
      .placeholder-img { width: 90px; height: 64px; background: #f5f7fa; color: #aaa; display: flex; align-items: center; justify-content: center; font-size: 12px; border: 1px dashed #ddd; border-radius: 4px; }
    }
  }

  .contact-vertical-style {
    .avatar-grey { background-color: #c0c4cc; color: #fff; font-size: 14px; }
    .info-list-cell {
      .info-li {
        margin-bottom: 12px; font-size: 14px; display: flex; align-items: center;
        .label { color: #333; width: 70px; }
        .value { color: #333; font-weight: normal; }
      }
    }
  }

  .table-tab-ops {
    display: flex; gap: 10px; justify-content: flex-end;
  }



  .table-ops {
    display: flex; align-items: center; margin: 16px 0 24px 0;
    .right-ops { margin-left: auto; }
    .search-inner-btn { background: #1890ff !important; border-color: #1890ff !important; color: #fff !important; border-radius: 0 4px 4px 0; font-size: 16px; }
    .el-input :deep(.el-input-group__append) { padding: 0; border: none; overflow: hidden; }
    .el-input :deep(.el-input__inner) { border-right: none; }
  }

  .link-text { color: #1890ff; cursor: pointer; transition: color 0.2s; &:hover { color: #40a9ff; } }
  
  .footer-back-fixed { text-align: center; margin-top: 40px; padding: 20px 0; border-top: 1px solid #f0f0f0; }

  .custom-tabs :deep(.el-tabs__item) { font-size: 16px; font-weight: 500; height: 54px; padding: 0 32px; }
  .custom-tabs :deep(.el-tabs__active-bar) { height: 3px; }
  .custom-tabs :deep(.el-tabs__nav-wrap::after) { height: 1px; background-color: #f0f0f0; }

  /* 添加员工视图样式 */
  .form-view-container {
    max-width: 100%; animation-duration: 0.4s;
    .form-card { padding: 40px; border-radius: 8px; }
    .employee-form {
      .w100 { width: 100%; }
      .avatar-uploader {
        .upload-placeholder {
          width: 280px; height: 140px; border: 1px dashed #d9d9d9; border-radius: 6px;
          display: flex; flex-direction: column; align-items: center; justify-content: center;
          background: #fafafa; cursor: pointer; transition: all 0.3s;
          &:hover { border-color: #1890ff; background: #f0f7ff; }
          .upload-icon { font-size: 32px; color: #999; margin-bottom: 12px; }
          .upload-text { font-size: 14px; color: #666; }
        }
        .upload-tip { font-size: 13px; color: #999; margin-top: 10px; }
      }
      .form-ops { display: flex; gap: 20px; justify-content: flex-start; padding-top: 20px; }
    }
  }
}

.mt20 { margin-top: 20px; }
.mt40 { margin-top: 40px; }

.animated { animation-fill-mode: both; }
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
.fadeIn { animation-name: fadeIn; }
</style>

