<template>
  <el-row>
    <el-col :span="3">
      <div class="box">
        <el-row class="tac">
          <el-col :span="12">
            <el-menu
              default-active="2"
              class="el-menu-vertical-demo"
              @open="handleOpen"
              @close="handleClose"
              background-color="#545c64"
              text-color="#fff"
              active-text-color="#ffd04b"
            >
              <el-submenu index="1">
                <template slot="title">
                  <i class="el-icon-location"></i>
                  <span>系统监控</span>
                </template>
                <el-menu-item-group>
                  <el-menu-item index="1-1">选项1</el-menu-item>
                  <el-menu-item index="1-2">选项2</el-menu-item>
                </el-menu-item-group>
              </el-submenu>
              <el-submenu index="2">
                <template slot="title">
                  <i class="el-icon-location"></i>
                  <span>业务数据运维</span>
                </template>
                <el-menu-item-group>
                  <el-menu-item index="2-1">选项1</el-menu-item>
                  <el-menu-item index="2-2">选项2</el-menu-item>
                </el-menu-item-group>
              </el-submenu>
            </el-menu>
          </el-col>
        </el-row>
      </div>
    </el-col>
    <el-col :span="21">
      <div style="width: 100%; height: 92vh; background-color: gray"></div>
    </el-col>
  </el-row>
</template>

<script>
import {
  getList,
  getDeptLazyTree,
  getDeptLazyTree2,
  remove,
  add,
  getDetails,
  getQy,
  getLc,
  getQy1,
  getLc1,
  saveImg,
  getDetail,
} from "@/api/equipment/index";
import { mapGetters } from "vuex";
import website from "@/config/website";
import { getToken } from "@/util/auth";

