<template>
  <div class="recordsContent">
    <div class="headertop flex justify-between" style="align-items: center">
      <div class="header left flex content-center" style="align-items: center;flex-direction: row-reverse">
        <div class="headerTitle">
          <div
            class="edit"
            style="white-space: nowrap; text-overflow: ellipsis"
          >
            勘 验 笔 录
          </div>
          <div class="span" :title="caseInfo.caseTitle">
            {{ caseInfo.caseTitle }}
          </div>
        </div>
        <!-- <el-icon style="margin: 0 40px" size="40px"><Download /></el-icon> -->
        <el-icon title="返回" style="margin-right: 10px; cursor: pointer;" size="24px" @click="backPageHandler"><ArrowLeftBold /></el-icon>
        <!-- <el-button @click="backPageHandler">返回</el-button>
        <el-button style="margin: 0px 10px" type="primary" @click="handleSave"
          >保存</el-button
        >
        <el-button :disabled="isDisableExport" @click="handleExport"
          >导出</el-button
        > -->
      </div>
      <div class="headerRight flex" style="align-items: center">
        <div
          @click="handleShowAi"
          v-if="showAI"
          style="
            color: #26559b;
            cursor: pointer;
            font-size: 24px;
            font-weight: bold;
            margin-right: 20px;
          "
          >AI</div
        >
        <el-icon title="下载" v-if="!isDisableExport" @click="handleExport" style="cursor: pointer; margin: 0 40px" size="24px"><Download /></el-icon>
        <el-button style="margin: 0px 10px  0px 0px" type="primary" @click="handleSave"
          >保存</el-button
        >
      </div>
    </div>
    <div class="records">
      <h3 class="title">现 场 勘 验 笔 录</h3>

      <div class="content">
        <div class="line" style="flex-direction: row-reverse">
          <el-input
            class="input"
            v-model="data.inquestNum"
            placeholder=""
            style="width: 280px"
          />
          <span>现场勘验号:</span>
        </div>

        <div class="line">
          <span>现场勘验单位:</span>
          <el-input
            class="input"
            v-model="data.deptName"
            placeholder=""
            style="width: 100%"
          />
        </div>

        <div class="line">
          <span>指派/报告单位:</span>
          <el-input
            class="input"
            v-model="data.reportDept"
            placeholder=""
            style="width: 100%"
          />
        </div>

        <div class="line">
          <span>勘验时间: &nbsp; </span>
          <div>
            <el-date-picker
              class="input"
              v-model="data.inquestTime"
              type="datetime"
              placeholder="勘验时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 200px"
            />
          </div>
        </div>
        <div class="textarea">
          <span>勘验事由： </span>
          <el-input
            type="textarea"
            :rows="6"
            v-model="data.inquestResource"
            placeholder="报警人：xxx（性别：xxx 电话：xxx）报警称：xxx发生一起：xxx案，现场需勘察。接报后技术科科长：xxx带领技术员：xxx、法医：xxx立即赶赴现场进行勘察."
            style="width: 100%"
          />
        </div>
        <div class="line">
          <span>现场勘验时间: &nbsp; </span>
          <div>
            <el-date-picker
              class="input"
              v-model="data.times"
              type="datetimerange"
              range-separator="至"
              start-placeholder="现场勘验开始时间"
              end-placeholder="现场勘验结束时间"
            />
          </div>
        </div>

        <div class="line">
          <span>现场地点:</span>
          <el-input
            class="input"
            type="text"
            v-model="data.address"
            placeholder=""
            style="width: 100%"
          />
        </div>

        <div class="line">
          <span>现场保护情况:</span>
          <el-input
            class="input"
            type="text"
            v-model="data.protectionSituation"
            placeholder=""
            style="width: 100%"
          />
        </div>

        <div class="line">
          <span>现场保护人: &nbsp;&nbsp; &nbsp;</span>
          <span>姓名</span>
          <!-- 单位 XX派出所 职务 一级警长 -->
          <el-input
            class="input"
            type="text"
            v-model="data.protector.name"
            placeholder=""
            style="width: 180px"
          />
          <span>单位</span>
          <el-input
            class="input"
            type="text"
            v-model="data.protector.unit"
            placeholder=""
            style="width: 200px"
          />
          <span>职务</span>
          <el-input
            class="input"
            type="text"
            v-model="data.protector.job"
            placeholder=""
            style="width: 200px"
          />
        </div>
        <!-- protectionMeasures -->
        <div class="line">
          <span>保护措施：&nbsp; </span>
          <el-checkbox-group v-model="data.protectionMeasures">
            <el-checkbox :value="0" label="专人看护现场，防止他人进入" />
            <el-checkbox :value="1" checked label="设立警戒带，划定禁行区域" />
            <el-checkbox :value="2" label="其他措施" />
          </el-checkbox-group>
        </div>
        <div class="line">
          <span>现场情况： &nbsp; </span>
          <el-checkbox-group v-model="data.situation">
            <el-checkbox :value="0" label="原始现场" />
            <el-checkbox :value="1" checked label="变动现场" />
          </el-checkbox-group>
        </div>
        <!-- changeReason -->
        <div class="line">
          <span>变动原因： &nbsp; </span>
          <el-checkbox-group v-model="data.changeReason">
            <el-checkbox
              v-for="reason in ChangeReasonType"
              :value="reason.id"
              :label="reason.name"
            >
            </el-checkbox>
            <!-- <el-checkbox :value="0" label="事主进入" />
          <el-checkbox :value="1" label="报案人进入" />
          <el-checkbox :value="2" label="其他" /> -->
          </el-checkbox-group>
          <el-input
            class="input"
            v-model="data.changeReasonOtherValue"
            :disabled="!data.changeReason.includes(2)"
            style="margin-left: 20px; width: 200px"
          />
        </div>

        <div class="line">
          <span>天气： &nbsp; </span>
          <el-checkbox-group v-model="data.weatherInfo.type">
            <el-checkbox :value="0" label="阴" />
            <el-checkbox :value="1" label="晴" />
            <el-checkbox :value="2" label="雨" />
            <el-checkbox :value="3" label="雾" />
          </el-checkbox-group>
          <span style="margin-left: 20px; font-size: 12px">温度： &nbsp;</span>
          <el-input
            class="input"
            v-model="data.weatherInfo.temperature"
            style="width: 80px"
          /><span>℃</span>
          <span style="margin-left: 20px; font-size: 12px">湿度： &nbsp;</span>
          <el-input
            class="input"
            v-model="data.weatherInfo.humidity"
            style="width: 80px"
          /><span>%</span>
          <span style="margin-left: 20px; font-size: 12px">风向： &nbsp;</span>
          <el-input
            class="input"
            v-model="data.weatherInfo.windDirection"
            style="width: 80px"
          />
        </div>

        <div class="line">
          <span>现场勘验利用的光线： &nbsp; </span>
          <el-checkbox-group v-model="data.light">
            <el-checkbox :value="0" checked label="自然光" />
            <el-checkbox :value="1" checked label="灯光" />
            <el-checkbox :value="2" label="特种光" />
          </el-checkbox-group>
        </div>

        <div class="line">
          <span>现场勘验指挥人： &nbsp;&nbsp; </span>
          <span>姓名</span>
          <!-- 单位 XX派出所 职务 一级警长 -->
          <el-input
            class="input"
            type="text"
            v-model="data.inquestCommander.name"
            placeholder=""
            style="width: 180px"
          />
          <span>单位</span>
          <el-input
            class="input"
            type="text"
            v-model="data.inquestCommander.unit"
            placeholder=""
            style="width: 200px"
          />
          <span>职务</span>
          <el-input
            class="input"
            type="text"
            v-model="data.inquestCommander.job"
            placeholder=""
            style="width: 200px"
          />
        </div>

        <div class="textarea">
          <div>
            <span>现场勘验情况 ：</span>
            <!-- <span @click="handleShowAi" style="color:#26559B;cursor: pointer;float: right;font-weight: bold;">AI</span> -->
          </div>
          <el-input
            type="textarea"
            :rows="6"
            v-model="data.inquestSituation"
            placeholder=""
            style="width: 100%"
          />
        </div>

        <div class="line">
          <span>现场勘验制图&nbsp; </span>
          <el-input-number
            class="input"
            controls-position="right"
            v-model="data.imageNum"
            style="width: 130px"
          />
          <span>张; &nbsp;&nbsp;</span>
          <span>照相</span>
          <el-input-number
            class="input"
            controls-position="right"
            v-model="data.photographNum"
            style="width: 130px"
          />
          <span>张;&nbsp;&nbsp;</span>
          <span>摄像</span>
          <el-input-number
            class="input"
            controls-position="right"
            v-model="data.photographyMinNum"
            style="width: 130px"
          />
          <span>分</span>
          <el-input-number
            class="input"
            controls-position="right"
            v-model="data.photographySecNum"
            style="width: 130px"
          />
          <span>秒</span>
          <span style="margin-left: 10px">录音</span>
          <el-input-number
            class="input"
            controls-position="right"
            v-model="data.recordingMinNum"
            style="width: 130px"
          />
          <span>分</span>
          <el-input-number
            class="input"
            controls-position="right"
            v-model="data.recordingSecNum"
            style="width: 130px"
          />
          <span>秒</span>
        </div>
        <div class="line">
          现场勘验记录人员：
          <el-button link @click="recorderInfoDialogShow = true"
            ><el-icon :size="18"><CirclePlus /> </el-icon>
          </el-button>
        </div>

        <!-- 现场勘验记录人员 -->
        <template v-for="(info, index) in data.recorderInfo">
          <div class="line info">
            <span>{{ info.typeLabel }}： &nbsp;&nbsp; </span>
            <span>姓名</span>
            <!-- 单位 XX派出所 职务 一级警长 -->
            <el-input
              class="input"
              type="text"
              v-model="info.name"
              placeholder=""
              style="width: 180px"
            />
            <span>单位</span>
            <el-input
              class="input"
              type="text"
              v-model="info.unit"
              placeholder=""
              style="width: 200px"
            />
            <span>职务</span>
            <el-input
              class="input"
              type="text"
              v-model="info.job"
              placeholder=""
              style="width: 200px"
            />
            <el-button
              link
              class="del-btn"
              type="danger"
              @click="removeRecorderInfo(index)"
              ><el-icon :size="18"><CircleClose /> </el-icon>
            </el-button>
          </div>
        </template>

        <div class="line">
          现场勘验人员：
          <el-button link @click="addSignatureInfo"
            ><el-icon :size="18"><CirclePlus /> </el-icon>
          </el-button>
        </div>
        <template v-for="(sign, index) of data.signatureInfo">
          <div class="line info">
            <span>本人签名： &nbsp;&nbsp; </span>
            <span>_______________ &nbsp;&nbsp;</span>

            <span>单位</span>
            <el-input
              class="input"
              type="text"
              v-model="sign.unit"
              placeholder=""
              style="width: 200px"
            />
            <span>职务</span>
            <el-input
              class="input"
              type="text"
              v-model="sign.job"
              placeholder=""
              style="width: 200px"
            />
            <el-button
              class="del-btn"
              link
              type="danger"
              @click="removeSignatureInfo(index)"
              ><el-icon :size="18"><CircleClose /> </el-icon>
            </el-button>
          </div>
        </template>

        <div class="line">
          现场勘验见证人：

          <el-button link @click="addWitnessInfo"
            ><el-icon :size="18"><CirclePlus /> </el-icon>
          </el-button>
        </div>
        <template v-for="(witness, index) of data.witnessInfo">
          <div class="line info">
            <span>本人签名： &nbsp;&nbsp; </span>
            <span>_______________ &nbsp;&nbsp;</span>
            <span>性别</span>
            <el-select
              class="input"
              v-model="witness.sex"
              placeholder="性别"
              style="width: 140px"
            >
              <el-option :value="0" label="男" />
              <el-option :value="1" label="女" />
            </el-select>
            <span>出生日期</span>
            <el-date-picker
              class="input"
              v-model="witness.birthday"
              type="date"
              placeholder="出生日期"
              style="width: 180px"
            />
            <!-- <el-input
            class="input"
            type="text"
            v-model="witness.birthday"
            placeholder=""
            style="width: 200px"
          /> -->
            <span>住址</span>
            <el-input
              class="input"
              type="text"
              v-model="witness.address"
              placeholder=""
              style="width: 260px"
            />
            <el-button
              link
              class="del-btn"
              type="danger"
              @click="removeWitnessInfo(index)"
              ><el-icon :size="18"><CircleClose /> </el-icon>
            </el-button>
          </div>
        </template>

        <div class="textarea">
          <span>备注：</span>
          <el-input
            type="textarea"
            :rows="6"
            v-model="data.remark"
            placeholder=""
            style="width: 100%"
          />
        </div>

        <div></div>
      </div>
      <el-dialog
        v-model="recorderInfoDialogShow"
        title="增加现场勘验记录人员"
        width="500"
        align-center
        @close="recorderInfoDialogSelect = null"
      >
        <div
          class="border"
          style="
            width: 500px;
            height: 1px;
            margin-bottom: 20px;
            border-bottom: none;
            position: relative;
            left: -16px;
          "
        ></div>
        <div style="width: 80%; margin: 30px auto">
          <el-select
            v-model="recorderInfoDialogSelect"
            placeholder="请选择现场勘验记录人员"
            size="large"
          >
            <el-option
              v-for="item in recorderInfoType"
              :key="item.type"
              :label="item.typeLabel"
              :value="item.type"
            />
          </el-select>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="addRecorderInfo">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog
        v-model="aiImgShow"
        title="AI识别平面图"
        width="1300px"
        align-center
        @close="aiImgData.result = null"
      >
        <div
          class="border"
          style="
            width: 1300px;
            height: 1px;
            margin-bottom: 20px;
            border-bottom: none;
            position: relative;
            left: -16px;
          "
        ></div>
        <div
          class="flex space-x-4 items-center content-center justify-center text-center"
        >
          <div class="flex-1" style="width: 80%">
            <el-select
              v-model="aiImgData.src"
              placeholder="请选择平面图"
              :disabled="isOption"
              style="display: block"
              @change="handleSelect"
              size="large"
            >
              <el-option
                v-for="item in aiImgData.list"
                :key="item.num"
                :label="item.title"
                :disabled="!item.viewAuth"
                :value="item.url"
              />
            </el-select>
            <div
              class="viewImg mt-4 text-center"
              style="
                height: 400px;
                line-height: 400px;
                border-radius: 0px 0px 0px 0px;
                border: 1px solid #d9d9d9;
              "
            >
              <img
                class="w-full h-full object-cover"
                v-if="aiImgData.src"
                :src="aiImgData.src"
                alt=""
              />
              <span v-else>预览选中的平面图</span>
            </div>
          </div>
          <div
            class="flex-1 text-center content-start"
            style="
              border-radius: 0px 0px 0px 0px;
              border: 1px solid #d9d9d9;
              min-height: 450px;
            "
          >
            <span style="line-height: 450px" v-if="aiImgData.loading"
              >识别中，请稍后...</span
            >
            <span style="line-height: 450px" v-else-if="!aiImgData.result"
              >请点击【识别】获取结果</span
            >
            <div
              class="text-left"
              style="
                height: 450px;
                padding: 10px;
                overflow: auto;
                white-space: pre-wrap;
              "
              v-else
              v-html="aiImgData.result"
            ></div>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer text-center flex">
            <div style="width: 50%">
              <el-button
                type="primary"
                :disabled="isOption || !aiImgData.src || aiImgData.loading"
                @click="handleAI"
              >
                识别
              </el-button>
            </div>
            <div style="width: 50%">
              <el-button
                :disabled="isOption || !aiImgData.result"
                @click="handleCopy"
              >
                复制
              </el-button>
            </div>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, watch, h, computed } from "vue";
