<template>
  <div class="container">
    <el-row :gutter="20" class="el_row">
      <el-col :span="17">
        <div class="map-content">
          <div class="map" id="mapcontainer"></div>
          <div class="chart">
            <div class="title">设备生理数据</div>
            <div ref="chartRef" style="width: 100%; height: 100%"></div>
          </div>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="right-content">
          <div class="info scrollbar">
            <div class="info-text">IMEI号：{{ curData.deviceId }}</div>
            <div class="info-text">告警时间：{{ curData.createTime }}</div>
            <div class="info-text">
              告警类型：<span style="color: red">{{ warnTypeEnum[curData.warnType] }}</span>
            </div>
            <div class="info-text">绑定关联人名称：{{ curData.username }}</div>
            <div class="info-text">绑定关联人警号：{{ curData.userNumber }}</div>
            <div class="info-text">
              状态：
              <el-tag :type="curData.status == 1 ? 'success' : 'danger'">
                {{ statusEnum[curData.status] }}
              </el-tag>
            </div>
            <div class="info-text">紧急电话：{{ curData.adminPhone }}</div>
            <div class="info-text">隶属辖区：{{ curData.orgName }}</div>

            <div class="info-box" v-if="curData.type == 1">
              <div class="info-box-title">生理指标</div>
              <div class="info-box-contetn">
                <div class="item">
                  <div class="label">&nbsp;&nbsp;当前指标：</div>
                  <div class="value">{{ curData.value }}{{ unitEnum[curData.warnType] }}</div>
                </div>
                <div class="item" v-if="curData.warnType != 5">
                  <div class="label">&nbsp;&nbsp;最大值：</div>
                  <div class="value">{{ curData.maxValue }}{{ unitEnum[curData.warnType] }}</div>
                </div>
                <div class="item">
                  <div class="label">&nbsp;&nbsp;最小值：</div>
                  <div class="value">{{ curData.minValue }}{{ unitEnum[curData.warnType] }}</div>
                </div>
              </div>
            </div>

            <div class="info-form">
              <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-position="top">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="处理人：" prop="name">
                      <el-input v-model="ruleForm.name" clearable :disabled="disabled" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="警号：" prop="username">
                      <el-input v-model="ruleForm.username" clearable :disabled="disabled" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="处理记录：" prop="content">
                  <el-input v-model="ruleForm.content" clearable :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" :disabled="disabled" />
                </el-form-item>
                <!-- <el-form-item label="处理图片：" prop="images">
                  <Upload v-model="ruleForm.images" :disabled="disabled" />
                </el-form-item> -->
              </el-form>
            </div>
          </div>
          <div class="right-foot" v-if="!disabled">
            <el-button type="primary" @click="submitForm(ruleFormRef)" :disabled="disabled">保存</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
    <div :style="{ display: 'none' }">
      <InfoWindow class="infoBox" :value="locationInfo" @close="InfoWin.close()" />
    </div>
  </div>
</template>

<script setup lang="ts" name="incidentDispose">
import location from "@/assets/img/location.png";
import { MapCustom } from "@/utils/mapCustom";
import { onMounted, ref, reactive, watch, onDeactivated, onUnmounted } from "vue";
import Upload from "@/components/upload-img.vue";
import * as echarts from "echarts";
import { warningDetail, warningConfirm } from "@/api/index";
import { TWarningConfirm, TWarningDetail } from "@/api/index.d";
import { useRoute } from "vue-router";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { debounce, format } from "@/utils";

// 定义一个响应式变量
enum unitEnum {
  "次/分" = 4,
  "%",
  "℃",
}
enum statusEnum {
  "待处理",
  "已处理",
}
enum warnTypeEnum {
  "SOS告警",
  "围栏告警",
  "破坏告警",
  "低电告警",
  "心率告警",
  "血氧告警",
  "体温告警",
}
const { query } = useRoute();
const chartRef = ref(null);
const disabled = ref(false);
const ruleFormRef = ref<FormInstance>();
let map = null;
let myChart = null;
let InfoWin = null;
let locationInfo = ref({});

