<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="batchNo">
            <el-select v-model="queryParams.batchNo" placeholder="请选择" style="width: 240px">
              <el-option v-for="item in publishList" :key="item.batchNo" :label="item.sessionName"
                :value="item.batchNo"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="测评人" prop="batchNo">
            <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 statusOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="严重度" prop="situation">
            <el-select v-model="queryParams.situation" placeholder="请选择" style="width: 240px">
              <el-option v-for="dict in yzd" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预警时间" prop="note">
            <el-date-picker clearable v-model="queryParams.warnTime" type="daterange" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="YYYY-MM-DD" />
          </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">
        <el-table-column label="场次名称" align="center" prop="sessionName" width="200" />
        <el-table-column label="测评人" align="center" prop="nickName" />
        <el-table-column label="预警时间" align="center" prop="warnTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.warnTime, '{y}-{m}-{d}') }}</span>
          </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="interveneNum" />
        <el-table-column label="状态" align="center" prop="interveneStatus">
          <template #default="scope">
            <el-tag v-if="scope.row.interveneStatus == 0" type="primary">无需干预</el-tag>
            <el-tag v-if="scope.row.interveneStatus == 1" type="danger">干预中</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="补充说明" align="center" prop="note" />
        <el-table-column label="操作" align="center" class-name="small-padding" width="330">
          <template #default="scope">
            <el-tooltip content="测评" placement="top">
              <el-button link type="primary" icon="Plus" @click="handlePublish(scope.row)"
                v-hasPermi="['evaluation:record:view']">测评</el-button>
            </el-tooltip>
            <el-tooltip content="测评详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleRecord(scope.row)"
                v-hasPermi="['evaluation:record:view']">测评详情</el-button>
            </el-tooltip>
            <el-tooltip content="处理" placement="top">
              <el-button link type="primary" icon="Pointer" @click="handleUpdate(scope.row)"
                v-hasPermi="['intervene:record:add']">处理</el-button>
            </el-tooltip>
            <el-tooltip content="干预列表" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleList(scope.row)"
                v-hasPermi="['intervene:record:list']">干预列表</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="dialog.visible" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="warnRecordFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="测评人" prop="nickName">
              <el-input disabled v-model="form.nickName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风险等级" prop="situationName">
              <el-input disabled v-model="form.situationName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="预警时间" prop="warnTime">
              <el-input disabled v-model="form.warnTime" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="干预时间" prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="补充说明" prop="note">
              <el-input disabled v-model="form.note" :rows="2" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="诊断说明" prop="diagnose">
              <el-input v-model="form.diagnose" :rows="5" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="0">暂存</el-radio>
                <el-radio :value="1">完成</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="诊断附件" prop="diagnoseAnnex">
              <file-upload v-model="form.diagnoseAnnex" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="是否通知家长" prop="noticeStatus">
              <el-radio-group v-model="form.noticeStatus">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.noticeStatus == 1">
          <el-col :span="24">
            <el-form-item label="通知附件" prop="noticeAnnex">
              <file-upload v-model="form.noticeAnnex" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>

      </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>

    <el-dialog title="干预详情" v-model="listDialog" width="600px" append-to-body :close-on-click-modal="false">
      <el-timeline style="max-width: 600px">
        <el-timeline-item :timestamp="item.time" placement="top" v-for="item in timeList" :key="item.id">
          {{ item.name }}
          <div style="margin-top: 5px;">
            <el-button v-if="item.annex" type="text" @click="downloadFile(item.annex)">下载附件</el-button>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <el-dialog :title="recordDialog.title" v-model="recordDialog.visible" width="800px" append-to-body
      :close-on-click-modal="false">
      <el-tabs v-model="activeName" class="demo-tabs">
        <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="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-tabs>
    </el-dialog>

    <el-dialog title="记录详情" v-model="dialogResult" width="900px" append-to-body @close="handleResultClose">
      <el-tabs v-model="activeFactory">
        <el-tab-pane v-for="des in currentResult" :label="des.factorName" :name="des.id">
          <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-tab-pane>
      </el-tabs>

      <!-- <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="publishDialog.title" v-model="publishDialog.visible" :width="700" append-to-body
      :close-on-click-modal="false">
      <el-form ref="publishFormRef" :model="publishForm" :rules="publishRules" label-width="120px">
        <el-form-item label="测评人" prop="nickName">
          <el-input v-model="publishForm.nickName" disabled />
        </el-form-item>
        <el-form-item label="场次名称" prop="sessionName">
          <el-input v-model="publishForm.sessionName" placeholder="请输入量表名称" />
        </el-form-item>
        <el-form-item label="是否预约发布" prop="status">
          <el-radio-group v-model="publishForm.status">
            <el-radio value="1">是</el-radio>
            <el-radio value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="查看结果" prop="allowQueryResult">
          <el-radio-group v-model="publishForm.allowQueryResult">
            <el-radio value="1">允许</el-radio>
            <el-radio value="0">不允许</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始日期" prop="startTime">
          <el-date-picker v-model="publishForm.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="截止日期" prop="expireTime">
          <el-date-picker v-model="publishForm.expireTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择截止日期" style="width: 100%" />
        </el-form-item>

        <el-form-item label="量表" prop="scaleIds">
          <el-select multiple v-model="publishForm.scaleIds" placeholder="请选择量表" style="width: 100%">
            <el-option v-for="item in scaleOptions" :key="item.scaleId" :label="item.scaleName" :value="item.scaleId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitPublishForm">确 定</el-button>
          <el-button @click="cancelPublish">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WarnRecord" lang="ts">