import { reactive } from "vue";
import { router, RouteName } from "@/router";
import {
  getCaseInquestInfo,
  saveCaseInquestInfo,
  exportCaseInquestInfo,
  getCaseInquestInfoOld,
  getAiByImage,
  getCaseInfoData,
  getFloorList,
} from "@/store/case";
import { ElMessage, ElMessageBox } from "element-plus";
import saveAs from "@/util/file-serve";
import { CirclePlus, CircleClose, MagicStick, Download } from "@element-plus/icons-vue";
import { recorderInfoType, ChangeReasonType } from "./formData.ts";
import { confirm } from "@/helper/message";
import { chat, abort, listModels } from "@/util/ollama";
import { createSSEPostClient  } from "@/util/ssePost";
import { copyTextToClipboard } from "@/util/index";
const props = defineProps({ caseId: Number, title: String });
let sseClient = null;
console.log("router.currentRoute", router.currentRoute.value?.params);
const fileId = computed(() => router.currentRoute.value?.params?.fileId);
const caseId = computed(() => router.currentRoute.value?.params?.caseId);
const showAI = computed(() => router.currentRoute.value?.query?.show);
const isDisableExport = ref(false);
const aiImgShow = ref(false);
const isOption = ref(false);
const aiImgData = ref({
  src: "",
  Aisrc: "",
  result: ``,
  loading: false,
  list: [],
});
const caseInfo = computed(() => getCaseInfoData());
const messages = ref([])
const isConnected = ref();
const data = reactive({
  title: "",
  inquestNum: "", //现场勘验号
  deptName: "", //单位名称
  sendDept: "", //发送单位
  issuanceCount: "", // 份数
  makeTime: "", //制作时间
  recorder: "", // 笔录人
  issuanceOpinion: "", //签发意见
  reportDept: "", //报告单位
  times: [], // startTime ,endTime
  address: "", // 勘验地址
  inquestTime: "", //勘验时间
  inquestResource:
    "x年x月x日x单位接到报警称;x年x月x日x地点发生一起什么案事件，需要勘验现场， 接通知后，技术员xx,xx前往现场考察", //勘验范围
  protector: {
    name: "",
    unit: "",
    job: "",
  }, // 现场保护人
  protectionSituation: "", // 现场保护情况
  situation: [], //现场情况
  changeReason: [],
  changeReasonOtherValue: "",
  protectionMeasures: [], //保护措施
  weatherInfo: {
    type: [],
    temperature: "",
    humidity: "",
    windDirection: "",
  }, //天气情况
  light: [], //光线
  painter: "",
  photographer: "",
  inquestCommander: {
    name: "",
    unit: "",
    job: "",
  }, //现场勘验指挥人
  inquestSituation:
    "案发现场以XXX小区为中心，东侧为XXX路，西侧是XXX街，北侧为XXX路，南侧是XXX路。", //现场勘验情况
  imageNum: 0, //现场勘验制图数量
  photographNum: 0, //照相数量
  photographyMinNum: 0, //摄影数量
  photographySecNum: 0, //摄影数量
  recordingMinNum: "",
  recordingSecNum: "",
  recorderInfo: JSON.parse(JSON.stringify(recorderInfoType)),
  signatureInfo: [], //现场勘验人员
  witnessInfo: [],
  remark: "",
});
const signatureInfoNum = 4;
const witnessInfoNum = 2;
const recorderInfoDialogShow = ref(false);
const recorderInfoDialogSelect = ref();
const initInfo = async (inquestFileId) => {
  const res = await getCaseInquestInfoOld(inquestFileId || fileId.value);
  console.log("initInfo", res);
  if (!res.data) {
    isDisableExport.value = true;
  } else {
    isDisableExport.value = false;
  }
  for (var k in data) {
    if (res.data && res.data.hasOwnProperty(k)) {
      // console.log("Key is " + k);
      if (res.data[k]) {
        data[k] = res.data[k];
      }
    }
  }
  console.log("data", data, res.data);
  setTimeout(() => {
    initSignatureAndWitInfo();
  }, 500);
};
const handleCopy = () => {
  copyTextToClipboard(aiImgData.value.result);
  ElMessage.success("复制成功！");
};
const handleShowAi = async () => {
  const list = await getFloorList(caseId.value);
  aiImgData.value.list = list.filter((i) => i.url);
  let item = list.find(ele => ele.viewAuth) || {}
  aiImgData.value.src = aiImgData.value.src
    ? aiImgData.value.src
    : item.url;
  aiImgData.value.Aisrc = item.freeSpaceUrl
  aiImgData.value.loading = false;
  aiImgShow.value = true;
  isOption.value = false;
};
//判断是否deepseek
let isThink = ref(false);
let testRegex = /deepseek/;
const handleAI = async () => {
  aiImgData.value.loading = true;
  aiImgData.value.result = "";
  isOption.value = true;
  // const item = aiImgData.value.list.find((i) => i.url == aiImgData.value.src);
  initSSE(aiImgData.value.Aisrc || aiImgData.value.src)
  // try {
  // const res = await getAiByImage({imageUrl: imageUrl})
  //   chat("", item.params + item.paramContent).then(async (stream) => {
  //     if (!aiImgShow.value) {
  //       abort();
  //     }
  //     for await (const part of stream) {
  //       // chatHistory.value.at(idx).text += part.message.content;
  //       let tep_mesg = part.message.content;
  //       console.log("isThinktep", tep_mesg);
  //       //判断是否是deepseek模型
  //       // if (testRegex.test(agentInfo.value.model)) {
  //       if (tep_mesg == "\u003c/think\u003e") {
  //         // isThink.value = true;
  //         aiImgData.value.loading = false;
  //       }
  //       if (!aiImgData.value.loading) {
  //         //清除think
  //         if (
  //           tep_mesg == "\u003cthink\u003e" ||
  //           tep_mesg == "\u003c/think\u003e"
  //         ) {
  //           // chatHistory.value.at(idx).think += "";
  //         } else {
  //           console.log("isThinktep_mesg", tep_mesg);
  //           aiImgData.value.result += tep_mesg;
  //           // chatHistory.value.at(idx).think += tep_mesg;
  //         }
  //         //如果结尾标签则停止拼接
  //         if (tep_mesg == "\u003c/think\u003e") {
  //           // isThink.value = false;
  //         }
  //       } else {
  //         // aiImgData.value.result += tep_mesg;
  //         // chatHistory.value.at(idx).text += tep_mesg;
  //       }
  //       // } else {
  //       //   // chatHistory.value.at(idx).text += tep_mesg;
  //       //   aiImgData.value.result += tep_mesg;
  //       // }
  //       // autoScrollSwitch.value && scrollToBottom(true);
  //     }
  //     isOption.value = false;
  //     console.log("handleAI完成", aiImgData.value.result);
  //   });
  //   // console.log("handleAI", res)
  //   // aiImgData.value.result = res
  //   // aiImgData.value.loading = false
  // } catch (error) {
  //   console.log("handleAI", error);
  //   aiImgData.value.loading = false;
  // }
};
const handleSelect = (val, itme) => {
  aiImgData.value.result = false;
  aiImgData.value.result = ''
}
const initSSE = (url) => {
  // 销毁旧连接（避免重复连接）
  if (sseClient) {
    sseClient.close();
  }
 sseClient = createSSEPostClient({
    // headers: {
    //   Authorization: `Bearer ${localStorage.getItem('token')}`, // 认证 Token
    // },
    body: {
      "inputs": {
        "img": {
          "type": "image",
          "transfer_method": "remote_url",
          "url": window.location.origin + url
        }
      },
      "response_mode": "streaming",
      "user": "web-4dage"
    }
  });

  // 监听连接成功
  sseClient.on('open', () => {
    isConnected.value = true;
    console.log('POST SSE 连接成功');
  });

  // 监听默认消息事件（服务器未指定 event 时）
  sseClient.on('message', ({data, outputs}) => {
    console.log('message连接成功', data);
    if(data && data.text){
      aiImgData.value.result += data.text
      aiImgData.value.loading = false
    }
    if(outputs && outputs.text){
      aiImgData.value.result = outputs.text
    }
  });

  // // 监听自定义事件（服务器指定 event: customEvent）
  // sseClient.on('customEvent', (data) => {
  //   messages.value.push({ type: '自定义事件', data });
  // });

  // 监听错误
  sseClient.on('error', (err) => {
    isOption.value = false;
    messages.value.push({ type: '错误', data: err.message });
    console.error('POST SSE 错误：', err);
    ElMessage.error("AI服务未开通，该功能暂不可用");
    aiImgData.value.loading = false
    aiImgData.value.result = false;
    aiImgData.value.result = ''
  });

  // 监听连接关闭
  sseClient.on('close', () => {
    isOption.value = false;
    console.log('POST SSE 连接关闭');
  });

  // 建立连接
  sseClient.connect();
};
const initSignatureAndWitInfo = () => {
  (data.recorderInfo.length === 0 || !data.recorderInfo) &&
    (data.recorderInfo = [...recorderInfoType, recorderInfoType[4]]);

  (data.signatureInfo.length === 0 || !data.signatureInfo) &&
    Array.from(new Array(signatureInfoNum)).forEach(() => {
      data.signatureInfo.push({
        unit: "",
        job: "",
      });
    });

  (data.witnessInfo.length === 0 || !data.witnessInfo) &&
    Array.from(new Array(witnessInfoNum)).forEach(() => {
      data.witnessInfo.push({
        sex: 0,
        birthday: "",
        address: "",
      });
    });
};

