<template>
  <div :class="{ robot: true, block: type === 1 }">
    <van-dropdown-menu v-if="robotList.length">
      <van-dropdown-item
        @change="change"
        v-model="deviceId"
        :options="robotList"
      />
    </van-dropdown-menu>
    <van-cell size="large">
      <template #title>
        <van-image
          width="20"
          height="20"
          :src="logo"
          style="vertical-align: middle;margin-right: 5px"
        />
        <span class="custom-title">党建机器人</span>
      </template>
    </van-cell>
    <div id="robot" class="app">
      <div class="van-hairline--surround msg" ref="scroll">
        <div ref="msgScroll">
          <div class="defaultQuestion">
            <van-row>
              <van-col
                span="8"
                class="queryTitle"
                :style="'height: ' + q.length * 28 + 'px;'"
              >
                <van-image
                  width="80"
                  height="80"
                  class="reset img"
                  :src="robotChart"
                />
                <van-icon name="replay" @click="reset" class="reset" />
              </van-col>
              <van-col span="16">
                <div
                  class="van-ellipsis van-hairline--bottom"
                  v-for="item in q"
                  :key="item"
                  v-text="item + '?'"
                  @click="() => defQ(item)"
                ></div>
              </van-col>
            </van-row>
          </div>
          <div
            class="msgBg"
            v-for="item in dialogueList"
            :style="'text-align: ' + (item.type === 'local' ? 'right' : 'left')"
            :key="item.reply"
          >
            <div
              style="display: inline-block;text-align: left;"
              v-text="item.reply"
            ></div>
          </div>
        </div>
      </div>
      <div class="van-hairline--left van-hairline--right van-hairline--bottom">
        <van-field
          v-model="message"
          center
          clearable
          placeholder="请输入你的问题"
        >
          <template #button>
            <van-button size="small" @click="tomsg">
              发送
            </van-button>
          </template>
        </van-field>
      </div>
      <van-cell title="遥控器" value="" />
      <van-row>
        <van-col span="12">
          <div class="control ">
            <div class="bg" :style="touchArce"></div>
            <van-icon
              @touchstart="() => toOperation('head', 'up')"
              @touchend="() => (touch = false)"
              class="btnClass"
              name="arrow-up"
            />
            <div class="conBtnGroup">
              <van-icon
                class="btnClass"
                @touchstart="() => toOperation('head', 'left')"
                @touchend="() => (touch = false)"
                name="arrow-left"
              />
              <div>
                <van-image
                  class="centerImg"
                  fit="cover"
                  :src="robotHead"
                ></van-image>
              </div>
              <van-icon
                class="btnClass"
                @touchstart="() => toOperation('head', 'right')"
                @touchend="() => (touch = false)"
                name="arrow"
              />
            </div>
            <van-icon
              class="btnClass"
              @touchstart="() => toOperation('head', 'down')"
              @touchend="() => (touch = false)"
              name="arrow-down"
            />
          </div>
        </van-col>
        <van-col span="12">
          <div class="control">
            <div class="bg" :style="touchArceWheel"></div>
            <van-icon
              @touchstart="() => toOperation('wheel', 'forward')"
              @touchend="() => (touch = false)"
              class="btnClass"
              name="arrow-up"
            />
            <div class="conBtnGroup">
              <van-icon
                class="btnClass"
                @touchstart="() => toOperation('wheel', 'left')"
                @touchend="() => (touch = false)"
                name="arrow-left"
              />
              <div>
                <van-image
                  class="centerImg"
                  fit="cover"
                  :src="robotBody"
                ></van-image>
              </div>
              <van-icon
                class="btnClass"
                @touchstart="() => toOperation('wheel', 'right')"
                @touchend="() => (touch = false)"
                name="arrow"
              />
            </div>

            <van-icon
              class="btnClass"
              @touchstart="() => toOperation('wheel', 'backward')"
              @touchend="() => (touch = false)"
              name="arrow-down"
            />
          </div>
        </van-col>
      </van-row>
    </div>
  </div>
</template>

