<template>
  <div class="main_root">
    <div class="search_header">
      <div class="search_left">
        <Select
          v-model="searchForm.handled"
          style="margin-right: 10px; width: 120px"
          placeholder="关注状态"
          @on-change="searchList()"
        >
          <Option :value="-1">全部</Option>
          <Option :value="0">未处理</Option>
          <Option :value="1">已处理</Option>
        </Select>
        <Input
          v-model="searchForm.name"
          placeholder="请输入设备号"
          search
          @on-search="searchList()"
          style="width: 200px"
        />
      </div>
      <div class="search_right">
        <Dropdown @on-click="dropdownSelected">
          <div class="drop_btn">
            其他操作<Icon type="ios-arrow-down" class="arrow_down" />
          </div>
          <DropdownMenu slot="list">
            <DropdownItem name="1">恢复出厂</DropdownItem>
            <DropdownItem name="2">发送消息</DropdownItem>
            <DropdownItem name="4">解除锁定</DropdownItem>
            <DropdownItem name="5">锁定</DropdownItem>
            <DropdownItem name="6">更新策略</DropdownItem>
            <DropdownItem name="7">重启设备</DropdownItem>
            <DropdownItem name="9">解除管控</DropdownItem>
            <DropdownItem name="8">合规处理</DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </div>
    </div>
    <div class="table_wrap">
      <Table
        ref="deviceTable"
        :columns="columns"
        :data="searchForm.list"
        @on-selection-change="selectionChange"
      >
        <template slot-scope="{ row }" slot="actionSlot">
          <div class="action_list">
            <div v-if="row.sn && row.num > 0" @click="toDetail(row)">
              违规详情
            </div>
            <div v-if="row.sn" @click="toRestore(row)">恢复出厂</div>
            <div v-if="row.sn" @click="toLogHandle([row.sn])">合规处理</div>
          </div>
        </template>
      </Table>
    </div>
    <div class="page_wrap">
      <Page
        :transfer="true"
        :total="searchForm.total"
        :current="searchForm.page"
        :page-size="searchForm.size"
        :page-size-opts="[10, 20, 40, 60]"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange"
        show-total
        show-sizer
      ></Page>
    </div>
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="controlMessageInfo.show"
      title="发送消息"
    >
      <Form
        v-if="controlMessageInfo.show"
        ref="sendMsgForm"
        :model="controlMessageInfo"
        :rules="rules"
        :label-width="60"
      >
        <FormItem label="标题" prop="title">
          <Input
            v-model="controlMessageInfo.title"
            :maxlength="32"
            show-word-limit
            placeholder="请输入标题，不超过32个字符"
          ></Input>
        </FormItem>
        <FormItem label="内容" prop="content">
          <Input
            type="textarea"
            v-model="controlMessageInfo.content"
            :maxlength="255"
            show-word-limit
            placeholder="请输入内容"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="controlMessageInfo.show = false">取消</Button>
        <Button @click="controlSendMessage()" type="primary" class="primary_btn"
          >保存</Button
        >
      </div>
    </Modal>
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="logDetailInfo.show"
      title="违规详情"
    >
      <div class="user_info">
        <div>
          当前设备绑定用户：<span>{{ logDetailInfo.user.username }}</span>
        </div>
        <div>
          绑定时间: <span>{{ logDetailInfo.user.createtime }}</span>
        </div>
        <div>
          所属班级：<span>{{ logDetailInfo.user.classname }}</span>
        </div>
      </div>
      <div class="table_wrap_modal">
        <Table :columns="detailColumns" :data="logDetailInfo.events">
          <template slot-scope="{ row }" slot="doEventSlot">
            <div>{{ doEventInfo[row.doEvent] }}</div>
          </template>
        </Table>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="logDetailInfo.show = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { doEventInfo } from "@/utils";
