<template>
  <div class="p-2 bg-gray-50 min-h-screen" v-loading="loading">
    <!-- 顶部导航和用户信息 -->
    <el-card shadow="never" class="mb-4">
      <div class="flex items-center justify-between mb-6">
        <el-button link @click="handleBack" icon="ArrowLeft">返回</el-button>
        <div class="space-x-2">
          <el-button v-if="!isEditing" type="primary" plain size="small" @click="isEditing = true">编辑</el-button>
          <template v-else>
            <el-button type="primary" size="small" @click="handleSave" :loading="saveLoading">保存</el-button>
            <el-button size="small" @click="handleCancel">取消</el-button>
          </template>
        </div>
      </div>
      <div class="flex gap-8 relative">
        <div class="flex flex-col items-center">
          <el-avatar :size="100" :src="form.avatar" />
          <el-tag type="success" size="small" class="mt-2">{{ form.availability || '未知状态' }}</el-tag>
        </div>
        <div class="flex-1">
          <el-form v-if="isEditing" :model="form" label-width="100px" size="small">
            <div class="grid grid-cols-3 gap-4">
              <el-form-item label="姓名">
                <el-input v-model="form.name" />
              </el-form-item>
              <el-form-item label="性别">
                <el-select v-model="form.gender" placeholder="请选择">
                  <el-option v-for="item in sys_user_sex" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="用户类型">
                <el-select v-model="form.userType" placeholder="请选择">
                  <el-option v-for="item in main_user_type" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="form.mobile" />
              </el-form-item>
              <el-form-item label="电子邮箱">
                <el-input v-model="form.email" />
              </el-form-item>
              <el-form-item label="身份证号">
                <el-input v-model="form.idCardNumber" />
              </el-form-item>
              <el-form-item label="求职意向">
                <el-input v-model="form.jobIntention" />
              </el-form-item>
              <el-form-item label="到岗时间">
                <el-select v-model="form.availability" placeholder="请选择">
                  <el-option v-for="item in main_arrivail_time" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="岗位类型">
                <el-select v-model="form.jobType" placeholder="请选择">
                  <el-option v-for="item in main_position_type" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="毕业院校">
                <el-input v-model="form.schoolName" />
              </el-form-item>
              <el-form-item label="学历">
                <el-select v-model="form.education" placeholder="请选择">
                  <el-option v-for="item in main_education" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="工作经验">
                <el-select v-model="form.grade" placeholder="请选择">
                  <el-option v-for="item in main_experience" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="实习时长">
                <el-select v-model="form.internshipDuration" placeholder="请选择">
                  <el-option v-for="item in main_internship_duration" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="备注" class="col-span-3">
                <el-input v-model="form.remark" type="textarea" rows="3" />
              </el-form-item>
            </div>
          </el-form>
          <div v-else class="grid grid-cols-3 gap-y-4 gap-x-12">
            <div class="col-span-1">
              <div class="flex items-center gap-2 mb-2">
                <span class="text-2xl font-bold">{{ form.name }}</span>
                <el-icon v-if="form.gender === '0'" class="text-blue-500"><Male /></el-icon>
                <el-icon v-else-if="form.gender === '1'" class="text-pink-500"><Female /></el-icon>
                <span v-if="form.userType === '1'" class="text-orange-400">💎</span>
              </div>
              <div class="text-xs text-gray-400 mb-1">身份证号</div>
              <div class="text-sm">{{ form.idCardNumber || '-' }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">联系电话</div>
              <div class="text-sm">{{ form.mobile }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">电子邮箱</div>
              <div class="text-sm">{{ form.email || '-' }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">求职意向</div>
              <div class="text-sm">{{ form.jobIntention || '-' }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">岗位类型</div>
              <div class="text-sm">
                <dict-tag :options="main_position_type" :value="form.jobType" />
              </div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">毕业院校</div>
              <div class="text-sm">
                {{ form.schoolName }} · 
                <dict-tag :options="main_experience" :value="form.grade" /> · 
                <dict-tag :options="main_education" :value="form.education" />
              </div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">实习时长</div>
              <div class="text-sm">
                <dict-tag :options="main_internship_duration" :value="form.internshipDuration" />
              </div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">注册日期</div>
              <div class="text-sm">{{ form.createTime }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">最后更新</div>
              <div class="text-sm">{{ form.updateTime }}</div>
            </div>
          </div>
        </div>
        <div v-if="!isEditing" class="absolute right-0 top-0 space-x-2">
          <el-button type="primary" plain size="small" icon="Download" @click="handleExport">导出在线简历</el-button>
          <el-button type="primary" plain size="small" icon="Download" @click="handleDownload">下载简历附件</el-button>
        </div>
      </div>
    </el-card>

    <!-- 底部 Tab 内容 -->
    <el-card shadow="never">
      <el-tabs v-model="activeTab">
        <!-- 在线简历 -->
        <el-tab-pane label="在线简历" name="resume">
          <div class="space-y-8 p-4">
            <section>
              <h3 class="font-bold text-base mb-4 border-l-4 border-blue-500 pl-2">教育经历</h3>
              <el-table :data="form.educationList" border>
                <el-table-column prop="school" label="学校" />
                <el-table-column prop="education" label="学历" />
                <el-table-column label="时间" width="200">
                  <template #default="scope">
                    {{ scope.row.startTime }} - {{ scope.row.endTime }}
                  </template>
                </el-table-column>
                <el-table-column prop="major" label="专业" />
                <el-table-column prop="campusExperience" label="在校经历" show-overflow-tooltip />
              </el-table>
            </section>
            <section>
              <h3 class="font-bold text-base mb-4 border-l-4 border-blue-500 pl-2">工作经历</h3>
              <el-table :data="form.experienceList" border>
                <el-table-column prop="company" label="公司" />
                <el-table-column prop="industry" label="行业" />
                <el-table-column label="时间" width="200">
                  <template #default="scope">
                    {{ scope.row.startTime }} - {{ scope.row.endTime }}
                    <el-tag v-if="scope.row.isInternship === 1" size="small" type="info" class="ml-1">实习</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="jobTitle" label="职位" />
                <el-table-column prop="department" label="所属部门" />
                <el-table-column prop="workContent" label="工作内容" show-overflow-tooltip />
              </el-table>
            </section>
            <section>
              <h3 class="font-bold text-base mb-4 border-l-4 border-blue-500 pl-2">项目经历</h3>
              <el-table :data="form.projectList" border>
                <el-table-column prop="projectName" label="项目名称" />
                <el-table-column prop="role" label="担任角色" />
                <el-table-column label="时间" width="200">
                  <template #default="scope">
                    {{ scope.row.startTime }} - {{ scope.row.endTime }}
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" show-overflow-tooltip />
                <el-table-column prop="achievement" label="业绩" show-overflow-tooltip />
                <el-table-column prop="link" label="链接">
                  <template #default="scope">
                    <el-link v-if="scope.row.link" type="primary" :href="scope.row.link" target="_blank">{{ scope.row.link }}</el-link>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
              </el-table>
            </section>
          </div>
        </el-tab-pane>

        <!-- 测评信息 -->
        <el-tab-pane label="测评信息" name="assessment">
          <div class="p-4">
            <el-table :data="assessmentData" border>
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="position" label="岗位" />
              <el-table-column prop="result" label="结果" />
              <el-table-column prop="time" label="测评时间" />
              <el-table-column label="操作" width="100" align="center">
                <template #default="scope">
                  <el-button link type="primary" @click="handleViewAssessment(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 培训信息 -->
        <el-tab-pane label="培训信息" name="training">
          <div class="p-4">
            <el-table :data="trainingData" border>
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="mode" label="培训方式" />
              <el-table-column prop="time" label="培训时间" />
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 订单信息 -->
        <el-tab-pane label="订单信息" name="order">
          <div class="p-4">
            <div class="flex items-center gap-2 mb-6">
              <div class="w-1 h-4 bg-blue-500"></div>
              <span class="font-bold text-gray-800">订单信息</span>
            </div>
            
            <el-tabs v-model="orderSubTab" class="mb-0 order-tabs">
              <el-tab-pane label="全部订单" name="all" />
              <el-tab-pane label="待付款" name="pending" />
              <el-tab-pane label="已完成" name="completed" />
              <el-tab-pane label="已关闭" name="closed" />
              <el-tab-pane label="退款中" name="refunding" />
            </el-tabs>
            
            <div class="order-table-header flex items-center bg-[#f8f9fb] py-3 px-4 text-xs font-bold text-gray-600 border border-b-0 border-gray-100">
              <div class="flex-1">商品信息</div>
              <div class="w-48 text-center">用户信息</div>
              <div class="w-32 text-center">订单来源</div>
              <div class="w-32 text-center">订单类型</div>
              <div class="w-32 text-center">订单状态</div>
              <div class="w-48 text-center">操作</div>
            </div>

            <div class="space-y-4">
              <div v-for="order in orderList" :key="order.orderId" class="order-item border border-gray-100">
                <div class="order-info-bar flex justify-between items-center bg-[#f4faff] py-2 px-4 text-[11px] text-gray-500 border-b border-gray-100">
                  <div class="flex gap-8">
                    <span>订单编号：{{ order.orderNo }}</span>
                    <span>下单时间：{{ order.createTime }}</span>
                    <span>{{ order.payMode }}</span>
                  </div>
                  <div class="text-[12px] font-bold text-gray-800">实付款（元）：{{ order.amount }}元</div>
                </div>
                <div class="flex items-center py-4 px-4">
                  <div class="flex-1 flex items-center gap-4">
                    <el-image :src="order.goodsImage" class="w-14 h-14 rounded object-cover border border-gray-100" />
                    <div class="flex flex-col gap-1">
                      <div class="font-bold text-blue-500 hover:text-blue-600 cursor-pointer text-[13px]">{{ order.goodsName }}</div>
                      <div class="text-[11px] text-gray-400">单价：{{ order.price }}  数量：{{ order.count }}</div>
                    </div>
                  </div>
                  <div class="w-48 flex items-center justify-center gap-2 border-l border-gray-50 h-14">
                    <el-avatar :size="28" :src="order.userAvatar" />
                    <div class="flex flex-col items-start leading-tight">
                      <div class="text-[12px] font-medium text-blue-500 cursor-pointer">{{ order.userName }}</div>
                      <div class="text-[11px] text-gray-400 mt-0.5">{{ order.userPhone || '18854789000' }}</div>
                    </div>
                  </div>
                  <div class="w-32 text-center text-[12px] text-gray-600 border-l border-gray-50 h-14 flex items-center justify-center">小程序</div>
                  <div class="w-32 text-center text-[12px] text-gray-600 border-l border-gray-50 h-14 flex items-center justify-center">{{ order.orderType }}</div>
                  <div class="w-32 flex justify-center border-l border-gray-50 h-14 items-center">
                    <span class="text-[#2dc26b] font-bold text-[12px]">已完成</span>
                  </div>
                  <div class="w-48 flex items-center justify-center gap-4 border-l border-gray-50 h-14 text-[12px]">
                    <el-button link type="primary" class="!p-0 !text-[12px]" @click="handleOrderDetail(order)">订单详情</el-button>
                    <el-button link type="primary" class="!p-0 !text-[12px]">复制订单</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 任职信息 -->
        <el-tab-pane label="任职信息" name="job">
          <div class="p-4">
            <el-table :data="jobData" border>
              <el-table-column prop="company" label="公司" />
              <el-table-column prop="position" label="岗位" />
              <el-table-column prop="type" label="岗位类型" />
              <el-table-column prop="status" label="任职状态" />
              <el-table-column prop="entryTime" label="入职时间" />
              <el-table-column prop="leaveTime" label="离职时间" />
              <el-table-column prop="reason" label="离职原因" />
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button link type="primary" @click="handleViewEvaluation(scope.row)">查看公司评价</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 评价对话框 -->
    <el-dialog v-model="evaluationOpen" title="评价" width="500px">
      <div class="space-y-6">
        <div class="flex flex-col gap-2">
          <div class="flex items-center gap-4">
            <span class="w-20 font-bold">综合评价</span>
            <el-rate v-model="evaluationForm.score" disabled show-score text-color="#ff9900" />
            <span class="text-xs text-gray-400">3.5星</span>
          </div>
          <el-input v-model="evaluationForm.comment" type="textarea" readonly rows="2" />
        </div>
        <div class="flex flex-col gap-2">
          <div class="flex items-center gap-4">
            <span class="w-20 font-bold">能力A</span>
            <el-rate v-model="evaluationForm.scoreA" disabled show-score text-color="#ff9900" />
            <span class="text-xs text-gray-400">3星</span>
          </div>
          <el-input v-model="evaluationForm.commentA" type="textarea" readonly rows="2" />
        </div>
        <div class="flex flex-col gap-2">
          <div class="flex items-center gap-4">
            <span class="w-20 font-bold">能力B</span>
            <el-rate v-model="evaluationForm.scoreB" disabled show-score text-color="#ff9900" />
            <span class="text-xs text-gray-400">3星</span>
          </div>
          <el-input v-model="evaluationForm.commentB" type="textarea" readonly rows="2" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="StudentDetail" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeft, Male, Female, Download } from '@element-plus/icons-vue'
import { getStudent } from "@/api/main/student";
import { StudentVO } from "@/api/main/student/types";

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_user_sex, main_user_type, main_arrivail_time, main_position_type, main_education, main_experience, main_internship_duration } = proxy?.useDict(
  "sys_user_sex",
  "main_user_type",
  "main_arrivail_time",
  "main_position_type",
  "main_education",
  "main_experience",
  "main_internship_duration"
) as any;

const loading = ref(false)
const saveLoading = ref(false)
const isEditing = ref(false)
const form = ref<Partial<StudentVO>>({})
const originalForm = ref<Partial<StudentVO>>({})
const activeTab = ref('resume')
const orderSubTab = ref('all')

const getDetail = () => {
  // router/index.ts uses 'userId' for the param name
  const id = route.params && route.params.userId;
  if (id) {
    loading.value = true;
    getStudent(id as string).then(response => {
      form.value = response.data;
      originalForm.value = JSON.parse(JSON.stringify(response.data));
      loading.value = false;
    }).catch(() => {
      loading.value = false;
    });
  }
}

onMounted(() => {
  getDetail()
})

const handleBack = () => {
  router.back()
}

/** 导出在线简历 */
const handleExport = () => {
  proxy.download('main/student/export', {
    id: form.value.id
  }, `student_resume_${form.value.name}_${new Date().getTime()}.xlsx`)
}

/** 下载简历附件 */
const handleDownload = () => {
  if (form.value.resumeFile) {
    proxy.$download.oss(form.value.resumeFile)
  } else {
    proxy.$modal.msgWarning("该学员未上传简历附件")
  }
}

const assessmentData = ref([
  {
    id: '1',
    name: '审计A1测评',
    position: '审计A1',
    result: '通过',
    time: '2023.12.12 12:12'
  },
  {
    id: '2',
    name: '审计A2测评',
    position: '审计A2',
    result: '未通过',
    time: '2023.12.13 10:00'
  }
])

const trainingData = ref([
  {
    name: '审计A1培训',
    mode: '线下',
    time: '2023.12.12 12:12'
  }
])

const orderList = ref([
  {
    orderId: 1,
    orderNo: '2020033016180804520',
    createTime: '2020-03-30 16:18:08',
    payMode: '微信支付',
    amount: '4000.00',
    goodsImage: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    goodsName: '审计师A·R2高级直通',
    price: '400.00',
    count: 1,
    userName: '王军',
    userAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    orderType: '测评-定金',
    status: '已完成'
  }
])

const jobData = ref([
  {
    company: 'XXXX公司',
    position: '审计A',
    type: '全职、实习、兼职',
    status: '在职',
    entryTime: '2023.12.12',
    leaveTime: '',
    reason: ''
  },
  {
    company: 'XXXX公司',
    position: '审计A',
    type: '全职',
    status: '离职',
    entryTime: '2024.12.12',
    leaveTime: '2025.12.01',
    reason: '个人发展'
  }
])

const evaluationOpen = ref(false)
const evaluationForm = reactive({
  score: 3.5,
  comment: '在职期间表现极佳',
  scoreA: 3,
  commentA: '在职期间表现极佳',
  scoreB: 3,
  commentB: '在职期间表现极佳'
})

const handleViewAssessment = (row) => {
  router.push({
    path: '/system/assessment/report',
    query: { id: row.id }
  })
}

const handleOrderDetail = (order) => {
  router.push({
    path: '/system/order/detail',
    query: { orderId: order.orderId }
  })
}

const handleViewEvaluation = (row) => {
  evaluationOpen.value = true
}

const handleSave = () => {
  saveLoading.value = true;
  proxy.$modal.msgSuccess('保存成功');
  originalForm.value = JSON.parse(JSON.stringify(form.value));
  isEditing.value = false;
  saveLoading.value = false;
}

const handleCancel = () => {
  form.value = JSON.parse(JSON.stringify(originalForm.value));
  isEditing.value = false;
}
</script>

<style scoped lang="scss">
:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}
:deep(.el-tabs__active-bar) {
  height: 3px;
}
.order-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }
  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
    background-color: #f0f0f0;
  }
}
.order-item {
  transition: all 0.3s;
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
}
</style>