onMounted(() => {
  // listModels().then((res) => {
  //   console.log("listModels", res);
  // });
  initInfo();
});

const addRecorderInfo = () => {
  recorderInfoDialogShow.value = false;
  if (recorderInfoDialogSelect.value || recorderInfoDialogSelect.value === 0) {
    const newCrew = recorderInfoType.find(
      (i) => i.type === recorderInfoDialogSelect.value
    );
    data.recorderInfo.push({
      ...newCrew,
      job: "",
      name: "",
      unit: "",
    });
    // debugger;
  }
};
const removeRecorderInfo = async (index) => {
  if (await confirm("确定要删除此数据？")) {
    data.recorderInfo.splice(index, 1);
  }
};
const addSignatureInfo = async () => {
  if (await confirm("确定要添加新的现场勘验人员？")) {
    data.signatureInfo.push({
      unit: "",
      job: "",
    });
  }
};
const removeSignatureInfo = async (index) => {
  if (await confirm("确定要删除此数据？")) {
    data.signatureInfo.splice(index, 1);
  }
};
const addWitnessInfo = async () => {
  if (await confirm("确定要添加新的现场勘验见证人？")) {
    data.witnessInfo.push({
      sex: 0,
      birthday: "",
      address: "",
    });
  }
};
const backPageHandler = () => {
  router.back();
};
const removeWitnessInfo = async (index) => {
  if (await confirm("确定要删除此数据？")) {
    data.witnessInfo.splice(index, 1);
  }
};