const options = {
  tooltip: {
    trigger: "axis",
    formatter: function (params) {
      let unit = { 0: "次/分", 1: "%", 2: "℃" };
      var res = format(Number(params[0].name)) + "<br/>";
      res += params
        .map(function (param, index) {
          return param.marker + param.seriesName + "：" + param.value + unit[index] + "<br/>";
        })
        .join("");
      return res;
    },
  },
  legend: {
    data: ["心率", "体表温度", "血氧"],
  },
  grid: {
    left: "0%",
    right: "4%",
    bottom: "6%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: [],
    axisLabel: {
      formatter: function (item) {
        return format(Number(item), "HH:mm:ss");
      },
    },
  },
  yAxis: {
    type: "value",
  },
  dataZoom: [
    {
      type: "slider", //slider表示有滑动块的，inside表示内置的
      start: 90, // 左边在 10% 的位置。
      end: 100, // 右边在 60% 的位置。
      show: true,
      xAxisIndex: [0],
      handleSize: 0, //滑动条的 左右2个滑动条的大小
      height: 12, //组件高度
      bottom: -2, //右边的距离
      borderColor: "#eee",
      fillerColor: "#E7E7E7",
      backgroundColor: "#eee", //两边未选中的滑动条区域的颜色
      showDataShadow: false, //是否显示数据阴影 默认auto
      showDetail: false, //即拖拽时候是否显示详细数值信息 默认true
      realtime: true, //是否实时更新
      filterMode: "filter",
      handleStyle: {
        borderRadius: "20",
      },
    },
  ],
  series: [
    {
      itemStyle: {
        color: "#FF4241",
      },
      name: "心率",
      type: "line",
      showSymbol: false,
      data: [],
      time: [],
    },
    {
      itemStyle: {
        color: "#12CCA2",
      },
      name: "血氧",
      type: "line",
      showSymbol: false,
      data: [],
      time: [],
    },
    {
      itemStyle: {
        color: "#FF7D00",
      },
      showSymbol: false,
      name: "体表温度",
      type: "line",
      data: [],
      time: [],
    },
  ],
};
const ruleForm = reactive<TWarningConfirm>({
  id: query.id as string,
  name: "",
  username: "",
  content: "",
  images: [],
});
let curData = ref<TWarningDetail.TRes>({
  address: "",
  adminName: "",
  adminPhone: "",
  creatUser: "",
  createTime: "",
  deviceId: "",
  healthData: [],
  id: 0,
  lat: 0,
  lng: 0,
  maxValue: 0,
  minValue: 0,
  rcontent: "",
  rimg: [],
  rname: "",
  status: 0,
  type: 0,
  updateTime: "",
  updateUser: "",
  userNumber: "",
  username: "",
  orgName: "",
  value: "",
  warnType: 0,
});

const rules = reactive<FormRules<TWarningConfirm>>({
  name: [{ required: true, message: "请输入处理人", trigger: "blur" }],
  username: [{ required: true, message: "请输入警号", trigger: "blur" }],
  content: [{ required: true, message: "请输入处理记录", trigger: "blur" }],
  images: [{ required: true, message: "请上传图片", trigger: "blur" }],
});
watch(
  () => curData.value,
  (newVal) => {
    if (newVal && newVal.status == 1) {
      disabled.value = true;
    }
  }
);

const getData = async () => {
  try {
    const res = await warningDetail({ id: query.id as string });
    locationInfo.value = res;
    curData.value = res;
    ruleForm.name = res.rname;
    ruleForm.username = res.rname;
    ruleForm.content = res.rcontent;
    ruleForm.images = JSON.parse(res.rimg);

    if (res.healthData && res.healthData.length) {
      res.healthData.forEach((item) => {
        options.xAxis.data.push(item.time);
        options.series[0].data.push(item.hr);
        options.series[1].data.push(item.bo);
        options.series[2].data.push(item.temp);
      });
      myChart.setOption(options);
    }

    map.clearMap();
    map.setCenter([res.lng, res.lat]);
    let icon = map.newIcon({ image: location });
    let marker = map.marker({ icon, position: [res.lng, res.lat] });
    marker.setMap(map.map);
    marker.on("click", () => {
      InfoWin = map.infoWindow();
      InfoWin.open(map.map, marker.getPosition());
    });
  } catch (error) {}
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      warningConfirm(ruleForm).then(() => {
        ElMessage.success("处理成功");
        curData.value.status = 1;
        disabled.value = true;
      });
    }
  });
};

const handleResize = debounce(() => {
  myChart.resize();
}, 200);
onMounted(() => {
  getData();
  try {
    map = new MapCustom({ dom: "mapcontainer", center: [116.406315, 39.908775] });
  } catch (error) {}
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value);
    myChart.setOption(options);
    window.addEventListener("resize", handleResize);
  }
});
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped lang="less">
.container {
  overflow: hidden;
  .el-row {
    height: 100%;
    .el-col {
      height: 100%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
    }
  }

  .map-content {
    display: flex;
    flex-direction: column;
    height: 100%;
    .map {
      flex: 1;
      background-color: #fff;
    }
    .chart {
      height: 391px;
      margin-top: 20px;
      background-color: #fff;
      padding: 20px;
      box-sizing: border-box;
      position: relative;
      .title {
        position: absolute;
        left: 0px;
        top: 20px;
        &::before {
          display: inline-block;
          margin-right: 10px;
          content: "";
          width: 2px;
          height: 14px;
          border-radius: 20px;
          background: #061451;
        }
      }
    }
  }

  .right-content {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 100%;
    .info {
      background: #ffffff;
      height: 100%;
      padding: 17px;
      box-sizing: border-box;
      position: relative;
      // overflow: auto;

      .info-text {
        color: #061451;
        font-size: 18px;
        margin-bottom: 20px;
      }
      .info-box {
        padding: 20px 0;
        border-radius: 3px;
        background: #fafafa;
        border: 1px solid #e6e6e6;

        .info-box-title {
          color: #061451;
          font-size: 18px;
          &::before {
            content: "";
            width: 2px;
            height: 14px;
            border-radius: 20px;
            background: #061451;
            display: inline-block;
            margin-right: 9px;
          }
        }
        .info-box-contetn {
          padding: 0 11px;
          .item {
            color: #061451;
            font-size: 18px;
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
            &:nth-child(1) {
              color: red;
            }
          }
        }
      }
      .info-form {
        margin-top: 20px;
      }
    }
    .right-foot {
      width: 100%;
      padding: 5px 20px;
      box-sizing: border-box;
      border-top: 1px solid rgba(0, 0, 0, 0.06);
      display: flex;
      justify-content: flex-end;
      background: #fff;
    }
  }
}
</style>
