<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="学生姓名" prop="studentId">
              <el-select v-model="queryParams.studentId" placeholder="选择学生" clearable filterable style="width: 180px" @keyup.enter="handleQuery">
                <el-option v-for="s in studentList" :key="s.id" :label="s.name" :value="s.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="约谈方式" prop="method">
              <el-select v-model="queryParams.method" placeholder="约谈方式" clearable style="width: 140px">
                <el-option v-for="opt in interviewMethodOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="约谈结论" prop="result">
              <el-select v-model="queryParams.result" placeholder="约谈结论" clearable style="width: 140px">
                <el-option v-for="opt in interviewResultOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="跟进状态" prop="followStatus">
              <el-select v-model="queryParams.followStatus" placeholder="跟进状态" clearable style="width: 120px">
                <el-option v-for="opt in followStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:interview:add']" type="primary" plain icon="Plus" @click="handleAdd">新增约谈</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:interview:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="interviewList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学生" align="center" prop="studentName" width="100" show-overflow-tooltip />
        <el-table-column label="约谈时间" align="center" prop="interviewTime" width="160">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.interviewTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="方式" align="center" width="80">
          <template #default="scope">
            <el-tag :type="getMethodTag(scope.row.method)" size="small">{{ getMethodLabel(scope.row.method) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="地点" align="center" prop="location" width="120" show-overflow-tooltip />
        <el-table-column label="谈话主题" align="center" prop="topic" min-width="160" show-overflow-tooltip />
        <el-table-column label="约谈人" align="center" prop="interviewerName" width="90" />
        <el-table-column label="约谈结论" align="center" width="110">
          <template #default="scope">
            <el-tag :type="getResultTag(scope.row.result)" size="small">{{ getResultLabel(scope.row.result) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下次跟进" align="center" width="120">
          <template #default="scope">
            <span v-if="scope.row.followStatus === '2'" class="text-gray-400">无需跟进</span>
            <span v-else-if="scope.row.followStatus === '1'">{{ proxy.parseTime(scope.row.nextFollowTime, '{y}-{m}-{d}') }}</span>
            <span v-else :class="{ 'text-red-500 font-bold': scope.row.nextFollowTime && new Date(scope.row.nextFollowTime) < new Date() }">
              {{ scope.row.nextFollowTime ? proxy.parseTime(scope.row.nextFollowTime, '{y}-{m}-{d}') : '-' }}
              <el-tag v-if="scope.row.nextFollowTime && new Date(scope.row.nextFollowTime) < new Date()" type="danger" size="small" class="ml-1">逾期</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="跟进状态" align="center" width="90">
          <template #default="scope">
            <el-tag :type="getFollowTag(scope.row.followStatus)" size="small">{{ getFollowLabel(scope.row.followStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button v-hasPermi="['edu:interview:query']" link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button v-hasPermi="['edu:interview:edit']" link type="primary" icon="Edit" @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.followStatus === '0'" content="标记已跟进" placement="top">
              <el-button v-hasPermi="['edu:interview:follow']" link type="success" icon="Check" @click="handleFollow(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['edu:interview:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="680px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="学生" prop="studentId">
              <el-select v-model="form.studentId" placeholder="选择学生" filterable :disabled="!!form.id" style="width: 100%">
                <el-option v-for="s in studentList" :key="s.id" :label="s.name" :value="s.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="约谈时间" prop="interviewTime">
              <el-date-picker v-model="form.interviewTime" type="datetime" placeholder="选择时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="约谈方式" prop="method">
              <el-select v-model="form.method" placeholder="选择方式" style="width: 100%">
                <el-option v-for="opt in interviewMethodOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="约谈地点">
              <el-input v-model="form.location" placeholder="面谈填写地点" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="谈话主题">
          <el-input v-model="form.topic" placeholder="请输入谈话主题" />
        </el-form-item>
        <el-form-item label="学生近况">
          <el-input v-model="form.studentStatus" type="textarea" :rows="2" placeholder="近期学习、生活状况" />
        </el-form-item>
        <el-form-item label="内容纪要">
          <el-input v-model="form.content" type="textarea" :rows="3" placeholder="约谈内容纪要" />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="约谈结论">
              <el-select v-model="form.result" placeholder="选择结论" clearable style="width: 100%">
                <el-option v-for="opt in interviewResultOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跟进状态">
              <el-select v-model="form.followStatus" placeholder="跟进状态" style="width: 100%">
                <el-option v-for="opt in followStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="达成结论">
          <el-input v-model="form.conclusion" type="textarea" :rows="2" placeholder="与家长达成的共识" />
        </el-form-item>
        <el-form-item label="下一步行动">
          <el-input v-model="form.nextAction" type="textarea" :rows="2" placeholder="下一步行动项" />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="下次跟进时间">
              <el-date-picker v-model="form.nextFollowTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件">
          <file-upload v-model="form.attachments" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog v-model="viewDialog.visible" title="约谈详情" width="680px" append-to-body>
      <template v-if="viewRow">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生">{{ viewRow.studentName }}</el-descriptions-item>
          <el-descriptions-item label="约谈时间">{{ proxy.parseTime(viewRow.interviewTime) }}</el-descriptions-item>
          <el-descriptions-item label="约谈方式">
            <el-tag :type="getMethodTag(viewRow.method)" size="small">{{ getMethodLabel(viewRow.method) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="地点">{{ viewRow.location || '-' }}</el-descriptions-item>
          <el-descriptions-item label="约谈人">{{ viewRow.interviewerName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="谈话主题">{{ viewRow.topic || '-' }}</el-descriptions-item>
          <el-descriptions-item label="约谈结论" :span="2">
            <el-tag :type="getResultTag(viewRow.result)" size="small">{{ getResultLabel(viewRow.result) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学生近况" :span="2">{{ viewRow.studentStatus || '-' }}</el-descriptions-item>
          <el-descriptions-item label="内容纪要" :span="2">{{ viewRow.content || '-' }}</el-descriptions-item>
          <el-descriptions-item label="达成结论" :span="2">{{ viewRow.conclusion || '-' }}</el-descriptions-item>
          <el-descriptions-item label="下一步行动" :span="2">{{ viewRow.nextAction || '-' }}</el-descriptions-item>
          <el-descriptions-item label="下次跟进时间">
            <span :class="{ 'text-red-500 font-bold': viewRow.nextFollowTime && new Date(viewRow.nextFollowTime) < new Date() }">
              {{ viewRow.nextFollowTime ? proxy.parseTime(viewRow.nextFollowTime, '{y}-{m}-{d}') : '-' }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="跟进状态">
            <el-tag :type="getFollowTag(viewRow.followStatus)" size="small">{{ getFollowLabel(viewRow.followStatus) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="附件" :span="2">
            <file-upload v-model="viewRow.attachments" :disabled="true" />
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ viewRow.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </template>
      <template #footer>
        <el-button @click="viewDialog.visible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduInterview" lang="ts">
import { listInterview, getInterview, addInterview, updateInterview, delInterview, markFollowed } from '@/api/edu/interview';
import { listStudent } from '@/api/edu/student';
import {
  InterviewQuery,
  InterviewVO,
  InterviewForm,
  interviewMethodOptions,
  interviewResultOptions,
  followStatusOptions
} from '@/api/edu/interview/types';
import { StudentVO } from '@/api/edu/student/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const interviewList = ref<InterviewVO[]>([]);
const studentList = ref<StudentVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();

const dialog = reactive<{ visible: boolean; title: string }>({ visible: false, title: '' });
const viewDialog = reactive<{ visible: boolean }>({ visible: false });
const viewRow = ref<InterviewVO | null>(null);

const data = reactive<PageData<InterviewForm, InterviewQuery>>({
  form: {
    studentId: undefined,
    interviewTime: '',
    method: 'FACE',
    location: '',
    topic: '',
    content: '',
    studentStatus: '',
    result: '',
    conclusion: '',
    nextAction: '',
    nextFollowTime: '',
    followStatus: '0',
    attachments: '',
    remark: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    method: '',
    result: '',
    followStatus: ''
  },
  rules: {
    studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
    interviewTime: [{ required: true, message: '请选择约谈时间', trigger: 'change' }],
    method: [{ required: true, message: '请选择约谈方式', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 字典辅助
const getMethodLabel = (val: string) => interviewMethodOptions.find((o) => o.value === val)?.label || val;
const getMethodTag = (val: string) => interviewMethodOptions.find((o) => o.value === val)?.elTagType || 'info';
const getResultLabel = (val: string) => interviewResultOptions.find((o) => o.value === val)?.label || val;
const getResultTag = (val: string) => interviewResultOptions.find((o) => o.value === val)?.elTagType || 'info';
const getFollowLabel = (val: string) => followStatusOptions.find((o) => o.value === val)?.label || val;
const getFollowTag = (val: string) => followStatusOptions.find((o) => o.value === val)?.elTagType || 'info';

/** 加载学生列表 */
const loadStudents = async () => {
  const res = await listStudent({ pageNum: 1, pageSize: 1000 } as any);
  studentList.value = res.rows;
};

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInterview(queryParams.value);
  interviewList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: InterviewVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 重置表单 */
const reset = () => {
  form.value = {
    studentId: undefined,
    interviewTime: '',
    method: 'FACE',
    location: '',
    topic: '',
    content: '',
    studentStatus: '',
    result: '',
    conclusion: '',
    nextAction: '',
    nextFollowTime: '',
    followStatus: '0',
    attachments: '',
    remark: ''
  };
  formRef.value?.resetFields();
};

/** 新增 */
const handleAdd = () => {
  reset();
  dialog.title = '新增约谈';
  dialog.visible = true;
};

/** 查看 */
const handleView = async (row: InterviewVO) => {
  const res = await getInterview(row.id);
  viewRow.value = res.data;
  viewDialog.visible = true;
};

/** 编辑 */
const handleEdit = async (row: InterviewVO) => {
  reset();
  const res = await getInterview(row.id);
  Object.assign(form.value, res.data);
  dialog.title = '编辑约谈';
  dialog.visible = true;
};

/** 标记已跟进 */
const handleFollow = async (row: InterviewVO) => {
  await proxy?.$modal.confirm('确认将此约谈标记为已跟进？');
  await markFollowed(row.id);
  proxy?.$modal.msgSuccess('已标记为已跟进');
  await getList();
};

/** 提交表单 */
const submitForm = async () => {
  await formRef.value?.validate();
  if (form.value.id) {
    await updateInterview(form.value);
    proxy?.$modal.msgSuccess('修改成功');
  } else {
    await addInterview(form.value);
    proxy?.$modal.msgSuccess('新增成功');
  }
  dialog.visible = false;
  await getList();
};

/** 删除 */
const handleDelete = async (row?: InterviewVO) => {
  const delIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选中的约谈记录？');
  await delInterview(delIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

onMounted(() => {
  loadStudents();
  getList();
});
</script>