export default {
  data() {
    return {
      options: [],
      iDisabled: true,
      eqiupType: "", //操作状态
      build: [], //区域选项
      floored: [], //楼层选项
      props: {
        value: "key",
        label: "title",
        emitPath: false,
        // lazy: true,
        // lazyLoad(node, resolve) {
        // 	console.log(node)
        // 	const parentId = (node.level === 0) ? 0 : node.data.id;
        // 	getDeptLazyTree(parentId).then(res => {
        // 		console.log(res)
        // 		resolve(res.data.data.map(item => {
        // 			return {
        // 				...item,
        // 				leaf: !item.hasChildren
        // 			}
        // 		}))
        // 	});
        // }
      },
      ruleForm: {
        classCode: null, //设备类型
        // 通知设置
        warnVO: {
          warnLevel: null, //报警级别
          notifier: null, //通知人
        },
        // 通讯设置
        electricConfig: {
          ip: null, //ip地址
          port: null, //端口号
          offsetData: null, //数据偏移量
          offsetStatus: null, //状态偏移量
        },
        lightConfigPowerVO: {
          mac: null, //设备号
          addr: null, //线路地址
        },
        thirdId: null, //第三方id
        area: null, //模型
        build: null, //区域
        floored: null, //楼层
        // 基础配置
        code: null, //编码
        name: null, //名称
        shortName: null, //简称
        brand: null, //厂家
        useStartTime: null, //使用时间
        location: null, //具体位置
        tendingUser: null,
        tendingPhone: null,
        tendingTime: null,
      },
      rules: {
        warnVO: {
          warnLevel: [
            {
              required: true,
              message: "请选择报警级别",
              trigger: "change",
            },
          ],
          notifier: [
            {
              required: true,
              message: "请选择通知人",
              trigger: "change",
            },
          ],
        },
        electricConfig: {
          ip: [
            {
              required: true,
              message: "请输入内容",
              trigger: "blur",
            },
          ],
          port: [
            {
              required: true,
              message: "请输入内容",
              trigger: "blur",
            },
          ],
          offsetData: [
            {
              required: true,
              message: "请输入内容",
              trigger: "blur",
            },
          ],
          offsetStatus: [
            {
              required: true,
              message: "请输入内容",
              trigger: "blur",
            },
          ],
        },

        // mqttdkh: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // dyzt: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // fbzt: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // appkey: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // secret: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        thirdId: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
        lightConfigPowerVO: {
          mac: [
            {
              required: true,
              message: "请输入内容",
              trigger: "blur",
            },
          ],
          addr: [
            {
              required: true,
              message: "请输入内容",
              trigger: "blur",
            },
          ],
        },
        // ywqipdz: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // ttipdz: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // httpdkh: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // websocketdkh: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        area: [
          {
            required: true,
            message: "请选择模型",
            trigger: "change",
          },
        ],
        // sb: [{
        // 	required: true,
        // 	message: '请选择设备',
        // 	trigger: 'change'
        // }],
        // sb2: [{
        // 	required: true,
        // 	message: '请选择设备',
        // 	trigger: 'change'
        // }],
        build: [
          {
            required: true,
            message: "请选择区域",
            trigger: "change",
          },
        ],
        floored: [
          {
            required: true,
            message: "请选择楼层",
            trigger: "change",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
        shortName: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
        brand: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
        useStartTime: [
          {
            type: "string",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        location: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
        // tendingUser: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // tendingPhone: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'blur'
        // }],
        // tendingTime: [{
        // 	required: true,
        // 	message: '请输入内容',
        // 	trigger: 'change'
        // }],
      },
      equipmentBox: false,
      equipmentTit: "新增设备",
      form: {},
      search: {},
      excelBox: false,
      selectionList: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      treeDeptId: this.$route.query.classCode
        ? this.$route.query.classCode
        : "",
      treeData: [],
      treeOption: {
        nodeKey: "id",
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = node.level === 0 ? 0 : node.data.id;
          getDeptLazyTree(parentId).then((res) => {
            resolve(
              res.data.data.map((item) => {
                return {
                  ...item,
                  leaf: !item.hasChildren,
                };
              })
            );
          });
        },
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          labelText: "标题",
          label: "title",
          value: "value",
          children: "children",
        },
      },
      option: {
        addBtn: false,
        editBtn: false,
        delBtn: false,
        // height: 'auto',
        // calcHeight: 80,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        //dialogType: 'drawer',
        dialogClickModal: false,
        column: [
          {
            label: "设备种类",
            prop: "className",
          },
          {
            label: "设备名称",
            prop: "name",
            search: true,
          },
          {
            label: "设备编号",
            prop: "code",
          },
          {
            label: "生产厂家",
            prop: "brand",
          },
          {
            label: "设备位置",
            prop: "location",
            search: true,
          },
          {
            label: "状态",
            prop: "statusName",
          },
          {
            label: "投入使用时间",
            prop: "useStartTime",
          },
          {
            label: "固定资产编号",
            prop: "inventarNummer",
          },
          {
            label: "更新时间",
            prop: "updateTime",
          },
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/blade-user/import-user",
          },
          {
            label: "数据覆盖",
            prop: "isCovered",
            type: "switch",
            align: "center",
            width: 80,
            dicData: [
              {
                label: "否",
                value: 0,
              },
              {
                label: "是",
                value: 1,
              },
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: "请选择是否覆盖",
                trigger: "blur",
              },
            ],
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      imgList: [],
      fileList: [],
    };
  },
  watch: {},
  computed: {
    // 勾选值处理
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    equipmentType() {
      if (this.ruleForm.classCode) {
        return this.ruleForm.classCode.slice(0, 2);
      }
      return null;
    },
  },
  mounted() {
    if (this.$route.query.code) {
      getDetail({ equipCode: this.$route.query.code }).then((res) => {
        console.log(res);
        this.ruleForm = res.data.data;
        this.equipmentBox = true;
        this.eqiupType = "look";
        this.equipmentTit = "查看设备";
      });
    }
    getDeptLazyTree2().then((res) => {
      let data = res.data.data;
      for (let i = 0; i < data.length; i++) {
        data[i].key = data[i].key.length < 4 ? "0" + data[i].key : data[i].key;
        if (data[i].hasChildren) {
          for (let a = 0; a < data[i].children.length; a++) {
            data[i].children[a].key =
              data[i].children[a].key.length < 4
                ? "0" + data[i].children[a].key
                : data[i].children[a].key;
          }
        }
      }
      this.options = data;
    });
  },
  methods: {
    // 左侧属性结构点击
    nodeClick(data) {
      this.treeDeptId = data.key;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    // 清空搜索
    searchReset() {
      this.query = {};
      this.treeDeptId = "";
      this.onLoad(this.page);
    },
    // 点击搜索
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    // 勾选时触发 获得勾选项
    selectionChange(list) {
      this.selectionList = list;
    },
    // 清除勾选项 初始化
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    // 图片上传成功
    handleSuccess(response, file, fileList) {
      console.log(response);
      if (response.code == 200) {
        this.imgList.push(response.data.link);
      }
      console.log(this.imgList);
    },
    beforeRemove(file, fileList) {
      if (this.eqiupType == "look") {
        return false;
      }
    },
    handleRemove(file, fileList) {
      console.log(file);
      if (file.response) {
        this.imgList = this.imgList.filter(
          (item) => item !== file.response.data.link
        );
      } else {
        this.imgList = this.imgList.filter(
          (item) => item !== file.url.slice(file.url)
        );
      }
      console.log(this.imgList);
    },
    // 点击删除
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    // 点击导入
    handleImport() {
      this.excelBox = true;
    },
    // 图片上传后的回调,function(res,done)，done用于结束操作，loading用于中断操作
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    // 导出数据
    // handleExport() {
    // 	this.$confirm("是否导出用户数据?", "提示", {
    // 		confirmButtonText: "确定",
    // 		cancelButtonText: "取消",
    // 		type: "warning"
    // 	}).then(() => {
    // 		window.open(
    // 			`/api/blade-user/export-user?${this.website.tokenHeader}=${getToken()}&account=${this.search.account}&realName=${this.search.realName}`
    // 			);
    // 	});
    // },
    // 点击下载模板
    handleTemplate() {
      window.open(
        `/api/blade-user/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    // 分页页码改变时会触发
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    // pageSize改变时会触发
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 点击刷新按钮触发该事件
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    // 首次加载数据、查询、翻页方法
    onLoad(page, params = {}) {
      this.loading = true;
      console.log(this.treeDeptId);
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query),
        this.treeDeptId
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 新增编辑设备
    handleAdd(type, row) {
      this.equipmentBox = true;
      this.iDisabled = false;
      this.eqiupType = type;
      this.imgList = [];
      this.fileList = [];
      if (type == "add") {
        // 新增
        this.equipmentTit = "新增设备";
      } else if (type == "edit") {
        // 编辑
        this.equipmentTit = "编辑设备";

        getDetails(row.id).then((res) => {
          this.ruleForm = res.data.data;
          console.log("data", this.ruleForm);
          this.ruleForm.images.map((item) => {
            this.fileList.push({ url: item.filePath });
            this.imgList.push(item.filePath);
          });
          console.log("设备编辑", this.ruleForm);
          getQy1(this.ruleForm.area).then((res) => {
            this.build = res.data.data;
          });
          // getLc(this.ruleForm.area).then(res => {
          // 	this.floored = res.data.data;
          // });
        });
      } else {
        this.iDisabled = true;
        // 查看
        this.equipmentTit = "查看设备";
        getDetails(row.id).then((res) => {
          this.ruleForm = res.data.data;
          this.ruleForm.images.map((item) => {
            this.fileList.push({ url: item.filePath });
            this.imgList.push(item.filePath);
          });
          getQy1(this.ruleForm.area).then((res) => {
            this.build = res.data.data;
          });
          // getLc(this.ruleForm.area).then(res => {
          // 	this.floored = res.data.data;
          // });
        });
      }
    },
    chooseFloor(e) {
      getLc1(Number(e)).then((res) => {
        this.ruleForm.floored = null;
        this.floored = res.data.data;
      });
    },
    // 确定
    submitForm(formName) {
      if (!this.ruleForm.classCode) {
        this.$message({
          message: "请选择设备类型",
          type: "warning",
        });
        return;
      }
      if (!this.iDisabled) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // let data = []
            // if(this.imgList.length !== 0){
            // 	this.imgList.map(item =>{
            // 		data.push({
            // 			equipCode:this.ruleForm.code,
            // 			filePath:item
            // 		})
            // 	})
            // }
            console.log(this.imgList);
            let data = {
              equipCode: this.ruleForm.code,
              filepaths: this.imgList.join(","),
            };
            console.log(data);
            saveImg(data).then((res) => {
              if (res.data.code == 200) {
                add(this.ruleForm).then((res) => {
                  this.resetForm("ruleForm");
                  this.page.currentPage = 1;
                  this.onLoad(this.page);
                });
              }
            });
            // }else{
            // 	add(this.ruleForm).then(res => {
            // 		this.resetForm('ruleForm');
            // 		this.page.currentPage = 1;
            // 		this.onLoad(this.page);
            // 	});
            // }
          } else {
            return false;
          }
        });
      } else {
        this.resetForm("ruleForm");
      }
    },
    // 取消
    resetForm(formName) {
      this.ruleForm = {
        classCode: null, //设备类型
        // 通知设置
        warnVO: {
          warnLevel: null, //报警级别
          notifier: null, //通知人
        },
        // 通讯设置
        electricConfig: {
          ip: null, //ip地址
          port: null, //端口号
          offsetData: null, //数据偏移量
          offsetStatus: null, //状态偏移量
        },
        lightConfigPowerVO: {
          mac: null, //设备号
          addr: null, //线路地址
        },
        thirdId: null, //第三方id
        area: null, //模型
        build: null, //区域
        floored: null, //楼层
        // 基础配置
        code: null, //编码
        name: null, //名称
        shortName: null, //简称
        brand: null, //厂家
        useStartTime: null, //使用时间
        location: null, //具体位置
      };
      this.equipmentBox = false;
      this.equipmentTit = "新增设备";
      this.$refs[formName].resetFields();
      this.$refs.cascaderClassroom.$refs.panel.clearCheckedNodes();
      this.$refs.cascaderClassroom.$refs.panel.activePath = [];
      this.equipmentType = null;
    },
    // 添加模型
    addModel(val) {
      // console.log(row)
      this.$router.replace({
        path: "/equipment/model",
        query: {
          row: val,
        },
      }); // 只能用 name
    },
    // 选择模型
    mxChange(val) {
      this.ruleForm.build = null;
      this.ruleForm.floored = null;
      getQy1(this.ruleForm.area).then((res) => {
        // console.log(res)
        this.build = res.data.data;
      });
      // getLc(this.ruleForm.area).then(res => {
      // 	console.log(res)
      // 	this.floored = res.data.data;
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}

.floor {
  .title {
    font-size: 18px;
    color: #303133;
    padding-bottom: 5px;
    border-bottom: 2px solid #e5e5e5;
    margin: 0 0 20px 0;
  }
}

.btn {
  margin-top: 50px;
}
/deep/.el-input {
  width: 220px;
}
.hide {
  /deep/ .el-upload--picture-card {
    display: none;
  }
}
</style>
