<template>
  <div class="assessment-edit-wrapper">
    <!-- 可滚动内容区域 -->
    <div class="scrollable-content">
      <div class="form-container">
        <el-form v-if="!isFinished" ref="formRef" :model="formData" :rules="rules" label-position="top" :disabled="isView">
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-title">基本信息</div>
            <el-row :gutter="40">
              <el-col :span="16">
                <el-form-item label="测评名称" prop="evaluationName">
                  <el-input v-model="formData.evaluationName" placeholder="请输入名称" maxlength="100" show-word-limit />
                  <div class="form-tip">最多可输入100个字符</div>
                </el-form-item>
                
                <el-form-item label="级别" prop="grade">
                  <el-select v-model="formData.grade" placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="dict in main_position_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="岗位" prop="positionId">
                  <el-select
                    v-model="formData.positionId"
                    placeholder="请选择"
                    style="width: 100%"
                    filterable
                  >
                    <el-option
                      v-for="item in positionOptions"
                      :key="item.id"
                      :label="item.postName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="岗位类型" prop="positionType">
          <!--  -->        <el-select v-model="formData.positionType" placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="dict in main_position_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="详情描述" prop="detail">
                  <editor v-model="formData.detail" :min-height="120" :height="150" placeholder="请输入详细描述，支持图文混排..." />
                </el-form-item>

                <el-form-item label="标签" prop="tags">
                  <el-select
                    v-model="formData.tags"
                    multiple
                    placeholder="请选择标签"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="tag in tagOptions"
                      :key="tag.id"
                      :label="tag.name"
                      :value="tag.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="商品主图" prop="mainImage">
                  <image-upload v-model="formData.mainImage" :limit="1" />
                  <div class="upload-tip" v-if="!isView">点击上传或拖拽图片至此处<br/>支持JPG、PNG格式，建议尺寸800*800px</div>
                </el-form-item>
                
                <el-form-item label="商品相册" prop="imageAlbum">
                  <image-upload v-model="formData.imageAlbum" :limit="10" />
                  <div class="upload-tip" v-if="!isView">最多可上传10张图片，这些图片将在小程序详情页顶部轮播展示</div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 能力配置（作答信息） -->
          <div class="form-section">
            <div class="section-title">能力配置</div>
            <div class="ability-list">
              <div v-for="(item, index) in formData.abilityConfigs" :key="index" class="ability-item-card">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item :label="'能力名称'" :prop="'abilityConfigs.' + index + '.abilityName'" :rules="{ required: true, message: '请输入能力名称', trigger: 'blur' }">
                      <el-input v-model="item.abilityName" placeholder="如：能力A" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item :label="'关联试卷'" :prop="'abilityConfigs.' + index + '.thirdExamInfoId'" :rules="{ required: true, message: '请选择试卷', trigger: 'change' }">
                      <el-input 
                        v-model="item.thirdExamName" 
                        placeholder="点击选择试卷" 
                        readonly 
                        @click="!isView && showExamDialog(index)"
                      >
                        <template #append v-if="!isView">
                          <el-button @click="showExamDialog(index)">选择</el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item :label="'时长(分)'" :prop="'abilityConfigs.' + index + '.thirdExamTime'">
                      <el-input-number v-model="item.thirdExamTime" :min="1" controls-position="right" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item :label="'总分'" :prop="'abilityConfigs.' + index + '.thirdExamTotalScore'">
                      <el-input-number v-model="item.thirdExamTotalScore" :min="0" controls-position="right" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item :label="'及格分'" :prop="'abilityConfigs.' + index + '.thirdExamPassMark'">
                      <el-input-number v-model="item.thirdExamPassMark" :min="0" :max="item.thirdExamTotalScore || 100" controls-position="right" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>

          <!-- 价格与上架 -->
          <div class="form-section no-border">
            <div class="section-title">价格与上架</div>
            <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item label="销售价" prop="price">
                  <el-input v-model="formData.price" placeholder="请输入价格">
                    <template #prefix>￥</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上架时间" prop="onlineStatus">
                  <div class="online-status-wrapper">
                    <el-radio-group v-model="formData.onlineStatus">
                      <el-radio label="1">立即上架</el-radio>
                      <el-radio label="2">定时上架</el-radio>
                      <el-radio label="3">暂不上架</el-radio>
                    </el-radio-group>
                    <div v-if="formData.onlineStatus === '2'" class="date-picker-inline">
                      <el-date-picker
                        v-model="formData.onlineTimeRange"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>

        <!-- 成功状态 -->
        <div v-else class="success-content">
          <div class="success-center">
            <el-icon :size="80" color="#67C23A" style="margin-bottom: 20px">
              <SuccessFilled />
            </el-icon>
            <div class="success-text">{{ isEdit ? '修改成功' : '创建成功' }}</div>
            <el-button type="primary" @click="goBack" class="finish-btn">完成</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 固定底部 -->
    <div v-if="!isFinished" class="fixed-footer">
      <el-button @click="goBack">{{ isView ? '返回' : '取消' }}</el-button>
      <el-button v-if="!isView" @click="handleSubmitDraft" :loading="loading">保存草稿</el-button>
      <el-button v-if="!isView" type="primary" @click="handleSubmit" :loading="loading">确认发布</el-button>
    </div>

    <!-- 试卷选择对话框 -->
    <el-dialog 
      v-model="examDialog.visible" 
      title="选择试卷" 
      width="900px" 
      append-to-body
    >
      <el-table 
        v-loading="examDialog.loading"
        :data="examDialog.examList"
        @row-click="selectExam"
        style="cursor: pointer"
      >
        <el-table-column label="试卷名称" prop="examName" min-width="200" show-overflow-tooltip />
        <el-table-column label="考试时长" prop="examTime" width="100" align="center">
          <template #default="scope">
            {{ scope.row.examTime || scope.row.duration || 0 }}分钟
          </template>
        </el-table-column>
        <el-table-column label="总分" prop="examTotalScore" width="80" align="center">
          <template #default="scope">
            {{ scope.row.examTotalScore || 100 }}分
          </template>
        </el-table-column>
        <el-table-column label="及格分" prop="passMark" width="80" align="center">
          <template #default="scope">
            {{ scope.row.passMark || 0 }}分
          </template>
        </el-table-column>
        <el-table-column label="开始时间" prop="examStartTime" width="160" align="center" />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click.stop="selectExam(scope.row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container" style="margin-top: 20px; text-align: center;">
        <el-pagination
          v-model:current-page="examDialog.currentPage"
          :page-size="examDialog.pageSize"
          :total="examDialog.total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="AssessmentDetail">