import { listWarnRecord, getEvaluationList } from '@/api/archive/warnRecord';
import { WarnRecordVO, WarnRecordQuery, WarnRecordForm } from '@/api/archive/warnRecord/types';
import { listStatistic } from '@/api/archive/information';
import { addInterveneRecord, listInterveneTimes } from '@/api/archive/interveneRecord';
import { findAll } from '@/api/scale/SysScale';
import { listPublish, addScalePublish } from '@/api/scale/scalePublish';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { yzd } = toRefs<any>(proxy?.useDict('yzd'));

const warnRecordList = ref<WarnRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

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

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

const statusOption = ref([
  {
    value: 0,
    label: '无需干预',
  },
  {
    value: 1,
    label: '干预中',
  }
])

const recordDialog = reactive<DialogOption>({
  visible: false,
  title: '测评记录'
});

const publishDialog = reactive<DialogOption>({
  visible: false,
  title: '量表个测发布'
})

const listDialog = ref(false)
const activeName = ref('static')

const activeFactory = ref('')

const initFormData: WarnRecordForm = {
  warnId: undefined,
  batchNo: undefined,
  userId: undefined,
  status: 0,
  note: undefined,
  warnTime: undefined
}
const data = reactive<PageData<WarnRecordForm, WarnRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    batchNo: undefined,
    userId: undefined,
    status: undefined,
    note: undefined,
    warnTime: undefined,
    startTime: undefined,
    endTime: undefined,
    interveneStatus: undefined,
    nickName: undefined,
    params: {
    }
  },
  rules: {
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    diagnose: [
      { required: true, message: "诊断说明不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "干预时间不能为空", trigger: "blur" }
    ]
  }
});

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

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 publishList = ref([]);
async function getPublishList() {
  const res = await listPublish()
  publishList.value = res.data
}

/** 查询预警记录列表 */
const getList = async () => {
  loading.value = true;
  const warnArr = queryParams.value.warnTime
  if (warnArr && warnArr.length > 0) {
    queryParams.value.startTime = warnArr[0]
    queryParams.value.endTime = warnArr[1]
  }
  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 = () => {
  queryParams.value.nickName = undefined
  queryParams.value.interveneStatus = undefined
  queryParams.value.warnTime = undefined
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 修改按钮操作 */
const handleUpdate = async (row?: WarnRecordVO) => {
  reset();
  form.value.batchNo = row?.batchNo
  form.value.userId = row?.userId
  form.value.nickName = row?.nickName
  form.value.warnTime = row?.warnTime
  form.value.situationName = handleSituation(row?.situation)
  form.value.situation = row?.situation
  form.value.note = row?.note

  dialog.title = "处理详情";
  dialog.visible = true
}

const timeList = ref<any[]>([])
async function handleList(row: any) {
  const userId = row.userId
  const res = await listInterveneTimes({ userId })
  timeList.value = res.data

  listDialog.value = true
}

/** 提交按钮 */
const submitForm = () => {
  warnRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      await addInterveneRecord(form.value).finally(() => buttonLoading.value = false);

      proxy?.$modal.msgSuccess("处理成功");
      dialog.visible = false;
      await getList();
    }
  });
}

const staticQuery = ref({
  userId: '',
  pageNum: 1,
  pageSize: 10
})
const staticTotal = ref(0)
const staticList = ref<any[]>([])
const current = ref({ userId: '', nickName: '' })
const handleRecord = async (row?: any) => {
  staticQuery.value.userId = row.userId;

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

  getStaticList()

  recordDialog.visible = true;
}

const publishFormRef = ref()
const publishForm = ref<any>({})
const publishRules = ref({

})
const scaleOptions = ref<any[]>([]);
const getScaleOptions = async () => {
  const res = await findAll({ status: 1 });
  scaleOptions.value = res.data;
}
const handlePublish = async (row?: any) => {
  publishDialog.visible = true
  publishForm.value.userIds = [row.userId]
  publishForm.value.publishType = 0
  publishForm.value.nickName = row.nickName

  getScaleOptions()
}

const submitPublishForm = () => {
  publishFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addScalePublish(publishForm.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess("发布成功");
      publishDialog.visible = false;
      await getList();
    }
  });
}

const cancelPublish = () => {
  publishForm.value = {};
  publishFormRef.value?.resetFields();
  publishDialog.visible = false;
}

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

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

  activeFactory.value = result.data[0].id
}

function handleResultClose() {
  currentResult.value = []
  activeFactory.value = ''
}

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}.pdf`)
}

function downloadFile(ossId) {
  proxy?.$download.oss(ossId)
}

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

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