<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="scene1" active-text="无人机" inactive-text="机库"></el-switch>
      </el-form-item>
      <el-form-item label="使用标准航线库">
        <el-switch v-model="useSTLAirway" active-text="启用" inactive-text="关闭"></el-switch>
      </el-form-item>
      <el-form-item label="使用定时任务">
        <el-switch v-model="useTimedTask" 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 -->
    <!-- https://tmj.mmcuav.cn -->
    <iframe
      id="iframe"
      ref="iframe"
      src="http://localhost:9000/"
      style="width: 1920px; height: 1000px;"
      anonymous
      allowfullscreen="true"
    ></iframe>
  </div>
</template>

<script>
import { Base64 } from "js-base64";
//航线数据
const airway = [
  {
    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: [],
  },
];

export default {
  name: "fkzxIframe",
  data() {
    return {
      isIframeReady: false, //是否接收到iframe里的ready事件
      devMode: false,
      url: {
        baseUrl: "/",
        wsUrl: "wss://tmj.mmcuav.cn/websocket",
        mqttUrl: "wss://fkzx.mmcuav.cn:8884/mqtt",
      },
      scene1: false, // 场景类型 true: 无人机 false: 机库
      useSTLAirway: false, // 使用标准航线库
      useTimedTask: 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:
              airway,
          },
        },
        {
          name: "任务2",
          id: 2,
          children: [],
          airway: {
            name: "航线名称2",
            id: 2,
            content: airway
        },
        }, */
      ],
      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
                }
              } */
        ],
      },
      postIframeList: [], //给iframe传递参数的队列
    };
  },
  computed: {
    scene() {
      return this.scene1 ? 1 : 2;
    },
  },
  watch: {
    isIframeReady() {
      if (this.isIframeReady) {
        this.postIframeList.forEach((item) => {
          this.postIframe(item);
        });
      }
    },
    devMode: {
      immediate: true,
      handler() {
        if (this.devMode) {
          this.account = "admin";
          this.password = "mmc@123456";
          this.url = {
            baseUrl: "http://192.168.5.80:30080",
            wsUrl: "wss://tmj.mmcuav.cn/websocket",
            mqttUrl: "wss://fkzx.mmcuav.cn:8884/mqtt",
          };
        } else {
          this.account = "admin";
          this.password = "mmc@123456";
          this.url = {
            baseUrl: "http://192.168.5.80:30132",
            wsUrl: "wss://tmj.mmcuav.cn/websocket",
            mqttUrl: "wss://fkzx.mmcuav.cn:8884/mqtt",
          };
        }
        this.postIframe({
          type: "param",
          param: "url",
          data: this.url,
        });
      },
    },
    // 无人机任务列表
    uavTaskList() {
      this.postIframe({
        type: "param",
        param: "uavTaskList",
        data: this.uavTaskList,
      });
    },
    // 机库任务列表
    hangarTaskList: {
      deep: true,
      handler() {
        this.postIframe({
          type: "param",
          param: "hangarTaskList",
          data: this.hangarTaskList,
        });
      },
    },
    // 场景
    scene: {
      immediate: true,
      handler() {
        this.postIframe({
          type: "param",
          param: "scene",
          data: this.scene,
        });
      },
    },
    userInfo() {
      this.postIframe({
        type: "param",
        param: "userInfo",
        data: this.userInfo,
      });
    },
    useSTLAirway() {
      this.postIframe({
        type: "param",
        param: "useSTLAirway",
        data: this.useSTLAirway,
      });
    },
    useTimedTask() {
      this.postIframe({
        type: "param",
        param: "useTimedTask",
        data: this.useTimedTask,
      });
    },
  },
  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) {
        this.postIframeList.push(data);
        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 "uavTaskAdd":
          this.onUavTaskAdd(data);
          break;

        case "uavTaskStart":
          this.onUAVTaskStart(data);
          break;

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

        case "hangarTaskTabChange":
          this.onHangarTaskTabChange(data);
          break;

        case "hangarTaskStart":
          this.onHangarTaskStart(data);
          break;

        case "hangarTaskAdd":
          this.onHangarTaskAdd(data);
          break;

        case "hangarTaskDel":
          this.onHangarTaskDel(data);
          break;

        case "log":
          this.onLog(data);
          break;

        case "airwayPageChange":
          this.onAirwayPageChange(data);
          break;

        case "airwayGet":
          this.onAirwayGet(data);
      }
    },
    /**
     * 获取航线事件
     */
    async onAirwayGet({ airwayId }) {
      this.postIframe({
        type: "callback",
        event: "airwayGet",
        data: {
          name: "获取航线" + airwayId,
          id: airwayId,
          content: airway,
        },
      });
    },
    /**
     * 航线分页更改
     */
    onAirwayPageChange({ page, pageSize }) {
      console.log("航线分页更改", page, pageSize);
      this.postIframe({
        type: "callback",
        event: "airwayPageChange",
        data: {
          current: page, // 当前页码
          records: [
            {
              id: 1,
              name: "模拟航线" + `第${page}页`,
              organizationName: "机构名",
              status: "可用", //空域状态
              isSafe: 1, // 安全状态1: 安全 , 0: 待确定,
              labelName: "航线标签",
              //航线数据
              content: airway,
            },
          ],
          size: 10, // 当前页记录数
          total: 20, // 总记录灵
        },
      });
    },
    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);
    },
    /**
     * 无人机通过航线创建任务
     */
    onUavTaskAdd({ airway }) {
      console.log("无人机通过航线创建任务", airway);
      let id = Date.now();
      this.uavTaskList.push({
        name: "任务1",
        id: id,
        airwayId: airway.id,
        airway,
      });
      this.$nextTick(() => {
        this.postIframe({
          type: "callback",
          event: "uavTaskAdd",
          data: {
            id,
          },
        });
      });
    },
    /**
     * 无人机开始任务
     */
    onUAVTaskStart({ 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 定时与周期任务创建的任务数组
     */
    onHangarTaskAdd({ 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,
            airway,
          });
          this.$nextTick(() => {
            // 回调，参数为更新后新增的任务id, 仅日常任务有用
            this.postIframe({
              type: "callback",
              event: "hangarTaskAdd",
              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:周期任务
     */
    onHangarTaskTabChange({ type }) {
      console.log("机库任务tab更改事件", type);
    },
    /**
     * 机库开始任务
     * @param {object} param
     * @parma {number} param.type  1: 日常任务 2: 定时任务 3:周期任务
     * @param {object} param.task 任务对象
     * @param {object} param.airway 航线信息
     */
    onHangarTaskStart({ type, hangar, task, airway }) {
      console.log("机库开始任务", type, hangar, task, airway);
    },
    /**
     * 删除机库任务
     * @param {object} param
     * @parma {number} param.type  1: 日常任务 2: 定时任务 3:周期任务
     * @param {object} param.task 任务对象
     */
    onHangarTaskDel({ 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.scene1 = true;
      this.useSTLAirway = false;
      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,
            },
          },
        ],
      };
    },
    async login() {
      let formData = new FormData();
      formData.append("userAccount", this.account);
      formData.append("password", Base64.encode(this.password));
      let res = await fetch(this.url.baseUrl + "/admin-api/system/auth/login", {
        method: "post",
        headers: {
          "Content-Type": "application/json",
          "Tenant-Id": 1,
          terminal: 2,
        },
        body: JSON.stringify({
          username: this.account,
          password: this.password,
        }),
      });
      this.userInfo = (await res.json()).data;
      this.init();
    },
  },
};
</script>