<template>
  <div class="app-container">
    <page-header :content="id?'编辑':'添加'"></page-header>
    <el-form label-width="140px" ref="dataForm" :model="dataForm" :rules="dataRules">
      <el-form-item label="路线名称" prop="name">
        <el-input v-model.trim="dataForm.name" placeholder="请输入设备名称" class="input-width" maxlength="32" clearable></el-input>
      </el-form-item>
      <el-form-item label="负责人名称" prop="responsibler">
        <el-input v-model.trim="dataForm.responsibler" placeholder="请输入负责人名称" class="input-width" maxlength="32" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="telephone">
        <el-input v-model.trim="dataForm.telephone" placeholder="请输入联系电话" class="input-width" maxlength="11" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model.trim="dataForm.remark" placeholder="请输入备注" class="input-width" maxlength="512" clearable></el-input>
      </el-form-item>

      <el-form-item label="设备" prop="devices" >
        <el-input
            class="input-width"
            placeholder="输入关键字进行过滤"
            v-model="filterDeviceText">
        </el-input>

        <el-tree
            class="input-width"
            :props="{label:'name',isLeaf: 'leaf'}"
            :filter-node-method="filterDevice"
            :load="loadDevice"
            lazy
            accordion
            show-checkbox
            :default-checked-keys="checkedDevices"
            :default-expanded-keys="expandedDevices"
            node-key="id"
            @check="checkDevice"
            empty-text="无数据"
            ref="devices">
        </el-tree>
      </el-form-item>
    </el-form>
    <page-footer showConfirm @confirm="onConfirm" @cancel="onCancel" width="800px"></page-footer>
  </div>
</template>

<script>

import {validateNotEmpty, validatePhoneCanBeEmpty} from "@/utils/validate";
import Upload from "@/components/Upload";

