<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="phonenumber">
            <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </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">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['scale:warnRecord:add']">批量导入档案</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['scale:warnRecord:edit']">下载档案导入模板</el-button>
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['scale:warnRecord:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['scale:warnRecord:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="archiveList">
        <el-table-column label="姓名" align="center" prop="nickName" />
        <el-table-column label="性别" align="center" prop="sex">
          <template #default="scope">
            <el-tag :type="scope.row.sex === '0' ? 'success' : 'danger'" size="small">
              {{ scope.row.sex === '0' ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="年级" align="center" prop="deptName" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" />
        <el-table-column label="家族地址" align="center" prop="address" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleUpdate(scope.row)"
                v-hasPermi="['evaluation:record:view']">查看</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="dialog.title" v-model="dialog.visible" width="900px" append-to-body
      :close-on-click-modal="false">
      <el-tabs v-model="activeName" class="demo-tabs">
        <!-- <el-tab-pane label="基本信息" name="first">
          <el-form ref="informationFormRef" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户名" prop="batchNo">
                  <el-input v-model="form.batchNo" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名" prop="userId">
                  <el-input v-model="form.userId" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="性别" prop="note">
                  <el-input v-model="form.note" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号码" prop="note">
                  <el-input v-model="form.note" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="年级" prop="note">
                  <el-input v-model="form.note" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="班级" prop="note">
                  <el-input v-model="form.note" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="出生年月" prop="note">
                  <el-input v-model="form.note" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="家族住址" prop="note">
                  <el-input v-model="form.note" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="家族信息" name="second">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="date" label="Date" width="180" />
            <el-table-column prop="name" label="Name" width="180" />
            <el-table-column prop="address" label="Address" />
          </el-table>
        </el-tab-pane> -->
        <el-tab-pane label="静态普查记录" name="static">
          <el-table :data="staticList" style="width: 100%">
            <el-table-column prop="sessionName" label="场次名称" />
            <el-table-column prop="scaleName" label="量表名称" />
            <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" class-name="small-padding fixed-width" width="200">
              <template #default="scope">
                <el-tooltip content="查看测评结果" placement="top">
                  <el-button link type="primary" icon="View" @click="handleResult(scope.row)"
                    v-hasPermi="['evaluation:conclusion:list']">查看测评结果</el-button>
                </el-tooltip>
                <el-tooltip content="导出" placement="top">
                  <el-button link type="primary" icon="View" @click="handleExport(scope.row)"
                    v-hasPermi="['evaluation:record:export']">导出</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="staticTotal > 0" :total="staticTotal" v-model:page="staticQuery.pageNum"
            v-model:limit="staticQuery.pageSize" @pagination="getStaticList" />
        </el-tab-pane>
        <!-- <el-tab-pane label="动态普查记录" name="dynamic">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="date" label="Date" width="180" />
            <el-table-column prop="name" label="Name" width="180" />
            <el-table-column prop="address" label="Address" />
          </el-table>
        </el-tab-pane> -->
        <el-tab-pane label="动态干预记录" name="warn">
          <el-table :data="interveneList">
            <el-table-column prop="userName" label="测评人" />
            <el-table-column prop="sessionName" label="场次名称" />
            <el-table-column prop="situation" label="风险等级">
              <template #default="scope">
                {{ handleSituation(scope.row.situation) }}
              </template>
            </el-table-column>
            <el-table-column prop="warnTime" label="预警时间" />
            <el-table-column prop="createTime" label="干预时间" />
            <el-table-column prop="counselorName" label="咨询师" />
            <el-table-column prop="note" label="补充说明" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="查看详情" placement="top">
                  <el-button link type="primary" icon="View" @click="handleInterveneResult(scope.row)">查看详情</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="interveneTotal > 0" :total="interveneTotal" v-model:page="interveneQuery.pageNum"
            v-model:limit="interveneQuery.pageSize" @pagination="getInterveneList" />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog title="记录详情" v-model="dialogResult" width="900px" append-to-body :close-on-click-modal="false">
      <el-card v-for="des in currentResult">
        <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-dialog>

    <el-dialog title="预警干预详情" v-model="interveneResult" width="800px" append-to-body :close-on-click-modal="false">
      <el-descriptions :column="2" direction="vertical" border>
        <el-descriptions-item label="测评人">{{ currentInterveneResult.userName }}</el-descriptions-item>
        <el-descriptions-item label="风险等级">{{ handleSituation(currentInterveneResult.situation)
          }}</el-descriptions-item>
        <el-descriptions-item label="预警时间">{{ currentInterveneResult.warnTime }}</el-descriptions-item>
        <el-descriptions-item label="干预时间">{{ currentInterveneResult.createTime }}</el-descriptions-item>
        <el-descriptions-item label="补充说明">{{ currentInterveneResult.note }}</el-descriptions-item>
        <el-descriptions-item label="诊断说明">{{ currentInterveneResult.diagnose }}</el-descriptions-item>
        <el-descriptions-item label="诊断附件" v-if="currentInterveneResult.diagnoseAnnex">
          <image-preview v-if="checkImg(currentInterveneResult.diagnoseAnnexUrl)"
            :src="currentInterveneResult.diagnoseAnnexUrl" :width="50" :height="50" />
          <el-button v-else type="primary" text
            @click="downloadOss(currentInterveneResult.diagnoseAnnex)">下载附件</el-button>
        </el-descriptions-item>
        <el-descriptions-item label="通知附件" v-if="currentInterveneResult.noticeAnnex">
          <image-preview v-if="checkImg(currentInterveneResult.noticeAnnexUrl)"
            :src="currentInterveneResult.noticeAnnexUrl" :width="50" :height="50" />
          <el-button v-else type="primary" text
            @click="downloadOss(currentInterveneResult.noticeAnnex)">下载附件</el-button>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="WarnRecord" lang="ts">
import { listArchive, listStatistic } from '@/api/archive/information';
import { getEvaluationList } from '@/api/archive/warnRecord';
import { pageInterveneRecord } from '@/api/archive/interveneRecord';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const archiveList = ref<any[]>([]);
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 informationFormRef = ref<ElFormInstance>();

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

const activeName = ref('static')
const current = ref({ userId: '', nickName: '' })

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 checkImg = (annex: any) => {
  return /\.(jpg|jpeg|png|gif)$/.test(annex)
}


const initFormData: any = {

}
const data = reactive<PageData<any, any>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {
    }
  },
  rules: {

  }
});

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

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加预警记录";
}

