<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="测评人" prop="nickName">
            <el-input v-model="queryParams.nickName" placeholder="请输入测评人" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="interveneStatus">
            <el-select v-model="queryParams.interveneStatus" placeholder="请选状态" style="width: 240px">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.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>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="warnRecordList" @selection-change="handleSelectionChange">
        <el-table-column label="场次名称" align="center" prop="sessionName" />
        <el-table-column label="测评人" align="center" prop="nickName" />
        <el-table-column label="预警时间" align="center" prop="warnTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.warnTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="interveneStatus" width="180">
          <template #default="scope">
            <el-tag :type="scope.row.interveneStatus === 0 ? 'success' : 'danger'">{{ scope.row.interveneStatus === 0 ?
              '无须干预' : '干预中' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="严重度" align="center" prop="situation">
          <template #default="scope">
            {{ handleSituation(scope.row.situation) }}
          </template>
        </el-table-column>
        <el-table-column label="补充说明" align="center" prop="note" />
        <el-table-column label="操作" align="center" class-name="small-padding" width="280">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleDesc(scope.row)"
                v-hasPermi="['warn:record:query']">详情</el-button>
            </el-tooltip>
            <el-tooltip content="补充说明" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['warn:record:edit']">补充说明</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加或修改预警记录对话框 -->
    <el-dialog title="记录详情" v-model="dialogDesc" width="900px" append-to-body :close-on-click-modal="false"
      @close="handleResultClose">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane :label="item.scaleName" :name="item.recordId" v-for="item in resultList" :key="item.recordId">
          <el-card v-for="des in currentResult" style="margin-bottom: 10px;">
            <el-descriptions title="测评详情" :column="1">
              <el-descriptions-item label="总分：">{{ des.score }}</el-descriptions-item>
              <el-descriptions-item label="测评项：">{{ des.factorName }}</el-descriptions-item>
              <el-descriptions-item label="测评结果：">{{ des.evalDesc }}</el-descriptions-item>
            </el-descriptions>
            <p v-html="des.evalPropose"></p>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog title="补充说明" v-model="dialog.visible" width="400px" append-to-body :close-on-click-modal="false">
      <el-form ref="warnRecordFormRef" :model="form" :rules="rules">
        <el-form-item label="" prop="note">
          <el-input v-model="form.note" :rows="4" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WarnRecord" lang="ts">
import { listWarnRecord, getWarnRecord, getEvaluationRecordList, getEvaluationList, delWarnRecord, addWarnRecord, updateWarnRecord } from '@/api/archive/warnRecord';
import { WarnRecordVO, WarnRecordQuery, WarnRecordForm } from '@/api/archive/warnRecord/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const warnRecordList = ref<WarnRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const warnRecordFormRef = ref<ElFormInstance>();

//状态 0 未处理，1 分配咨询师，2 咨询师拒绝干预，3 干预中 4 干预结束
const statusOptions = [
  { label: '无须干预', value: 0 },
  { label: '干预中', value: 1 }
]

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogDesc = ref(false)

const initFormData: WarnRecordForm = {
  warnId: undefined,
  batchNo: undefined,
  userId: undefined,
  status: undefined,
  note: undefined,
  warnTime: undefined,
  nickName: undefined,
  interveneStatus: undefined
}
const data = reactive<PageData<WarnRecordForm, WarnRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    batchNo: undefined,
    userId: undefined,
    status: undefined,
    note: undefined,
    warnTime: undefined,
    nickName: undefined,
    interveneStatus: undefined,
    params: {
    }
  },
  rules: {
    warnId: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    batchNo: [
      { required: true, message: "td_scale_publish表主键不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "测评人id不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态 0 未处理，1 分配咨询师，2 咨询师拒绝干预，3 干预中 4 干预结束不能为空", trigger: "change" }
    ],
    note: [
      { required: true, message: "补充说明不能为空", trigger: "blur" }
    ],
    warnTime: [
      { required: true, message: "预警时间不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询预警记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listWarnRecord(queryParams.value);
  warnRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  warnRecordFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

const resultList = ref([])
const currentResult = ref([])

function handleSituation(situation: any) {
  if (situation == 1) {
    return '未见异常'
  } else if (situation == 2) {
    return '低风险'
  } else if (situation == 3) {
    return '中风险'
  } else if (situation == 4) {
    return '高风险'
  } else {
    return '重大风险'
  }
}

const activeTab = ref('')
/** 修改按钮操作 */
const handleUpdate = async (row?: WarnRecordVO) => {
  reset();
  const _warnId = row?.warnId || ids.value[0]
  const res = await getWarnRecord(_warnId);

  Object.assign(form.value, res.data);
  dialog.title = "补充说明";
  dialog.visible = true
}

async function handleDesc(row: any) {
  dialogDesc.value = true;

  const _warnId = row?.warnId || ids.value[0]
  const res = await getEvaluationRecordList(_warnId);
  resultList.value = res.data
  if (res.data.length > 0) {
    const result = await getEvaluationList({ recordId: res.data[0].recordId, status: 1 })
    activeTab.value = res.data[0].recordId
    currentResult.value = result.data
  }
}

const handleTabChange = async (recordId: any) => {
  activeTab.value = recordId
  const result = await getEvaluationList({ recordId, status: 1 })
  currentResult.value = result.data
}

const handleResultClose = () => {
  resultList.value = []
}

/** 提交按钮 */
const submitForm = () => {
  warnRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      console.log("submitForm");
      buttonLoading.value = true;
      if (form.value.warnId) {
        await updateWarnRecord(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addWarnRecord(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

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

<style lang="scss" scoped>
.card-header {
  font-size: 18px;
  font-weight: bold;
}
</style>
