<template>
  <div class="app-container h100p flex-col">
    <page-header :content="id?'编辑':'添加'"></page-header>
    <el-form ref="dataForm" :model="dataForm" :rules="dataRules" label-width="100px">
      <el-form-item label="房间名称" prop="name">
        <el-input v-model.trim="dataForm.name" class="input-width" clearable maxlength="20" minlength="2" placeholder="房间名称"></el-input>
      </el-form-item>

      <el-form-item label="房间编号" prop="number">
        <el-input v-model.trim="dataForm.number" class="input-width" clearable maxlength="20" minlength="8" placeholder="请输入房间编号"></el-input>
      </el-form-item>

      <el-form-item label="房间位置" prop="floorId">
        <el-cascader
            ref="floorId"
            v-model="dataForm.floorId"
            :options="buildingTree"
            class="input-width"
            clearable
            :props="floorProps"
            filterable
            placeholder="请选择房间位置">
        </el-cascader>
      </el-form-item>

      <el-form-item label="关联项目" prop="checkItems">
        <div class="flex flex-warp">
          <el-tag style="margin: 4px 5px 4px 0" :key="checkItem.id" v-for="checkItem in dataForm.checkItems" closable @close="removeCheckItem(checkItem)">
            {{ checkItem.name }}
          </el-tag>
          <el-tag style="margin: 4px 5px 4px 0; cursor: pointer" @click="checkItemDialogVisible = true" effect="dark">编辑</el-tag>
        </div>
      </el-form-item>
    </el-form>
    <page-footer showConfirm width="600px" @cancel="onCancel" @confirm="onConfirm"></page-footer>

    <el-dialog v-if="checkItemDialogVisible" :visible.sync="checkItemDialogVisible" width="1200px">
      <check-item :selectable="true" :selected="dataForm.checkItems" @select="onCheckItemSelect"></check-item>
    </el-dialog>
  </div>
</template>

<script>

import {validateNotEmpty} from "@/utils/validate";
import checkItem from "@/views/patrol/inspection/inquiry"

export default {
  name: "DeviceRoomEdit",
  watch: {},

  components: {checkItem},

  data() {
    return {
      id: undefined, // 数据id
      disabled: true,
      dataForm: {
        id: undefined, // 房间id
        name: undefined, // 房间名称
        number: undefined, // 房间编号
        floorId: undefined, // 楼层id
        checkItems: undefined, // 关联项目
      },
      buildingTree: undefined, // 楼栋列表
      floorProps: {
        label: 'name',
        value: 'id',
        emitPath: false,
        lazy: true,
        lazyLoad: (node, resolve) => {
          if (node.level === 1) {
            if (node.children.length) {
              resolve(undefined);
            } else {
              // 加载楼层
              this.$axios.get(`/v1/device/floor/list/option/${node.data.id.replace('building', '')}`, undefined, false).then((data) => {
                resolve(data.map(item => {
                  item.leaf = true;
                  return item;
                }));
              });
            }
          }
        }
      },
      checkItemsProps: {
        label: 'name',
        value: 'id',
        emitPath: false,
        multiple: true,
        lazy: true,
        checkStrictly: true,
        lazyLoad: (node, resolve) => {
          if (node.level === 2) {
            // 加载检查项
            this.$axios.get(`/v1/check/item/list/option`, {params: {itemType: node.parent.data.itemType, isScore: node.data.isScore}}, false).then((data) => {
              resolve(data.map(item => {
                item.leaf = true;
                return item;
                // 过滤已从详情中加载的检查项，避免重复显示
              }).filter(item => this.dataForm.checkItems.indexOf(item.id) === -1));
            });
          } else {
            resolve(undefined);
          }
        }
      },
      dataRules: {
        'name': [{validator: validateNotEmpty, errorMessage: "房间名称不能为空", required: true, trigger: 'blur'}],
        'number': [{validator: validateNotEmpty, errorMessage: "房间编号不能为空", required: true, trigger: 'blur'}],
        'floorId': [{validator: validateNotEmpty, message: "房间位置不能为空", required: true, trigger: 'change'}],
      },

      checkItemDialogVisible: false
    }
  },

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

  methods: {
    // 初始化数据
    initData() {
      this.id = this.$route.query.id;
      if (this.id) {
        this.getDetail(this.id);
      } else {
        this.$axios.get('/v1/device/building/list/option', undefined, false).then(data => {
          this.buildingTree = data.map(item => {
            item.id = 'building' + item.id;
            item.leaf = false;
            return item;
          });
        });
      }
    },

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

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let dataForm = JSON.parse(JSON.stringify(this.dataForm));
          dataForm.checkItems = dataForm.checkItems && dataForm.checkItems.map(item => item.id);
          if (this.id) { // 更新
            this.$axios.put('/v1/device/room/update', dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$eventBus.$emit("DeviceRoomUpdate");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post('/v1/device/room/add', dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$eventBus.$emit("DeviceRoomAdd");
              this.onCancel();
            });
          }
        }
      });
    },

    // 获取详情
    getDetail(roomId) {
      // 加载楼栋
      const buildingPromise = this.$axios.get('/v1/device/building/list/option', undefined, false);
      // 加载房间信息
      const roomPromise = this.$axios.get(`/v1/device/room/query/${roomId}`);
      Promise.all([buildingPromise, roomPromise]).then(data => {
        // 楼栋树处理
        const buildingTree = data[0].map(item => {
          // 楼栋id处理，避免树中id重复
          item.id = "building" + item.id;
          item.leaf = false;
          return item;
        });
        const roomInfo = data[1];
        roomInfo.buildingId = "building" + roomInfo.buildingId;
        // 加载选中楼栋的所有楼层
        this.$axios.get(`/v1/device/floor/list/option/${roomInfo.buildingId.replace('building', '')}`, undefined, false).then((data) => {
          // 装配楼栋树
          buildingTree.find(item => item.id === roomInfo.buildingId).children = data.map(item => {
            item.leaf = true;
            return item;
          })
          this.buildingTree = buildingTree;
          this.dataForm = roomInfo;
        })
      })
    },

    // 选中选择项
    onCheckItemSelect(selectItem) {
      const list = [];
      selectItem.forEach(value => {
        list.push({id: value.id, name: value.itemName})
      })
      this.dataForm.checkItems = list;
      this.checkItemDialogVisible = false;
    },

    // 删除选择项
    removeCheckItem(checkItem) {
      const index = this.dataForm.checkItems.findIndex(item => item.id === checkItem.id);
      this.dataForm.checkItems.splice(index, 1);
      console.log(checkItem);
    },
  },
}
</script>
<style lang="scss">
.room-popper-class {
  .el-checkbox .is-disabled {
    display: none !important;
  }
}
</style>
<style lang="scss" scoped>
.app-container {
  .input-width {
    width: 500px;
  }
}
</style>