import ControlWs from "@/utils/ControlWs";
let controlWs = new ControlWs();
import ControlWSMsg from "@/utils/ControlWSMsg";
import { logPush_add, logdoperate_edit_handled } from "@/api/log";
import {
  device_manager_list_vd,
  device_manager_detail_vd
} from "@/api/device_manager";
export default {
  data() {
    return {
      doEventInfo,
      userInfo: {},
      // ws连接后回发信息
      wsEnterInfo: {
        // 消息ID
        mid: null,
        // 是否进入
        isEnter: false
      },
      searchForm: {
        name: "",
        // 是否处理：0否 1是
        handled: 0,
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      logDetailInfo: {
        show: false,
        user: {},
        events: []
      },
      tableSelection: [],
      controlMessageInfo: {
        show: false,
        title: "",
        content: "",
        snList: [],
        useridList: []
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur"
          }
        ],
        content: [
          {
            required: true,
            message: "请选择内容",
            trigger: "blur"
          }
        ]
      },
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "序号",
          align: "center",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.searchForm.page - 1) * this.searchForm.size +
                1
            );
          }
        },
        /* {
          title: "登录账号",
          key: "loginname",
          align: "center"
        },
        {
          title: "姓名",
          key: "username",
          align: "center"
        }, */
        // {
        //   title: "设备名称",
        //   key: "device",
        //   align: "center"
        // },
        // {
        //   title: "设备型号",
        //   key: "deviceModel",
        //   align: "center"
        // },
        {
          title: "设备号",
          key: "sn",
          align: "center"
        },
        // {
        //   title: "Rom版本",
        //   key: "romVersion",
        //   align: "center"
        // },
        {
          title: "更新时间",
          key: "createtime",
          width: 190,
          align: "center"
        },
        {
          title: "累计违规数量",
          key: "num",
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 260,
          align: "center"
        }
      ],
      detailColumns: [
        {
          title: "序号",
          type: "index",
          align: "center",
          width: 70
        },
        {
          title: "设备使用人",
          key: "username",
          align: "center"
        },
        {
          title: "违规事件",
          slot: "doEventSlot",
          align: "center"
        },
        {
          title: "违规时间",
          key: "createtime",
          width: 190,
          align: "center"
        }
      ]
    };
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.searchList();
    this.initMonitorWS();
  },
  computed: {
    powerParams() {
      return this.$store.getters.powerParams;
    }
  },
  beforeDestroy() {
    controlWs.myevent.$off("ws_error");
    controlWs.myevent.$off("ws_open");
    controlWs.myevent.$off("ws_getmsg");
    controlWs.closeWs();
  },
  methods: {
    initMonitorWS() {
      controlWs.setWs();
      this.getWSEventInfo();
    },
    getWSEventInfo() {
      controlWs.myevent.$on("ws_error", () => {
        this.$Message.error("网络异常，请检查网络");
      });
      controlWs.myevent.$on("ws_open", () => {
        this.sendAfterConnection();
      });
      controlWs.myevent.$on("ws_getmsg", (data) => {
        if (data.code === 666) {
          if (this.wsEnterInfo.mid === data.mid) {
            this.wsEnterInfo.isEnter = true;
          }
        }
        if (!this.wsEnterInfo.isEnter) {
          return;
        }
      });
    },
    // 连接后回发(需确认)
    sendAfterConnection() {
      this.wsEnterInfo.isEnter = false;
      let controlWSMsg = new ControlWSMsg(controlWs.ws, this.userInfo.adminid);
      controlWSMsg.afterConnection({
        userid: String(this.userInfo.adminid),
        username: this.userInfo.aname,
        schoolid: this.powerParams.objectid,
        usertype: 1
      });
      controlWSMsg.send((isSend) => {
        if (isSend) {
          this.wsEnterInfo.mid = controlWSMsg.mid;
        }
      });
    },
    // 搜索
    searchList() {
      this.searchForm.page = 1;
      this.getList();
    },
    // 页码改变
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },
    // 每页显示数量改变
    pageSizeChange(size) {
      this.searchForm.size = size;
      this.searchForm.page = 1;
      this.getList();
    },
    // 获取列表
    getList() {
      this.tableSelection = [];
      device_manager_list_vd({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        page: this.searchForm.page,
        size: this.searchForm.size,
        handled: this.searchForm.handled,
        name: this.searchForm.name
      }).then((data) => {
        if (data.code === 0) {
          this.searchForm.list = data.obj.data;
          this.searchForm.total = data.obj.total;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 违规详情
    toDetail(row) {
      device_manager_detail_vd({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        size: 20,
        name: row.sn
      }).then((data) => {
        if (data.code === 0) {
          this.logDetailInfo = {
            show: true,
            user: data.obj.user || {},
            events: data.obj.events || []
          };
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 恢复出厂
    toRestore(row) {
      if (!row.sn) {
        this.$Message.error("设备不存在");
        return;
      }
      this.$Modal.confirm({
        title: "提示",
        content: "确定对所选设备进行恢复出厂设置操作吗？",
        onOk: () => {
          this.controlRestoreFactory([row.sn], row.userid ? [row.userid] : []);
        },
        onCancel: () => {}
      });
    },
    // 合规处理
    toLogHandle(snList) {
      this.$Modal.confirm({
        title: "提示",
        content: "确定对所选设备进行合规处理操作吗？",
        onOk: () => {
          logdoperate_edit_handled({
            sn: snList
          }).then((data) => {
            if (data.code === 0) {
              this.$Message.success(data.msg);
              this.searchList();
            } else {
              this.$Message.error(data.msg);
            }
          });
        },
        onCancel: () => {}
      });
    },
    selectionChange(selection) {
      this.tableSelection = selection;
    },
    // 其他操作
    dropdownSelected(name) {
      if (!this.wsEnterInfo.isEnter) {
        this.$Message.error("推送服务不可用");
        return;
      }
      let userList = this.tableSelection.filter((row) => row.sn);
      let snList = [];
      let useridList = [];
      userList.forEach((item) => {
        snList.push(item.sn);
        if (item.userid) {
          useridList.push(item.userid);
        }
      });
      if (name === "1") {
        // 恢复出厂
        if (snList.length === 0) {
          this.$Message.error("请勾选至少一个设备。");
          return;
        }
        this.$Modal.confirm({
          title: "提示",
          content: "确定对所选设备进行恢复出厂设置操作吗？",
          onOk: () => {
            this.controlRestoreFactory(snList, useridList);
          },
          onCancel: () => {}
        });
      } else if (name === "2") {
        // 发送消息
        if (snList.length === 0) {
          this.$Message.error("请勾选至少一个设备。");
          return;
        }
        this.controlMessageInfo = {
          show: true,
          title: "",
          content: "",
          snList,
          useridList
        };
      } else if (name === "4") {
        // 解除锁定
        if (snList.length === 0) {
          this.$Message.error("请勾选至少一个设备。");
          return;
        }
        this.$Modal.confirm({
          title: "提示",
          content: "确定对所选设备进行解除锁定操作吗？",
          onOk: () => {
            this.controlRemoveLimit(snList, useridList);
          },
          onCancel: () => {}
        });
      } else if (name === "5") {
        // 锁定
        if (snList.length === 0) {
          this.$Message.error("请勾选至少一个设备。");
          return;
        }
        this.$Modal.confirm({
          title: "提示",
          content: "确定对所选设备进行锁定操作吗？",
          onOk: () => {
            this.controlLimitedUse(snList, useridList);
          },
          onCancel: () => {}
        });
      } else if (name === "6") {
        // 更新策略
        if (snList.length === 0) {
          this.$Message.error("请勾选至少一个设备。");
          return;
        }
        this.$Modal.confirm({
          title: "提示",
          content: "确定对所选设备进行更新策略操作吗？",
          onOk: () => {
            this.controlUpdateStrategy(snList, useridList);
          },
          onCancel: () => {}
        });
      } else if (name === "7") {
        // 重启设备
        if (snList.length === 0) {
          this.$Message.error("请勾选至少一个设备。");
          return;
        }
        this.$Modal.confirm({
          title: "提示",
          content: "确定对所选设备进行重启设备操作吗？",
          onOk: () => {
            this.controlRebootDevice(snList, useridList);
          },
          onCancel: () => {}
        });
      } else if (name === "8") {
        // 合规处理
        if (snList.length === 0) {
          this.$Message.error("请勾选至少一个设备。");
          return;
        }
        this.toLogHandle(snList);
      } else if (name === "9") {
        // 解除管控
        if (snList.length === 0) {
          this.$Message.error("请勾选至少一个设备。");
          return;
        }
        this.$Modal.confirm({
          title: "提示",
          content: "确定对所选设备进行解除管控操作吗？",
          onOk: () => {
            this.controlRemoveDevice(snList, useridList);
          },
          onCancel: () => {}
        });
      }
    },
    // 恢复出厂设置
    controlRestoreFactory(snList, useridList) {
      let controlWSMsg = new ControlWSMsg(
        controlWs.ws,
        this.userInfo.adminid,
        snList
      );
      controlWSMsg.restoreFactory();
      controlWSMsg.send((isSend) => {
        if (isSend) {
          this.$Message.success("推送成功");
        } else {
          this.$Message.error("推送失败");
        }
      });
      this.$refs.deviceTable.selectAll(false);
      let form = {
        pushType: 6,
        pushObj: 1
      };
      form.userids = useridList;
      this.addPushLog(form);
    },
    // 发送消息
    controlSendMessage() {
      this.$refs.sendMsgForm.validate((valid) => {
        if (valid) {
          this.controlMessageInfo.show = false;
          let snList = this.controlMessageInfo.snList;
          let useridList = this.controlMessageInfo.useridList;
          let controlWSMsg = new ControlWSMsg(
            controlWs.ws,
            this.userInfo.adminid,
            snList
          );
          controlWSMsg.msgContent(
            JSON.stringify({
              title: this.controlMessageInfo.title,
              content: this.controlMessageInfo.content
            })
          );
          controlWSMsg.send((isSend) => {
            if (isSend) {
              this.$Message.success("推送成功");
            } else {
              this.$Message.error("推送失败");
            }
          });
          let form = {
            pushType: 1,
            pushObj: 1,
            msgTitle: this.controlMessageInfo.title,
            content: this.controlMessageInfo.content
          };
          form.userids = useridList;
          this.$refs.deviceTable.selectAll(false);
          this.addPushLog(form);
        }
      });
    },
    // 解除锁定
    controlRemoveLimit(snList, useridList) {
      let controlWSMsg = new ControlWSMsg(
        controlWs.ws,
        this.userInfo.adminid,
        snList
      );
      controlWSMsg.removeLimit();
      controlWSMsg.send((isSend) => {
        if (isSend) {
          this.$Message.success("推送成功");
        } else {
          this.$Message.error("推送失败");
        }
      });
      this.$refs.deviceTable.selectAll(false);
      let form = {
        pushType: 2,
        pushObj: 1
      };
      form.userids = useridList;
      this.addPushLog(form);
    },
    // 锁定
    controlLimitedUse(snList, useridList) {
      let controlWSMsg = new ControlWSMsg(
        controlWs.ws,
        this.userInfo.adminid,
        snList
      );
      controlWSMsg.limitedUse();
      controlWSMsg.send((isSend) => {
        if (isSend) {
          this.$Message.success("推送成功");
        } else {
          this.$Message.error("推送失败");
        }
      });
      this.$refs.deviceTable.selectAll(false);
      let form = {
        pushType: 3,
        pushObj: 1
      };
      form.userids = useridList;
      this.addPushLog(form);
    },
    // 更新策略
    controlUpdateStrategy(snList, useridList) {
      let controlWSMsg = new ControlWSMsg(
        controlWs.ws,
        this.userInfo.adminid,
        snList
      );
      controlWSMsg.updateStrategy();
      controlWSMsg.send((isSend) => {
        if (isSend) {
          this.$Message.success("推送成功");
        } else {
          this.$Message.error("推送失败");
        }
      });
      this.$refs.deviceTable.selectAll(false);
      let form = {
        pushType: 4,
        pushObj: 1
      };
      form.userids = useridList;
      this.addPushLog(form);
    },
    // 重启设备
    controlRebootDevice(snList, useridList) {
      let controlWSMsg = new ControlWSMsg(
        controlWs.ws,
        this.userInfo.adminid,
        snList
      );
      controlWSMsg.rebootDevice();
      controlWSMsg.send((isSend) => {
        if (isSend) {
          this.$Message.success("推送成功");
        } else {
          this.$Message.error("推送失败");
        }
      });
      this.$refs.deviceTable.selectAll(false);
      let form = {
        pushType: 5,
        pushObj: 1
      };
      form.userids = useridList;
      this.addPushLog(form);
    },
    // 解除管控
    controlRemoveDevice(snList, useridList) {
      let controlWSMsg = new ControlWSMsg(
        controlWs.ws,
        this.userInfo.adminid,
        snList
      );
      controlWSMsg.removeControl();
      controlWSMsg.send((isSend) => {
        if (isSend) {
          this.$Message.success("推送成功");
        } else {
          this.$Message.error("推送失败");
        }
      });
      this.$refs.deviceTable.selectAll(false);
      let form = {
        pushType: 7,
        pushObj: 1
      };
      form.userids = useridList;
      this.addPushLog(form);
    },
    // 添加推送日志
    addPushLog(form) {
      if (form.userids && form.userids.length === 0) {
        return;
      }
      logPush_add(form).then((data) => {
        if (data.code === 0) {
          this.$Message.success(data.msg);
        } else {
          this.$Message.error(data.msg);
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.main_root {
  .search_header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 16px 16px;
    .search_left {
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }
    .search_right {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      /deep/.ivu-dropdown {
        &:hover {
          .arrow_down {
            transform: rotate(180deg);
          }
        }
      }
      .drop_btn {
        padding: 0 6px 0 10px;
        line-height: 30px;
        border-radius: 8px;
        border: 1px solid #d8dce9;
        cursor: pointer;
        .arrow_down {
          margin: 4px;
          color: #96acdf;
          transition: all 0.2s ease-in-out;
        }
      }
    }
  }
}
.table_wrap_modal {
  border: 1px solid #e8eaec;
  border-bottom: none;
}
.user_info {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 16px;
  font-size: 16px;
  color: #7c8db5;
  > div {
    margin-right: 20px;
    span {
      color: #2e4276;
    }
  }
}
</style>