import { ref, reactive, onMounted, onActivated, nextTick, getCurrentInstance, toRefs, watch } from 'vue';
import { SuccessFilled } from '@element-plus/icons-vue';
import { getEvaluation, addEvaluation, updateEvaluation, getThirdPartyExamList } from '@/api/main/evaluation';
import { listTag } from '@/api/system/tag';
import { listPosition } from '@/api/main/position';
import { useRoute, useRouter } from 'vue-router';
import Editor from '@/components/Editor/index.vue';
import ImageUpload from '@/components/ImageUpload/index.vue';

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

// 字典数据
const { main_position_level, main_position_type } = toRefs<any>(
  proxy?.useDict('main_position_level', 'main_position_type')
);

const loading = ref(false);
const isFinished = ref(false);
const formRef = ref();
const isEdit = ref(false);
const isView = ref(false);
const positionOptions = ref<any[]>([]);
const tagOptions = ref<any[]>([]);

// 试卷选择对话框相关
const examDialog = reactive({
  visible: false,
  loading: false,
  examList: [],
  currentPage: 1,
  pageSize: 10,
  total: 0,
  currentAbilityIndex: -1 // 当前正在为哪个能力选择试卷
});

const createDefaultFormData = (): any => ({
  id: undefined,
  evaluationName: '',
  grade: '',
  positionId: undefined,
  positionType: '',
  status: '0',
  description: '',
  tags: '',
  remark: '',
  switchStatus: '0',
  onlineStatus: '1',
  onlineTimeRange: [],
  abilityConfigs: [
    { abilityName: '能力A', thirdExamInfoId: '', thirdExamName: '', thirdExamTime: 60, thirdExamPassMark: 60, thirdExamTotalScore: 100, thirdExamLink: '' },
    { abilityName: '能力B', thirdExamInfoId: '', thirdExamName: '', thirdExamTime: 60, thirdExamPassMark: 60, thirdExamTotalScore: 100, thirdExamLink: '' },
    { abilityName: '能力C', thirdExamInfoId: '', thirdExamName: '', thirdExamTime: 60, thirdExamPassMark: 60, thirdExamTotalScore: 100, thirdExamLink: '' }
  ]
});