const staticQuery = ref({
  userId: '',
  pageNum: 1,
  pageSize: 10
})
const staticTotal = ref(0)
const staticList = ref<any[]>([])
/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  staticQuery.value.userId = row.userId;
  interveneQuery.value.userId = row.userId

  current.value.userId = row.userId
  current.value.nickName = row.nickName

  getStaticList()
  getInterveneList()

  // const _warnId = row?.warnId || ids.value[0]
  // const res = await getWarnRecord(_warnId);
  // Object.assign(form.value, res.data);

  dialog.visible = true;
  dialog.title = "查看详情";
}

async function getStaticList() {
  const res = await listStatistic(staticQuery.value);
  staticList.value = res.rows
  staticTotal.value = res.total
}

const interveneQuery = ref({
  userId: '',
  pageNum: 1,
  pageSize: 10
})
const interveneTotal = ref(0)
const interveneList = ref<any[]>([])
async function getInterveneList() {
  const res = await pageInterveneRecord(interveneQuery.value);
  interveneList.value = res.rows
  interveneTotal.value = res.total
}


/** 提交按钮 */
const submitForm = () => {
  informationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      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();
    }
  });
}

const dialogResult = ref(false)
const currentResult = ref([])
async function handleResult(row: any) {
  dialogResult.value = true
  const result = await getEvaluationList({ recordId: row.recordId, status: 1 })
  currentResult.value = result.data
}


const interveneResult = ref(false)
const currentInterveneResult = ref({})
async function handleInterveneResult(row: any) {
  interveneResult.value = true
  currentInterveneResult.value = row
}

function downloadOss(ossId: any) {
  proxy?.$download.oss(ossId)
}

function handleExport(row: any) {
  proxy?.download('scale/evaluation/record/export', {
    scaleId: row.scaleId,
    scaleName: row.scaleName,
    recordId: row.recordId,
    userId: current.value.userId,
    nickName: current.value.nickName
  }, `${current.value.nickName}-${row.scaleName}.pdf`)
}

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