<template>
  <div>
    <el-form v-if="isIframeReady">
      <el-form-item label="环境">
        <el-switch v-model="devMode" active-text="测试环境" inactive-text="正式环境"></el-switch>
      </el-form-item>
      <el-form-item label="场景">
        <el-switch v-model="scene" active-text="无人机" inactive-text="机库"></el-switch>
      </el-form-item>

      <el-form-item label="账号">
        <el-input v-model="account"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="password"></el-input>
      </el-form-item>
      <el-form-item label="token">{{ userInfo }}</el-form-item>
      <el-button @click="login">登录</el-button>
    </el-form>
    <!-- http://localhost:9000/ -->
    <!-- https://ctn.mmcuav.cn/tmj_fkzx -->
    <iframe
      id="iframe"
      ref="iframe"
      src="http://localhost:9000/"
      style="width: 1920px; height: 1000px;"
    ></iframe>
  </div>
</template>

<script>
import { Base64 } from "js-base64";

export default {
  name: "fkzxIframe",
  data() {
    return {
      isIframeReady: false, //是否接收到iframe里的ready事件
      baseUrl: "https://test.tmj.mmcuav.cn",
      devMode: false,
      scene: null, // 场景类型 true: 无人机 false: 机库
      account: "mmctest@admin",
      password: "test@Admin001",
      userInfo: null,
      uavTaskList: [
        /*  {
          name: "任务1",
          id: 1,
          children: [
            {
              name: "任务2",
              id: 2,
              // children: [],
              airway: {
                name: "航线名称2",
                id: 2,
              },
            },
          ],
          airway: {
            name: "航线名称1",
            id: 1,
            content:
              '{"filename":"肇庆航线20240318","line":{"baseSpeed":3},"content":[{"uuid":"1nmI-Fo18IagbcVJsia7Q","latitude":23.178153411812204,"longitude":112.57807281336807,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"9pTbBPlF8iIwbUNqusyHK","latitude":23.17783116525969,"longitude":112.57797543441967,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"s91IhN22wuaeyG-UQs0XR","latitude":23.17786413506686,"longitude":112.57824336604547,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"xS_JIl3wxQrhMPdpcjcSn","latitude":23.17820934975604,"longitude":112.5781357731637,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]}],"baseSpeed":3,"gimbalYaw":0,"gimbalPitch":0,"alt":100}',
          },
        },
        {
          name: "任务2",
          id: 2,
          children: [],
          airway: {
            name: "航线名称2",
            id: 2,
            content:
              '{"filename":"肇庆航线20240318","line":{"baseSpeed":3},"content":[{"uuid":"1nmI-Fo18IagbcVJsia7Q","latitude":23.178153411812204,"longitude":112.57807281336807,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"9pTbBPlF8iIwbUNqusyHK","latitude":23.17783116525969,"longitude":112.57797543441967,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"s91IhN22wuaeyG-UQs0XR","latitude":23.17786413506686,"longitude":112.57824336604547,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"xS_JIl3wxQrhMPdpcjcSn","latitude":23.17820934975604,"longitude":112.5781357731637,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]}],"baseSpeed":3,"gimbalYaw":0,"gimbalPitch":0,"alt":100}',
          },
        }, */
      ],
      hangarTaskList: {
        // 常态
        normal: [
          /* 
          {
            name: "任务1",
            id: 1,
            airwayId: 105,
          },
          {
            name: "任务2",
            id: 2,
            airwayId: 106,
          }, */
        ],
        // 定时
        timed: [
          /* {
            name: "任务",
            id: 1,
            time: "2024-04-28 01:00:00", //定时与周期的时间
            status: "未执行", //任务状态
            airwayId: 105,
          }, */
        ],
        // 周期
        period: [
          /* {
                name: '任务',
                id: 1,
                time: '', //定时与周期的时间
                status: '', 任务状态
                airway: {
                  name: '航线名称',
                  id: 1
                }
              } */
        ],
      },
      airwayList: [
        /* {
          name: "航线名称1",
          id: 1,
          organizationName: "所属单位1",
          status: 1, //空域状态 1: 可用 2: 待申请 3: 待审批 4: 通过 5: 驳回
          isSafe: 1, //空域状态 1: 安全 2: 待确定
          labelName: "航线标签1",
          content:
            '{"filename":"肇庆航线20240318","line":{"baseSpeed":3},"content":[{"uuid":"1nmI-Fo18IagbcVJsia7Q","latitude":23.178153411812204,"longitude":112.57807281336807,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"9pTbBPlF8iIwbUNqusyHK","latitude":23.17783116525969,"longitude":112.57797543441967,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"s91IhN22wuaeyG-UQs0XR","latitude":23.17786413506686,"longitude":112.57824336604547,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"xS_JIl3wxQrhMPdpcjcSn","latitude":23.17820934975604,"longitude":112.5781357731637,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]}],"baseSpeed":3,"gimbalYaw":0,"gimbalPitch":0,"alt":100}',
        },
        {
          name: "航线名称2",
          id: 2,
          organizationName: "所属单位2",
          status: 2, //空域状态 1: 可用 2: 待申请 3: 待审批 4: 通过 5: 驳回
          isSafe: 2, //空域状态 1: 安全 2: 待确定
          labelName: "航线标签2",
          content:
            '{"filename":"肇庆航线20240318","line":{"baseSpeed":3},"content":[{"uuid":"1nmI-Fo18IagbcVJsia7Q","latitude":23.178153411812204,"longitude":112.57807281336807,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"9pTbBPlF8iIwbUNqusyHK","latitude":23.17783116525969,"longitude":112.57797543441967,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"s91IhN22wuaeyG-UQs0XR","latitude":23.17786413506686,"longitude":112.57824336604547,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"xS_JIl3wxQrhMPdpcjcSn","latitude":23.17820934975604,"longitude":112.5781357731637,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]}],"baseSpeed":3,"gimbalYaw":0,"gimbalPitch":0,"alt":100}',
        }, */
      ],
    };
  },
  computed: {},
  watch: {
    devMode: {
      immediate: true,
      handler() {
        if (this.devMode) {
          this.account = "mmctest@admin";
          this.password = "test@Admin001";
          this.baseUrl = "https://test.tmj.mmcuav.cn";
        } else {
          this.account = "mmcadmin@kbt001";
          this.password = "TMJMMC@kbta0227&adm";
          this.baseUrl = "https://tmj.mmcuav.cn";
        }
        this.postIframe({
          type: "param",
          param: "devMode",
          data: this.devMode,
        });
      },
    },
    // 无人机任务列表
    uavTaskList() {
      this.postIframe({
        type: "param",
        param: "uavTaskList",
        data: this.uavTaskList,
      });
    },
    // 机库任务列表
    hangarTaskList: {
      deep: true,
      handler() {
        this.postIframe({
          type: "param",
          param: "hangarTaskList",
          data: this.hangarTaskList,
        });
      },
    },
    // 航线列表
    airwayList() {
      this.postIframe({
        type: "param",
        param: "airwayList",
        data: this.airwayList,
      });
    },
    // 场景
    scene() {
      this.postIframe({
        type: "param",
        param: "scene",
        data: this.scene,
      });
    },
    userInfo() {
      this.postIframe({
        type: "param",
        param: "userInfo",
        data: this.userInfo,
      });
    },
  },
  async mounted() {
    window.postIframe = this.postIframe;
    window.addEventListener(
      "message",
      async (event) => {
        if (event.data.module === "MMCFlightControlCenter") {
          if (event.data.type === "ready") {
            // ready中往iframe传参数进行初始化
            console.log(event.data); // 输出子传父
            this.isIframeReady = true;
          }

          if (event.data.type === "event") {
            this.eventHandler(event.data);
          }
        }
      },
      false
    );
  },
  methods: {
    /**
     * 给iframe发送消息
     */
    postIframe(data) {
      if (!this.isIframeReady) {
        throw Error("iframe未准备好");
      }
      let iframeWindow = this.$refs.iframe.contentWindow;
      console.log("postIframe", data);
      iframeWindow.postMessage(
        {
          module: "MMCFlightControlCenter",
          ...data,
        },
        "*"
      );
    },
    /**
     * 事件处理
     */
    eventHandler({ event, data }) {
      console.log("eventHandler", data);
      switch (event) {
        case "uavChange":
          this.onUavChange(data);
          break;
        case "uavAddTask":
          this.onUavAddTask(data);
          break;

        case "uavStartTask":
          this.onUAVStartTask(data);
          break;

        case "hangarChange":
          this.onHangarChange(data);
          break;

        case "hangarChangeTaskTab":
          this.onHangarChangeTaskTab(data);
          break;

        case "hangarStartTask":
          this.onHangarStartTask(data);
          break;

        case "hangarAddTask":
          this.onHangarAddTask(data);
          break;

        case "hangarDelTask":
          this.onHangarDelTask(data);
          break;

        case "log":
          this.onLog(data);
          break;
      }
    },
    onLog({keys, value}){
      console.log('日志输出', keys, value);
    },
    /**
     * 更换无人机
     * @param data
     * @param {Object} data.uav 无人机
     * @param {Boolean} data.showPanel 是否显示数据面板
     * @param {Boolean} data.showPlayer 是否显示播放器
     */
    onUavChange({ uav, showPanel, showPlayer }) {
      console.log("更换无人机事件", uav, showPanel, showPlayer);
    },
    /**
     * 无人机通过航线创建任务
     */
    onUavAddTask({ airway }) {
      console.log("无人机通过航线创建任务", airway);
      let id = Date.now();
      this.uavTaskList.push({
        name: "任务1",
        id: id,
        airwayId: airway.id,
      });
      this.$nextTick(() => {
        this.postIframe({
          type: "callback",
          event: "uavAddTask",
          data: {
            id: Date.now(),
          },
        });
      });
    },
    /**
     * 无人机开始任务
     */
    onUAVStartTask({ uav, selectedTask, selectedAirway }) {
      console.log("一键任务事件", uav, selectedTask, selectedAirway);
      // alert("一键任务事件");
    },
    /**
     * 更换机库事件
     */
    onHangarChange({ hangar }) {
      console.log("更换机库事件", hangar);
      if (hangar) {
        this.hangarTaskList = {
          // 常态
          normal: [
            {
              name: "任务1",
              id: 1,
              airwayId: 105,
            },
            {
              name: "任务2",
              id: 2,
              airwayId: 106,
            },
          ],
          // 定时
          timed: [
            {
              name: "任务",
              id: 1,
              time: "2024-04-28 01:00:00", //定时与周期的时间
              status: "未执行", //任务状态
              airwayId: 105,
            },
          ],
          // 周期
          period: [
            {
              name: "任务",
              id: 1,
              time: "2024-04-28 01:00:00 2024-05-28 01:00:00", //定时与周期的时间
              status: "未执行", //任务状态
              airwayId: 105,
            },
          ],
        };
      }
    },
    /**
     * 机库任务添加事件
     * @param {Object} param
     * @param {number} param.type 1: 日常任务 2: 定时任务 3:周期任务
     * @param {Object} param.airway 航线数据
     * @param {Array} param.taskList 定时与周期任务创建的任务数组
     */
    onHangarAddTask({ type, airway, taskList }) {
      console.log("机库任务添加事件", type, airway, taskList);
      switch (type) {
        case 1: {
          let id = Date.now();
          this.hangarTaskList.normal.push({
            name: "任务" + id,
            id: id,
            airwayId: airway.id,
          });
          this.$nextTick(() => {
            // 回调，参数为更新后新增的任务id, 仅日常任务有用
            this.postIframe({
              type: "callback",
              event: "hangarAddTask",
              data: {
                id,
              },
            });
          });

          break;
        }

        case 2: {
          let id = Date.now();
          let _taskList = taskList.map((item, i) => {
            return {
              ...item,
              id: id + String(i),
              status: "未执行",
              name: "任务" + (this.hangarTaskList.timed.length + 1),
            };
          });
          this.hangarTaskList.timed =
            this.hangarTaskList.timed.concat(_taskList);
          break;
        }

        case 3: {
          let id = Date.now();
          let _taskList = taskList.map((item, i) => {
            return {
              ...item,
              id: id + String(i),
              status: "未执行",
              name: "任务" + (this.hangarTaskList.period.length + 1),
              time: `${item.date[0]} ${item.time[0]} ${item.date[1]} ${item.time[1]}`,
            };
          });
          this.hangarTaskList.period =
            this.hangarTaskList.period.concat(_taskList);
          break;
        }
      }
    },
    /**
     * 机库任务tab更改事件
     * @param {object} param
     * @param {number} param.type  1: 日常任务 2: 定时任务 3:周期任务
     */
    onHangarChangeTaskTab({ type }) {
      console.log("机库任务tab更改事件", type);
    },
    /**
     * 机库开始任务
     * @param {object} param
     * @parma {number} param.type  1: 日常任务 2: 定时任务 3:周期任务
     * @param {object} param.task 任务对象
     * @param {object} param.airway 航线信息
     */
    onHangarStartTask({ type, hangar, task, airway }) {
      console.log("机库开始任务", type, hangar, task, airway);
    },
    /**
     * 删除机库任务
     * @param {object} param
     * @parma {number} param.type  1: 日常任务 2: 定时任务 3:周期任务
     * @param {object} param.task 任务对象
     */
    onHangarDelTask({ type, task }) {
      console.log("删除机库任务", type, task);
      switch (type) {
        case 2:
          this.hangarTaskList.timed = this.hangarTaskList.timed.filter(
            (item) => item.id !== task.id
          );
          break;

        case 3:
          this.hangarTaskList.period = this.hangarTaskList.period.filter(
            (item) => item.id !== task.id
          );
          break;
      }
    },
    init() {
      this.uavTaskList = [
        {
          name: "任务1",
          id: 1,
          children: [
            {
              name: "任务2",
              id: 2,
              // children: [],
              airwayId: 105,
            },
          ],
          airwayId: 106,
        },
        {
          name: "任务2",
          id: 2,
          children: [],
          airwayId: 105,
        },
      ];
      this.hangarTaskList = {
        // 常态
        normal: [
          {
            name: "任务1",
            id: 1,
            airwayId: 105,
          },
          {
            name: "任务2",
            id: 2,
            airwayId: 106,
          },
        ],
        // 定时
        timed: [
          {
            name: "任务",
            id: 1,
            time: "2024-04-28 01:00:00", //定时与周期的时间
            status: "未执行", //任务状态
            airwayId: 105,
          },
        ],
        // 周期
        period: [
          {
            name: "任务",
            id: 1,
            time: "", //定时与周期的时间
            status: "", // 任务状态
            airway: {
              name: "航线名称",
              id: 1,
            },
          },
        ],
      };
      this.airwayList = [
        {
          name: "航线名称1",
          id: 1,
          organizationName: "所属单位1",
          status: 1, //空域状态 1: 可用 2: 待申请 3: 待审批 4: 通过 5: 驳回
          isSafe: 1, //空域状态 1: 安全 2: 待确定
          labelName: "航线标签1",
          content:
            '{"filename":"肇庆航线20240318","line":{"baseSpeed":3},"content":[{"uuid":"1nmI-Fo18IagbcVJsia7Q","latitude":23.178153411812204,"longitude":112.57807281336807,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"9pTbBPlF8iIwbUNqusyHK","latitude":23.17783116525969,"longitude":112.57797543441967,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"s91IhN22wuaeyG-UQs0XR","latitude":23.17786413506686,"longitude":112.57824336604547,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"xS_JIl3wxQrhMPdpcjcSn","latitude":23.17820934975604,"longitude":112.5781357731637,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]}],"baseSpeed":3,"gimbalYaw":0,"gimbalPitch":0,"alt":100}',
        },
        {
          name: "航线名称2",
          id: 2,
          organizationName: "所属单位2",
          status: 2, //空域状态 1: 可用 2: 待申请 3: 待审批 4: 通过 5: 驳回
          isSafe: 2, //空域状态 1: 安全 2: 待确定
          labelName: "航线标签2",
          content:
            '{"filename":"肇庆航线20240318","line":{"baseSpeed":3},"content":[{"uuid":"1nmI-Fo18IagbcVJsia7Q","latitude":23.178153411812204,"longitude":112.57807281336807,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"9pTbBPlF8iIwbUNqusyHK","latitude":23.17783116525969,"longitude":112.57797543441967,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"s91IhN22wuaeyG-UQs0XR","latitude":23.17786413506686,"longitude":112.57824336604547,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"xS_JIl3wxQrhMPdpcjcSn","latitude":23.17820934975604,"longitude":112.5781357731637,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]}],"baseSpeed":3,"gimbalYaw":0,"gimbalPitch":0,"alt":100}',
        },
      ];
    },
    async login() {
      let formData = new FormData();
      formData.append("userAccount", this.account);
      formData.append("password", Base64.encode(this.password));
      let res1 = await fetch(this.baseUrl + "/crm/login", {
        method: "post",
        headers: {
          // "Content-Type": "multipart/form-data",
        },
        body: formData,
      });
      let data1 = await res1.json();

      if (data1.code == 200) {
        await fetch(this.baseUrl + "/crm/user/platformPermission", {
          method: "get",
          headers: {
            Token: data1.data.token,
          },
        });
        this.userInfo = data1.data;
        this.init();
      }
    },
  },
};
</script>