const handleSave = async () => {
  console.log("data", data);

  for (var k in data) {
    if (data && data.hasOwnProperty(k)) {
      // console.log("Key is " + k);
      if (Array.isArray(data[k])) {
        data[k] = data[k].sort((a, b) => a - b);
      }
    }
  }
  let inquestFileId = fileId.value == -1 ? "" : fileId.value;
  let params = { ...data, caseId: caseId.value, inquestFileId };
  const res = await saveCaseInquestInfo(params);
  initInfo(res.data.inquestFileId);
  console.log("saveCaseInquestInfo", res);
  if (fileId.value == -1) {
    router.replace({
      name: RouteName.records,
      params: { caseId: caseId.value, fileId: res.data?.inquestFileId },
    });
    return;
  }
  if (res.code === 0) {
    ElMessage.success("保存成功！");
  }
};
const handleExport = async () => {
  let inquestFileId = fileId.value == -1 ? "" : fileId.value;
  let params = { ...data, caseId: caseId.value, inquestFileId };
  await saveCaseInquestInfo(params);
  const res = await exportCaseInquestInfo(fileId.value);
  console.log("res", res);
  saveAs(res, `勘验笔录.docx`);
};
</script>

<style lang="scss" scoped>
.el-popper {
  max-width: 100% !important;
}
.records {
  max-width: 1024px;
  margin: 0 auto;
  padding: 64px 48px;
  position: relative;
  background: #fff;
  .header {
    display: flex;
    justify-content: flex-endTime;
    position: sticky;
    top: 10px;
    z-index: 1000;
    background-color: white;
  }

  .input {
    height: 32px;
    line-height: 32px;
    margin: 0 8px;
  }

  .textarea {
    margin-right: 8px;
    margin-bottom: 20px;

    span {
      padding: 10px 0;
      display: inline-block;
    }

    // margin: 0 8px;
  }

  .line {
    display: inline-flex;
    width: 100%;
    flex-direction: row;
    align-items: center;
    margin-bottom: 24px;
    line-height: 38px;

    span {
      white-space: nowrap;
    }
  }
}