const formData = ref<EvaluationVO>(createDefaultFormData());

/** 重置表单 */
const resetForm = () => {
  formData.value = createDefaultFormData();
  formRef.value?.resetFields();
};

const rules = {
  evaluationName: [
    { required: true, message: '测评名称不能为空', trigger: 'blur' }
  ],
  thirdExamInfoId: [
    { required: true, message: '请选择试卷', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '级别不能为空', trigger: 'change' }
  ],
  positionId: [
    { required: true, message: '岗位不能为空', trigger: 'change' }
  ],
  positionType: [
    { required: true, message: '岗位类型不能为空', trigger: 'change' }
  ],
  price: [
    { required: true, message: '价格不能为空', trigger: 'blur' }
  ],
  onlineStatus: [
    { required: true, message: '请选择上架时间', trigger: 'change' }
  ],
  onlineTimeRange: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (formData.value.onlineStatus === '2' && (!value || value.length !== 2)) {
          callback(new Error('请选择定时上架时间范围'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

/** 返回 */
const goBack = () => {
  resetForm();
  router.replace({
    path: '/system/assessment',
    query: { t: Date.now() }
  });
};

/** 添加能力 */
const addAbility = () => {
  formData.value.abilityConfigs.push({
    abilityName: '',
    thirdExamInfoId: '',
    thirdExamName: '',
    thirdExamTime: 60,
    thirdExamPassMark: 60,
    thirdExamTotalScore: 100,
    thirdExamLink: ''
  });
};

/** 删除能力 */
const removeAbility = (index: number) => {
  formData.value.abilityConfigs.splice(index, 1);
};

/** 显示试卷选择对话框 */
const showExamDialog = async (index: number) => {
  examDialog.currentAbilityIndex = index;
  examDialog.visible = true;
  examDialog.currentPage = 1;
  await loadExamList();
};

/** 加载试卷列表 */
const loadExamList = async () => {
  examDialog.loading = true;
  try {
    const res = await getThirdPartyExamList(examDialog.currentPage);
    let examData = [];
    let total = 0;
    
    // 根据用户提供的特殊格式：数据在 msg 字段的 JSON 字符串中
    const rawData = (res as any).data || (res as any).msg;
    
    if (rawData && typeof rawData === 'string') {
      try {
        const parsedData = JSON.parse(rawData);
        if (parsedData.bizContent) {
          examData = parsedData.bizContent.rows || [];
          total = parsedData.bizContent.total || 0;
        }
      } catch (e) {
        console.error('解析考试列表失败:', e);
      }
    } else if (typeof res === 'object') {
      // 兼容普通对象格式
      const data: any = res;
      if (data.bizContent) {
        examData = data.bizContent.rows || [];
        total = data.bizContent.total || 0;
      }
    }
    
    examDialog.examList = examData;
    examDialog.total = total;
  } catch (error) {
    console.error('获取试卷列表失败:', error);
    proxy?.$modal.msgError('获取试卷列表失败');
  } finally {
    examDialog.loading = false;
  }
};

/** 分页变化处理 */
const handlePageChange = (page: number) => {
  examDialog.currentPage = page;
  loadExamList();
};

/** 选择试卷 */
const selectExam = (exam: any) => {
  const index = examDialog.currentAbilityIndex;
  if (index !== -1) {
    const ability = formData.value.abilityConfigs[index];
    ability.thirdExamName = exam.examName || exam.name;
    ability.thirdExamInfoId = exam.examInfoId || exam.id;
    ability.thirdExamTime = exam.examTime || exam.duration || 0;
    ability.thirdExamPassMark = exam.passMark || 0;
    ability.thirdExamTotalScore = exam.examTotalScore || exam.totalScore || 0;
    if (exam.examLink) {
      ability.thirdExamLink = exam.examLink;
    }
  }
  
  examDialog.visible = false;
  proxy?.$modal.msgSuccess('试卷选择成功');
};

/** 获取详情 */
const getDetail = async (id: string | number) => {
  try {
    loading.value = true;
    const res = await getEvaluation(id);
    const data = res.data;
    
    let decodedDetail = data.detail || '';
    if (decodedDetail && !decodedDetail.includes('<') && /^[A-Za-z0-9+/=\r\n]+$/.test(decodedDetail) && decodedDetail.length % 4 === 0) {
      try {
        decodedDetail = decodeURIComponent(escape(atob(decodedDetail)));
      } catch (e) {
        console.warn('Detail decoding failed', e);
      }
    }

    formData.value = {
      id: data.id,
      evaluationName: data.evaluationName || '',
      grade: data.grade ? String(data.grade) : '',
      positionId: data.positionId,
      positionType: data.positionType ? String(data.positionType) : '',
      detail: decodedDetail,
      tags: data.tags ? data.tags.split(',') : [],
      mainImage: data.mainImage || '',
      imageAlbum: data.imageAlbum || '',
      price: data.price || 0,
      status: data.status || '0',
      onlineStatus: data.status === '0' ? '3' : '1',
      onlineTimeRange: (data.onTime && data.downTime) ? [data.onTime, data.downTime] : [],
      abilityConfigs: (data.abilityConfigs || []).map((item: any) => ({
        id: item.id,
        evaluationId: item.evaluationId,
        abilityName: item.abilityName || '',
        thirdExamInfoId: item.thirdExamInfoId || '',
        thirdExamName: item.thirdExamName || '',
        thirdExamTime: item.thirdExamTime || 60,
        thirdExamPassMark: item.thirdExamPassMark || 60,
        thirdExamTotalScore: item.thirdExamTotalScore || 100,
        thirdExamLink: item.thirdExamLink || ''
      }))
    };
    
    // 如果能力配置不足3个，补足到3个
    const currentLength = formData.value.abilityConfigs.length;
    if (currentLength < 3) {
      const names = ['能力A', '能力B', '能力C'];
      for (let i = currentLength; i < 3; i++) {
        formData.value.abilityConfigs.push({
          abilityName: names[i],
          thirdExamInfoId: '',
          thirdExamName: '',
          thirdExamTime: 60,
          thirdExamPassMark: 60,
          thirdExamTotalScore: 100,
          thirdExamLink: ''
        });
      }
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    proxy?.$modal.msgError('获取详情失败');
  } finally {
    loading.value = false;
  }
};

 /** 提交表单 */
 const handleSubmit = async () => {
     try {
      if (loading.value) {
        return;
      }
      await formRef.value?.validate();
      loading.value = true;
      
      const submitData = {
        ...formData.value,
        abilityConfigs: (formData.value.abilityConfigs || []).map((item: any, index: number) => ({
          id: item.id,
          evaluationId: item.evaluationId,
          abilityName: item.abilityName,
          thirdExamInfoId: item.thirdExamInfoId,
          thirdExamName: item.thirdExamName,
          thirdExamTime: item.thirdExamTime,
          thirdExamPassMark: item.thirdExamPassMark,
          thirdExamTotalScore: item.thirdExamTotalScore,
          thirdExamLink: item.thirdExamLink,
          sortOrder: index
        }))
      };
      
      // 标签转回字符串
      submitData.tags = Array.isArray(submitData.tags) ? submitData.tags.join(',') : submitData.tags;
      
      // 设置上架/下架时间
      if (submitData.onlineStatus === '2' && submitData.onlineTimeRange?.length === 2) {
      submitData.onTime = submitData.onlineTimeRange[0];
      submitData.downTime = submitData.onlineTimeRange[1];
    } else {
      submitData.onTime = null;
      submitData.downTime = null;
    }

    // 设置状态：0=草稿, 1=已发布, 2=已下架
    if (submitData.onlineStatus === '3') {
      submitData.status = '0';
    } else {
      submitData.status = '1';
      }

      const hasValidId = submitData.id !== undefined && submitData.id !== null && submitData.id !== '';
      
      if (isEdit.value) {
        if (!hasValidId) {
          proxy?.$modal.msgError('当前编辑数据缺少ID，请刷新后重试');
          return;
        }
        await updateEvaluation(submitData);
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addEvaluation(submitData);
        proxy?.$modal.msgSuccess('新增成功');
      }
    
    goBack();
  } catch (error) {
    console.error('提交失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 保存草稿 */
const handleSubmitDraft = async () => {
  try {
    loading.value = true;
    const draftData = { ...formData.value };
    draftData.saveTime = new Date().toISOString();
    const draftKey = isEdit.value ? `assessment_draft_${formData.value.id}` : `assessment_draft_new`;
    localStorage.setItem(draftKey, JSON.stringify(draftData));
    proxy?.$modal.msgSuccess('草稿保存成功');
  } catch (error) {
    console.error('保存草稿失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 加载岗位列表 */
const getPositionList = async () => {
  try {
    const res: any = await listPosition({ pageNum: 1, pageSize: 999 });
    positionOptions.value = res.rows || [];
  } catch (error) {
    console.error('获取岗位列表失败:', error);
  }
};

/** 加载标签列表 */
const getTagList = async () => {
  try {
    const res: any = await listTag({ status: '0' });
    // 后端返回的数据可能直接是数组，也可能是包含 rows 或 data 的对象
    tagOptions.value = Array.isArray(res) ? res : (res.rows || res.data || []);
  } catch (error) {
    console.error('获取标签列表失败:', error);
  }
};

onMounted(() => {
  getPositionList();
  getTagList();
  handleRouteChange(route.query);
});

onActivated(() => {
  handleRouteChange(route.query);
});

/** 统一处理路由参数逻辑 */
const handleRouteChange = (query: any) => {
  isFinished.value = false;
  const id = query.id;
  isView.value = query.mode === 'view';
  if (id) {
    isEdit.value = true;
    getDetail(id as string);
  } else {
    isEdit.value = false;
    isView.value = false;
    resetForm();
  }
};

watch(() => route.query, (newQuery) => {
  handleRouteChange(newQuery);
}, { immediate: false, deep: true });
</script>

<style scoped lang="scss">
.assessment-edit-wrapper {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  overflow: hidden;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding: 30px 40px;
  background-color: #fff;
}

.form-container {
  width: 100%;
}

.success-content {
  height: 60vh;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .success-center {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .success-text {
      font-size: 18px;
      color: #333;
      margin-bottom: 30px;
    }
    
    .finish-btn {
      width: 100px;
    }
  }
}

.form-section {
  background: #fff;
  padding: 24px;
  margin-bottom: 20px;
  border-radius: 4px;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 24px;
    color: #303133;
    position: relative;
    padding-left: 12px;
    
    &::before {
      content: "";
      position: absolute;
      left: 0;
      top: 3px;
      bottom: 3px;
      width: 4px;
      background: #409eff;
      border-radius: 2px;
    }
  }
}

.no-border {
  margin-bottom: 0;
}

.fixed-footer {
  height: 64px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  border-top: 1px solid #e6e6e6;
  flex-shrink: 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.6;
  margin-top: 8px;
}

.ability-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  
  .ability-item-card {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 20px;
    position: relative;
    
    .ability-ops {
      display: flex;
      justify-content: flex-end;
      margin-top: -10px;
    }
  }
  
  .add-ability-btn {
    text-align: center;
    border: 1px dashed #dcdfe6;
    border-radius: 8px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      border-color: #409eff;
      background: #f0f7ff;
    }
  }
}

.online-status-wrapper {
  .date-picker-inline {
    margin-top: 16px;
  }
}

:deep(.el-form-item__label) {
  font-weight: normal;
  padding-bottom: 8px !important;
}

:deep(.el-input-group__append) {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
  
  .el-button {
    color: #fff;
  }
}

:deep(.editor) {
  width: 100% !important;
  .ql-container {
    height: 150px !important;
  }
}
</style>
