<template>
  <div style="height: 100%">
    <el-row style="height: 67%" :gutter="10">
      <el-col :span="7" style="height: 100%">
        <el-card class="tableHeight">
          <div slot="header" class="clearfix">
            <span>雷达控制参数</span>
            <el-button size="mini" type="success" @click="handleEdit" style="float: right">变更</el-button>
          </div>
          <el-table :data="radarParams" style="width: 100%" size="small" border fit>
            <!-- @current-change="instanceChange" -->
            <el-table-column width="130" prop="key" label="属性"></el-table-column>
            <el-table-column width="80" prop="value" label="值"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-switch v-if="scope.row.key == '开关机状态'" active-text="打开" inactive-text="关闭"
                  v-model="StartUpStatusBoolean" :change="switchChange()"></el-switch>
                <el-select v-if="scope.row.key == '抗干扰措施'" v-model="currentRadarParam.AntiJamStyle" size="mini"
                  placeholder="请选择防干扰措施">
                  <el-option v-for="item in AntiJamStyles" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                <el-button v-if="scope.row.key == '脉冲参数'" type="primary" size="mini">编辑</el-button>
                <el-select v-if="scope.row.key == '工作模式'" v-model="currentRadarParam.RadarWorkType" size="mini"
                  placeholder="请选择工作模式">
                  <el-option v-for="item in radarModes" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>

                <el-slider v-if="scope.row.key == '方位扫描中心(°)'" v-model="currentRadarParam.AzimuthScanCenter" :step="5"
                  :min="-180" :max="179" input-size="mini"> </el-slider>
                <el-slider v-if="scope.row.key == '俯仰扫描中心(°)'" v-model="currentRadarParam.PitchScanCenter" :step="5"
                  :min="-90" :max="89" input-size="mini"> </el-slider>
                <el-slider v-if="scope.row.key == '方位扫描范围(°)'" v-model="currentRadarParam.AzimuthScanDeg" :step="5"
                  :min="0" :max="50" input-size="mini"> </el-slider>
                <el-slider v-if="scope.row.key == '俯仰扫描范围(°)'" v-model="currentRadarParam.PitchScanDeg" :step="5"
                  :min="0" :max="50" input-size="mini"> </el-slider>

                <el-input-number v-if="scope.row.key == '天线最大增益(dB)'" :step="1" :max="120" :min="-120"
                  v-model="currentRadarParam.MaxGain" size="mini"></el-input-number>
                <el-input-number v-if="scope.row.key == '发射机功率(W)'" :step="10" :max="100" :min="50"
                  v-model="currentRadarParam.PeakPower" size="mini"></el-input-number>
                <el-input-number v-if="scope.row.key == '方位波束宽度'" :step="1" :max="10" :min="0"
                  v-model="currentRadarParam.BeamAzimuthWidth" size="mini"></el-input-number>
                <el-input-number v-if="scope.row.key == '俯仰波束宽度'" :step="1" :max="10" :min="0"
                  v-model="currentRadarParam.BeamPitchWidth" size="mini"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12" style="height: 100%">
        <el-card class="radar">
          <div slot="header" class="clearfix">
            <span>半实物设备状态</span>
          </div>
            <el-table height="100%" border size="small" :data="sdrStatus">
              <el-table-column prop="key" align="left" label="属性" width="130"></el-table-column>
              <el-table-column prop="value" align="right" label="值"></el-table-column>
            </el-table>
        </el-card>
      </el-col>
      <el-col :span="5" style="height: 100%">
        <el-card class="tableHeight">
          <div slot="header" class="clearfix">
            <span>雷达状态</span>
          </div>
          <el-table :data="radarStatusList" style="width: 100%">
            <el-table-column prop="key" label="参数"></el-table-column>
            <el-table-column prop="value" label="数值">
              <template slot-scope="scope">
                <span>{{ scope.row.value }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-row style="height: 33%">
      <el-card class="target">
        <div slot="header" class="clearfix">
          <span>雷达目标列表</span>
        </div>
        <el-table :data="radarData" class="targetTable" height="100%;" size="small" border fit ref="radarTargetTable">
          <el-table-column prop="SimTime" label="时间"></el-table-column>
          <el-table-column prop="TargetID" label="目标批号"> </el-table-column>
          <el-table-column prop="EnemyPro" label="敌我属性"> </el-table-column>
          <el-table-column prop="FlightState" label="航迹状态">
          </el-table-column>
          <el-table-column prop="LightQuality" label="航迹质量">
          </el-table-column>
          <el-table-column prop="TargetAzi" label="目标方位角(°)">
          </el-table-column>
          <el-table-column prop="TargetEle" label="目标俯仰角(°)">
          </el-table-column>
          <el-table-column prop="TargetDistance" label="目标距离(m)">
          </el-table-column>
          <el-table-column prop="TargetRSpeed" label="目标径向速度(m/s)">
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import axios from "axios";

export default {
  computed: {
    ...mapGetters('app', [
      "init",
      "radarParams",
      "radarStatus",
      "radarData",
      "platformID",
    ]),
    radarStatusList() {
      return this.radarStatus || [];
    }
  },
  watch: {
    init: {
      handler: function (val, oldVal) { },
    },
    platformID: {
      handler: function (val, oldVal) {
        // this.$wst.send({
        //   url: "getRadarInstances",
        //   data: {
        //     PlatformID: this.platformID,
        //   },
        // });
      },
    },
    radarParams: {
      handler: function (val, oldVal) {
        if (this.getValue(val, "开关机状态") == "开机") {
          this.currentRadarParam.StartUpStatus = 1;
        } else {
          this.currentRadarParam.StartUpStatus = 0;
        }
        if (this.getValue(val, "抗干扰措施") == "不抗干扰") {
          this.currentRadarParam.AntiJamStyle = 0;
        } else if (this.getValue(val, "抗干扰措施") == "频率捷变") {
          this.currentRadarParam.AntiJamStyle = 1;
        } else if (this.getValue(val, "抗干扰措施") == "旁瓣匿影") {
          this.currentRadarParam.AntiJamStyle = 2;
        } else if (this.getValue(val, "抗干扰措施") == "旁瓣对消") {
          this.currentRadarParam.AntiJamStyle = 3;
        }
        if (this.getValue(val, "工作模式") == "待机") {
          this.currentRadarParam.RadarWorkType = 0;
        } else if (this.getValue(val, "工作模式") == "搜索") {
          this.currentRadarParam.RadarWorkType = 1;
        } else if (this.getValue(val, "工作模式") == "跟踪") {
          this.currentRadarParam.RadarWorkType = 2;
        }
        this.currentRadarParam.AzimuthScanCenter = this.getValue(val, "方位扫描中心(°)");;
        this.currentRadarParam.PitchScanCenter = this.getValue(val, "俯仰扫描中心(°)");;
        this.currentRadarParam.AzimuthScanDeg = this.getValue(val, "方位扫描范围(°)");;
        this.currentRadarParam.PitchScanDeg = this.getValue(val, "俯仰扫描范围(°)");;
        this.currentRadarParam.Detection = this.getValue(val, "发现概率");

        this.currentRadarParam.WorkFreq = this.getValue(val, "雷达工作频率");
        this.currentRadarParam.MaxGain = this.getValue(val, "最大增益");
        this.currentRadarParam.PeakPower = this.getValue(val, "发射机峰值功率");
        this.currentRadarParam.FalseAlarm = this.getValue(val, "虚警率");
        this.currentRadarParam.PulseFreq = this.getValue(val, "脉冲重复频率");
        this.currentRadarParam.AntennaSpeed = this.getValue(val, "天线转速");
        this.currentRadarParam.BeamAzimuthWidth = this.getValue(
          val,
          "方位波束宽度"
        );
        this.currentRadarParam.BeamPitchWidth = this.getValue(
          val,
          "俯仰波束宽度"
        );
        this.currentRadarParam.PulseWidth = this.getValue(val, "脉冲宽度");
        this.currentRadarParam.SignalWidth = this.getValue(val, "信号带宽");
        this.currentRadarParam.SideGain = this.getValue(val, "副瓣增益");

        this.StartUpStatusBoolean =
          this.currentRadarParam.StartUpStatus == 1 ? true : false;
      },
    },
  },
  data() {
    return {
      data: [[859, 10],
      [458, 40],
      [269, 120],
      [234, 210]],
      frequencevalue: "",
      workvalue: "",
      radarEchart: null,
      uRrWorkModeBoolean: true,
      StartUpStatusBoolean: null,
      currentRadarParam: {
        StartUpStatus: null,
        AntiJamStyle: null,
        RadarWorkType: null,
        AzimuthScanCenter: null,
        PitchScanCenter: null,
        AzimuthScanDeg: null,
        PitchScanDeg: null,
        Detection: null,
        WorkFreq: null,
        MaxGain: null,
        PeakPower: null,
        FalseAlarm: null,
        PulseFreq: null,
        AntennaSpeed: null,
        BeamAzimuthWidth: null,
        BeamPitchWidth: null,
        PulseWidth: null,
        SignalWidth: null,
        SideGain: null,
      },
      sdrStatus: [
        { key: "平台状态", value: "未知" },
        { key: "服务状态", value: "未知" },
        { key: "干扰策略", value: "未知" },
        { key: "抗干扰策略", value: "未知" },

      ],
      AntiJamStyles: [
        {
          value: 0,
          label: "不抗干扰",
        },
        {
          value: 1,
          label: "频率捷变",
        },
        {
          value: 2,
          label: "旁瓣匿影",
        },
        {
          value: 3,
          label: "旁瓣对消",
        },
      ],
      radarModes: [
        {
          value: 0,
          label: "待机",
        },
        {
          value: 1,
          label: "搜索",
        },
        {
          value: 2,
          label: "跟踪",
        },
      ],

      echartoption: {
        polar: {},
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        angleAxis: {
          max: 360,
          min: 0,
          type: "value",
          startAngle: 90,
        },
        radiusAxis: {
          max: 1000,
          min: 0,
          splitArea: {
            show: true,
            areaStyle: {
              color: ["#006600", "#009900", "#00CC00"],
            },
          },
          axisLine: {
            lineStyle: {
              color: "#f7f7f7", // 设置轴线的颜色为红色
            },
          },
          axisPointer: {
            show: false,
          },
        },
        series: [
          {
            coordinateSystem: "polar",
            name: "line",
            type: "scatter",
            data: null,
          },
        ],
      },
      // radarData: {
      //     [12, 32,42]
      // }
      timer: null,  // 添加timer属性
    };
  },
  activated() {
    try {
      this.timerRefresh();
      this.refreshTargets();
      this.setTimer();
    } catch (error) {
      console.error('激活组件时出错:', error);
    }
  },
  deactivated() {
    try {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    } catch (error) {
      console.error('停用组件时出错:', error);
    }
  },
  beforeDestroy() {
    this.timerDestory();
  },
  mounted() {
    // for (let i = 0; i <= 7; i++) {
    //   let theta = (i / 100) * 180 + Math.random() * 90;
    //   let r = 5 * (1 + Math.sin((theta / 180) * Math.PI));
    //   this.data.push([r, theta]);
    //   // this.Radarresults.push({
    //   //   az: theta,
    //   //   range: r,
    //   // });
    // }

    this.echartoption.series[0].data = this.data;

    this.echartsInit();
    // 页面加载设置高度自适应
    window.onresize = () => {
      this.resizeDom();
    };
    // 页面加载设置高度自适应
    this.resizeDom();
  },
  methods: {
    setTimer() {
      try {
        if (this.timer == null) {
          this.timer = setInterval(() => {
            // 刷新雷达状态
            this.timerRefresh().catch(error => {
              console.error('定时刷新雷达状态出错:', error);
            });
            
            // 刷新雷达目标数据
            this.refreshTargets().catch(error => {
              console.error('定时刷新目标数据出错:', error);
            });
          }, 3000);
        }
      } catch (error) {
        console.error('设置定时器出错:', error);
      }
    },
    timerDestory() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    async timerRefresh() {
      try {
        const response = await axios.get(`/api/platform/${this.platformID}/radar-status`);
        if (response.data) {
          const formattedData = response.data.map(item => ({
            ...item,
            value: item.value?.toString() || ''
          }));
          this.$store.commit("app/SET_RADAR_STATUS", formattedData);
        }
      } catch (error) {
        console.error('获取雷达状态失败:', error);
        // 网络错误时使用默认值
        if (error.code === 'ERR_NETWORK') {
          const defaultStatus = [
            { key: "型号", value: "相控阵雷达" },
            { key: "序号", value: "001" },
            { key: "类型", value: "相控阵雷达" },
            { key: "连接方式", value: "CAN" },
            { key: "开机时间", value: new Date().toLocaleTimeString() },
            { key: "发现概率(%)", value: "95.0" },
            { key: "虚警率(%)", value: "3.0" },
            { key: "扫描周期(s)", value: "1" }
          ];
          this.$store.commit("app/SET_RADAR_STATUS", defaultStatus);
        }
      }
      axios.get(`http://192.168.5.22:5200/api/platform/${this.platformID}/getSdrStatusByID`)
              .then(response => {
                console.log(response.data)
                console.log(this.sdrStatus)
                this.sdrStatus[0].value = response.data.platformStatus
                this.sdrStatus[1].value = response.data.serviceStatus
                this.sdrStatus[2].value = response.data.jamingPolicy
                this.sdrStatus[3].value = response.data.investingPolicy
                console.log(this.sdrStatus)
              })
    },
    echartsInit() {
      this.$echarts
        .init(document.getElementById("radarEchart"))
        .setOption(this.echartoption);
      if (this.localEchart == null) {
        this.radarEchart = this.$echarts.init(
          document.getElementById("radarEchart")
        );
      } else {
        this.radarEchart.setOption(this.echartoption);
      }
    },
    echartsRefresh() {
      this.data = [];
      for (let i = 0; i <= 7; i++) {
        let theta = (i / 100) * 180 + Math.random() * 360;
        let r = 5 * (1 + Math.sin((theta / 180) * Math.PI));
        this.data.push([r, theta]);
        // this.ESMresults.push({
        //   az: theta,
        //   range: r,
        // });
      }
      this.echartoption.series[0].data = this.data;
      this.echartsInit();
    },
    //通过窗体高宽计算容器高宽，渲染echart图表的div的宽高度以达到自适应目的
    resizeDom() {
      console.log("高度自适应");
      const boxHeight =
        document.getElementsByClassName("echarts-box")[0].clientHeight;
      var Echart = document.getElementById("radarEchart");
      Echart.style.height = boxHeight - 65 + "px";
      this.$echarts.init(document.getElementById("radarEchart")).resize();
    },
    async handleEdit() {
      try {
        // 添加参数默认值和类型检查
        const getParamValue = (value, defaultValue = "0") => {
          if (value === null || value === undefined) {
            return defaultValue;
          }
          return value.toString();
        };

        // 构造符合后端API格式的参数数组
        const radarParams = [
          { 
            key: "开关机状态", 
            value: this.StartUpStatusBoolean ? "打开" : "关闭" 
          },
          { 
            key: "抗干扰措施", 
            value: this.getAntiJamStyleText(this.currentRadarParam.AntiJamStyle || 0) 
          },
          { 
            key: "工作模式", 
            value: this.getWorkModeText(this.currentRadarParam.RadarWorkType || 0) 
          },
          { 
            key: "脉冲参数", 
            value: "自动" 
          },
          { 
            key: "方位扫描中心(°)", 
            value: getParamValue(this.currentRadarParam.AzimuthScanCenter, "0") 
          },
          { 
            key: "俯仰扫描中心(°)", 
            value: getParamValue(this.currentRadarParam.PitchScanCenter, "0") 
          },
          { 
            key: "波束宽度(°)", 
            value: getParamValue(this.currentRadarParam.BeamAzimuthWidth, "2") 
          },
          { 
            key: "方位扫描范围(°)", 
            value: getParamValue(this.currentRadarParam.AzimuthScanDeg, "10") 
          },
          { 
            key: "俯仰扫描范围(°)", 
            value: getParamValue(this.currentRadarParam.PitchScanDeg, "10") 
          },
          { 
            key: "发射机功率(W)", 
            value: getParamValue(this.currentRadarParam.PeakPower, "100") 
          }
        ];

        // 检查platformID是否存在
        if (!this.platformID) {
          throw new Error("平台ID不能为空");
        }

        // 发送POST请求到后端API
        const response = await axios.post(
          `/api/platform/${this.platformID}/radar-params`,
          radarParams
        );

        if (response.data) {
          // 只更新雷达控制参数
          this.$store.commit("app/SET_RADAR_PARAMS", radarParams);
          this.$message.success("雷达参数更新成功");
        }
      } catch (error) {
        console.error("更新雷达参数失败:", error);
        this.$message.error(error.message || "更新雷达参数失败");
      }
    },
    getAntiJamStyleText(value) {
      const styles = {
        0: "不抗干扰",
        1: "频率捷变",
        2: "旁瓣匿影",
        3: "旁瓣对消"
      };
      return styles[value] || styles[0];
    },
    getWorkModeText(value) {
      const modes = {
        0: "待机",
        1: "搜索",
        2: "跟踪"
      };
      return modes[value] || modes[0];
    },
    getValue(params, key) {
      let value = null;
      params.forEach((element) => {
        if (element.key == key) {
          value = element.value;
        }
      });
      return value;
    },
    switchChange() {
      this.currentRadarParam.StartUpStatus =
        this.StartUpStatusBoolean == true ? 1 : 0;
    },
    async refreshTargets() {
      try {
        const response = await axios.get(`/api/platform/${this.platformID}/radar-targets`);
        if (response.data) {
          // 将后端数据的字段名转换为前端使用的格式
          const formattedData = response.data.map(item => ({
            SimTime: item.simTime,
            TargetID: item.targetId,
            EnemyPro: item.enemyPro,
            FlightState: item.flightState,
            LightQuality: item.lightQuality,
            TargetAzi: item.targetAzi,
            TargetEle: item.targetEle,
            TargetDistance: item.targetDistance,
            TargetRSpeed: item.targetRSpeed
          }));
          
          // 更新到 store
          this.$store.commit("app/SET_RADAR_DATA", formattedData);
          
          // 更新雷达图上的点
          this.data = formattedData.map(item => [item.TargetDistance, item.TargetAzi]);
          this.echartoption.series[0].data = this.data;
          this.echartsInit();

          // 添加自动滚动到最新数据
          this.$nextTick(() => {
            const table = this.$refs.radarTargetTable;
            if (table && formattedData.length > 0) {
              // 获取表格的滚动容器
              const scrollContainer = table.bodyWrapper;
              if (scrollContainer) {
                scrollContainer.scrollTop = scrollContainer.scrollHeight;
              }
            }
          });
        }
      } catch (error) {
        console.error('获取雷达目标数据失败:', error);
        if (error.code === 'ERR_NETWORK') {
          // 网络错误时使用默认数据
          const defaultData = [
            {
              SimTime: "14:37.15",
              TargetID: 1,
              EnemyPro: "我方",
              FlightState: "进入搜索范围",
              LightQuality: "高",
              TargetAzi: 10,
              TargetEle: -50,
              TargetDistance: 859,
              TargetRSpeed: 5.4
            }
            // ... 可以添加更多默认数据
          ];
          this.$store.commit("app/SET_RADAR_DATA", defaultData);
        }
      }
    }
  },
};
</script>
<style scoped>
::v-deep .el-input__inner {
  background-color: transparent !important;
  border: 1px solid #1296db;
  color: #ffffff;
}

::v-deep .el-form-item__label {
  color: white !important;
}

.tableHeight {
  height: 100%;
}

.echarts-box {
  height: 100%;
  width: 100%;
}

#radarEchart {
  width: 100%;
  height: 100% !important;
}

.radar {
  height: 100%;
}
</style>