.title {
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
  color: rgba(0,0,0,0.85);
  line-height: 24px;
}

.sub-tit {
  display: inline-block;
  padding-bottom: 20px;
}

.info {
  display: block;

  .inner {
    display: flex;
    flex-direction: row;
    width: 100%;

    .input {
      flex: 1;
    }

    .sec {
      flex: 1;
      display: inline-flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.witnessInfo {
  background: #f5f5f5;
  padding: 15px;
  margin-top: 20px;
  margin-right: 8px;
}

.gap {
  margin: 15px 0;
}

.btn-container {
  padding: 20px 0;

  .btn {
    color: #26559b;
    width: 100%;

    &:hover {
      background: #f5f5f5;
      border-color: #dcdfe6;
    }
  }
}
.info {
  .del-btn {
    display: none;
  }
  &:hover {
    .del-btn {
      display: block;
    }
  }
}
.recordsContent{
  .headertop{
  background: #fff;
    padding: 40px 40px 24px 40px;
    margin-bottom: 20px;
    .headerTitle{
      display: flex;
      font-weight: 400;
            line-height: 32px;
      font-size: 32px;
      color: rgba(0,0,0,0.85);
      text-align: left;
      font-style: normal;
          .edit {
      margin: 0 12px 0 0px;
      padding: 0 12px 0 0px;
      border-right: 1px solid #ECECEC;
    }
    }
  }
}
</style>