export default {
  name: "CheckRouteInquireEdit",
  components: {Upload},
  watch: {
    'dataForm.type'(value) {
      if (!value || value !== 1) {
        this.dataForm.layerTotal = undefined;
      }
    },
    filterDeviceText(val) {
      this.$refs['devices'].filter(val);
    }
  },

  data() {
    return {
      id: undefined, // 数据id
      dataForm: {
        id: undefined, // 设备id
        name: undefined, // 设备名称
        roomIds: undefined, // 房间id列表
        deviceIds: undefined, // 设备id列表
        responsibler: undefined, // 负责人名称
        telephone: undefined, // 联系电话
        remark: undefined, // 备注
      },
      checkedDevices: [],
      expandedDevices: [],
      filterDeviceText: undefined,
      dataRules: {
        'name': [{validator: validateNotEmpty, errorMessage: "设备名称不能为空", required: true, trigger: 'blur'}],
        'telephone': [{validator: validatePhoneCanBeEmpty, errorMessage: "设备名称不能为空", required: false, trigger: 'blur'}],
      },
    }
  },

  mounted() {
    this.initData();
  },

  methods: {
    validateNotEmpty,
    // 初始化数据
    initData() {
      this.id = this.$route.query.id;
      if (this.id) {
        this.getDetail(this.id);
      }
    },

    // 取消
    onCancel() {
      this.$router.back();
    },

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let dataForm = JSON.parse(JSON.stringify(this.dataForm));
          let devices = this.$refs.devices.getCheckedKeys(true);
          dataForm.roomIds = devices.filter(item => String(item).startsWith('room')).map(item => Number(item.substr(item.lastIndexOf('-') + 1)));
          dataForm.deviceIds = devices.filter(item => String(item).startsWith('device')).map(item => Number(item.substr(item.lastIndexOf('-') + 1)));
          if (this.id) { // 更新
            this.$axios.put('/v1/check/route/update', dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$eventBus.$emit("CheckRouteInquireUpdate");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post('/v1/check/route/add', dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$eventBus.$emit("CheckRouteInquireAdd");
              this.onCancel();
            });
          }
        }
      });
    },
    merge(deviceTree, roomTree) {
      roomTree?.forEach(room => {
        let device = deviceTree?.find(device => device.id === room.id);
        if (!device) {
          deviceTree?.unshift(room);
        } else {
          this.merge(device.children, room.children);
        }
      })
    },
    //设备过滤
    filterDevice(value, data) {
      return data.name.includes(value);
    },
    // 加载设备
    loadDevice(node, resolve) {
      if (node.level === 0) {
        // 加载楼栋
        this.$axios.get('/v1/device/building/list/option', undefined, false).then((data) => {
          // data.map(item=>{item.disabled = true;})
          resolve(data);
        });
      } else if (node.level === 1) {
        // 加载楼层
        this.$axios.get(`/v1/device/floor/list/option/${node.data.id}`, undefined, false).then((data) => {
          resolve(data.map(item => {
                item.id = `${node.data.id}-${item.id}`;
                // this.expandedDevices.push(item.id);
                // item.disabled = true;
                return item;
              })
          );
        });
      } else if (node.level === 2) {
        // 加载房间
        this.$axios.get(`/v1/device/room/list/option/${node.data.id.substr(node.data.id.lastIndexOf('-') + 1)}`, undefined, false).then((data) => {
          resolve(data.map(item => {
                item.id = `${node.data.id}-${item.id}`;
                // this.expandedDevices.push(item.id);
                // item.disabled = true;
                return item;
              })
          );
        });
      } else if (node.level === 3) {
        // 加载设备
        this.$axios.get(`/v1/device/list/option/${node.data.id.substr(node.data.id.lastIndexOf('-') + 1)}`, undefined, false).then((data) => {
          // node.data.disabled = false;
          // node.parent.data.disabled = false;
          // node.parent.parent.data.disabled = false;
          let devices = data.map(item => {
            item.id = `device-${node.data.id}-${item.id}`;
            item.leaf = true;
            return item;
          });
          devices.unshift({
            'id': `room-${node.data.id}`,
            'leaf': true,
            'name': node.data.name + '自带项目'
          });
          resolve(devices);
        });
      }
    },
    // 设备选中
    checkDevice(data) {
      this.expandedDevices.length = 0;
      let node = this.$refs["devices"].getNode(data);
      this.expandedDevices.push(node.parent.parent.id);
      this.expandedDevices.push(node.parent.id);
      this.expandedDevices.push(data.id);
    },
    // 获取详情
    getDetail(id) {
      // 加载路线详情
      this.$axios.get(`/v1/check/route/query/${id}`).then(data => {
        let expandedDevices = [];
        let checkedDevices = [];
        data.rooms.filter(item => item).forEach(building => {
          expandedDevices.push(building.id);
          building.children.filter(item => item).forEach(floor => {
            expandedDevices.push(`${building.id}-${floor.id}`);
            floor.children.filter(item => item).forEach(room => {
              expandedDevices.push(`${building.id}-${floor.id}-${room.id}`);
              checkedDevices.push(`room-${building.id}-${floor.id}-${room.id}`);
            });
          })
        });
        data.devices.filter(item => item).forEach(building => {
          expandedDevices.push(building.id);
          building.children.filter(item => item).forEach(floor => {
            expandedDevices.push(`${building.id}-${floor.id}`);
            floor.children.filter(item => item).forEach(room => {
              expandedDevices.push(`${building.id}-${floor.id}-${room.id}`);
              room.children.filter(item => item).forEach(device => {
                checkedDevices.push(`device-${building.id}-${floor.id}-${room.id}-${device.id}`);
              });
            });
          });
        });
        delete data.rooms;
        delete data.devices;
        this.expandedDevices = Array.from(new Set(expandedDevices));
        this.checkedDevices = Array.from(new Set(checkedDevices));
        this.dataForm = data;
      })
    },
  }
}
</script>
<style scoped lang="scss">
.app-container {
  ::v-deep .el-tree > .el-tree-node > .el-tree-node__content > label.el-checkbox,
  ::v-deep .el-tree > .el-tree-node > .el-tree-node__children > .el-tree-node > .el-tree-node__content > label.el-checkbox {
    display: none;
  }

  .input-width {
    width: 500px;
  }
}
</style>