<script>
import { currentUrlToParams } from "@/utils/common.js";
import { getRobotToken, getRobotClient } from "@/api/robot/index.js";
import Config from "@/config/index.js";
import {
  Button as vanButton,
  Cell as vanCell,
  Col as vanCol,
  Row as vanRow,
  Field as vanField,
  Image as vanImage,
  DropdownMenu as vanDropdownMenu,
  DropdownItem as vanDropdownItem,
  Icon as vanIcon,
  Toast
} from "vant";
import "vant/lib/button/style";
import "vant/lib/cell/style";
import "vant/lib/col/style";
import "vant/lib/row/style";
import "vant/lib/field/style";
import "vant/lib/toast/style";
import "vant/lib/image/style";
import "vant/lib/icon/style";
import "vant/lib/dropdown-menu/style";
import "vant/lib/dropdown-item/style";

import robotHead from "@/assets/image/robot-head.png";
import robotBody from "@/assets/image/robot-body.png";
import logo from "@/assets/image/logo.png";
import robotChart from "@/assets/image/robot-chart.png";

export default {
  name: "app",
  data: function() {
    return {
      robotToken: "",
      scoket: undefined,
      status: false,
      timeout: undefined,
      quetion: [
        "三严三实的具体内容",
        "中华民族近代以来最伟大的梦想",
        "中国梦的本质是",
        "两学一做是指",
        "党风廉政建设的‘两个责任’",
        "什么是三会一课",
        "党的根本宗旨是",
        "“四风”问题指的是",
        "加强党的“五大建设”是",
        "建设“三型”马克思主义执政党是",
        "党的最高理想和最终目标是",
        "社会主义核心价值观的主要内容",
        "四讲四有是指",
        "“两学一做”增强的是哪四大意识",
        "五四运动是什么时候爆发的"
      ],
      qPage: 1,
      qPageSize: 5,
      robotHead,
      robotBody,
      robotChart,
      logo,
      robotList: [],
      dialogueList: [],
      q: [],
      touch: false,
      deviceId: "",
      message: "",
      type: undefined
    };
  },
  computed: {
    touchArce() {
      if (!this.touch)
        return {
          type: "",
          style: ""
        };
      let l = this.touch.split("-");
      switch (l[1]) {
        case "up":
          l[1] = "top";
          break;
        case "down":
          l[1] = "bottom";
          break;
      }
      return l[0] === "head" ? "border-" + l[1] + "-color: #dadada" : "";
    },
    touchArceWheel() {
      if (!this.touch)
        return {
          type: "",
          style: ""
        };
      let l = this.touch.split("-");
      switch (l[1]) {
        case "forward":
          l[1] = "top";
          break;
        case "backward":
          l[1] = "bottom";
          break;
      }
      return l[0] === "wheel" ? "border-" + l[1] + "-color: #dadada" : "";
    }
  },
  methods: {
    defQ(t) {
      this.message = t;
      this.tomsg();
    },
    creatID() {
      const T =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      let id = "";
      for (let i = 0; i < 8; i++) {
        id += T[Math.floor(Math.random() * 62)];
      }
      return id;
    },
    tomsg() {
      if (!this.status) {
        this.message = "";
        return Toast("未链接！");
      }
      if (!this.message) return;
      let dialogue = {
        type: "local",
        reply: this.message
      };
      console.log("发送------>", dialogue);
      let dialogueList = JSON.parse(JSON.stringify(this.dialogueList));
      dialogueList.push(dialogue);
      this.dialogueList = dialogueList;
      let p = {
        id: this.creatID(),
        dialog: {
          reply: this.message
        }
      };
      this.scoket && this.scoket.send(JSON.stringify(p));
      this.message = "";
    },
    toOperation(type, opera) {
      if (!this.status) return Toast("未链接！");
      if (this.timeout) clearInterval(this.timeout);
      this.touch = type + "-" + opera;
      this.timeout = setInterval(() => {
        if (!this.touch) clearInterval(this.timeout);
        let p = {
          id: this.creatID(),
          controller: {}
        };
        p.controller[type] = opera;
        this.scoket && this.scoket.send(JSON.stringify(p));
      }, Config.robotMoveTimeout);
    },
    createRobotLink() {
      if (!window.WebSocket) return Toast("该版本暂时不支持");
      let _this = this;
      this.scoket && this.scoket.onclose() && (this.scoket = undefined);
      console.log("开始链接");
      this.scoket = new WebSocket(
        Config.robotBaseWss +
          "/ws/app/event?clientId=" +
          Config.robotClientId +
          "&deviceId=" +
          this.deviceId +
          "&token=" +
          this.robotToken
      );
      this.scoket.onmessage = function(event) {
        var data = JSON.parse(event.data || "{}");
        // 处理数据
        let dialogue = {
          type: "",
          text: data.reply
        };
        console.log("接收------>", data);
        let dialogueList = JSON.parse(JSON.stringify(this.dialogueList));
        dialogueList.push(dialogue);
        this.dialogueList = dialogueList;
      };
      this.scoket.onopen = function() {
        _this.status = true;
        console.log("链接成功");
      };
      this.scoket.onerror = function() {
        _this.status = false;
        console.log("链接错误");
        Toast("未链接！");
      };
      this.scoket.onclose = function() {
        _this.status = false;
        console.log("链接断开");
        Toast("未链接！");
      };
    },
    change(e) {
      if (!e) return;
      this.deviceId = e;
      this.createRobotLink();
    },
    reset() {
      let l = [];
      let start = this.qPageSize * (this.qPage - 1);
      for (let i = 0; i < this.qPageSize; i++) {
        let index =
          i + start >= this.quetion.length
            ? i + start - this.quetion.length
            : i + start;
        const v = this.quetion[index];
        l.push(v);
      }
      this.q = l;
      if (this.qPageSize * this.qPage > this.quetion.length) {
        this.qPage = 1;
      } else {
        this.qPage++;
      }
    }
  },
  mounted() {
    this.$pageParams = currentUrlToParams();
    this.type = this.$pageParams.pattern - 0;
    this.reset();
    getRobotToken().then(res => {
      if (res.error_code !== 0) return Toast("机器人走丢了");
      this.robotToken = res.token || "";
      getRobotClient({
        clientId: Config.robotClientId,
        token: this.robotToken
      }).then(r => {
        this.$refs.scroll.scrollTop = this.$refs.msgScroll.scrollHeight;
        if (r.error_code !== 0) return Toast("暂无线上设备");
        this.robotList = (r.result || []).map(v => {
          return {
            text: v.deviceName,
            value: v.deviceId
          };
        });
        this.change(this.robotList[0] ? this.robotList[0].value : "");
      });
    });
  },
  beforeDestroy: function() {},
  components: {
    vanButton,
    vanCell,
    vanCol,
    vanRow,
    vanIcon,
    vanField,
    vanImage,
    vanDropdownMenu,
    vanDropdownItem
  }
};
</script>
<style lang="scss">
#robot {
  padding: 0.1rem 0.16rem;
  .msg {
    padding: 0.1rem;
    height: 3rem;
    overflow-y: scroll;
    .defaultQuestion {
      padding: 5px;
      color: #222;
      line-height: 2em;
      font-size: 0.14rem;
      border-radius: 5px;
      word-wrap: break-word;
      box-shadow: rgba(122, 122, 122, 0.2) 0px 0px 5px;
      .queryTitle {
        padding: 3px;
        position: relative;
        .reset {
          position: absolute;
          font-size: 16px;
        }
        .img {
          right: 5px;
          bottom: 3px;
        }
      }
    }
    .msgBg {
      padding: 5px 3px;
      > div {
        padding: 5px;
        color: #fff;
        border-radius: 5px;
        word-wrap: break-word;
        background-color: #959595;
      }
    }
  }
  .control {
    margin-top: 0.05rem;
    width: 173px;
    text-align: center;
    position: relative;
    padding: 3px;
    .bg {
      width: 0;
      height: 0;
      border: 83px solid #fafafa;
      border-radius: 50%;
      position: absolute;
      z-index: -1;
    }
    .btnClass {
      width: 45px;
      height: 55px;
      line-height: 55px;
      display: inline-block;
    }
    .conBtnGroup {
      display: flex;
      > * {
        flex: 1;
      }
      .centerImg {
        width: 0.56rem;
        height: 0.55rem;
        text-align: center;
        padding: 0.1rem;
        border: 1px solid #eee;
        background-color: #dadada;
        border-radius: 50%;
      }
    }
  }
}
</style>
