<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" minlength="2" maxlength="20" clearable></el-input>
      </el-form-item>

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

      <el-form-item label="设备厂家" prop="vendor">
        <el-input v-model.trim="dataForm.vendor" placeholder="请输入设备厂家" class="input-width" minlength="2" maxlength="20" clearable></el-input>
      </el-form-item>

      <el-form-item label="设备型号" prop="model">
        <el-input v-model.trim="dataForm.model" placeholder="请输入设备型号" class="input-width" minlength="2" maxlength="20" clearable></el-input>
      </el-form-item>

      <el-form-item label="设备类型" prop="type">
        <el-select :disabled="id!==undefined" v-model="dataForm.type" placeholder="请选择设备类型" class="input-width" clearable>
          <el-option v-for="item in typeList" :value="item.id" :key="item.id" :label="item.label"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item v-if="dataForm.type===1" label="设备总层数" prop="layerTotal">
        <el-input v-if="dataForm.type===1" :disabled="id!==undefined" class="input-width" placeholder="请输入设备总层数" v-model.trim="dataForm.layerTotal" maxlength="3" oninput="value=value.replace(/[^\d]/g,'')">
          <template slot="append">层</template>
        </el-input>
      </el-form-item>

      <el-form-item
          v-for="(params, index) in dataForm.params"
          :key="index"
          :label="index?'':'设备参数'"
          :prop="'params.'+index"
          :rules="{ required: index!==dataForm.params.length-1, validator: validateNotEmpty, message: '设备参数不能为空', trigger: 'blur'}">
        <div class="flex align-center">
          <el-input v-model="dataForm.params[index]" class="input-width" placeholder="请输入设备参数" type="textarea" :autosize="{ minRows: 1}" show-word-limit></el-input>
          <el-link v-if="index===dataForm.params.length-1" type="primary" @click.prevent="addParams" icon="el-icon-plus" class="ml10">添加</el-link>
          <el-link v-else type="danger" @click.prevent="removeParams(params)" icon="el-icon-delete" class="ml10">删除</el-link>
        </div>
      </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-item label="上传照片" prop="images">
        <upload v-model="dataForm.images" :width="114" :height="114" tips="上传照片" multiple accept="image/jpeg,image/gif,image/png"></upload>
      </el-form-item>

      <el-form-item label="上传文件" prop="images">
        <upload v-model="dataForm.files" :width="120" :height="36" accept="*/*" multiple :limit="5">
          <div style="font-size: 12px;color: #00BAFF">
            上传文件
          </div>
        </upload>
      </el-form-item>
    </el-form>
    <page-footer showConfirm @confirm="onConfirm" @cancel="onCancel" width="800px"></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 Upload from "@/components/Upload";
import checkItem from "@/views/patrol/inspection/inquiry"


export default {
  name: "DeviceDeviceEdit",
  components: {Upload, checkItem},
  watch: {
    'dataForm.type'(value) {
      if (!value || value !== 1) {
        this.dataForm.layerTotal = undefined;
      }
    }
  },

  data() {
    return {
      id: undefined, // 数据id
      dataForm: {
        id: undefined, // 设备id
        name: undefined, // 设备名称
        roomId: undefined, // 房间id
        number: undefined, // 设备编号
        vendor: undefined, // 设备厂家
        model: undefined, // 设备型号
        type: undefined, // 设备类型 1:机柜设备  99:其他设备
        layerTotal: undefined, // 设备层数 机柜设备有效
        params: [''], // 设备参数 json格式
        images: [], // 设备照片 json格式
        files: [], // 设备附件 json格式
      },
      buildingTree: undefined, // 楼栋列表
      props: {
        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', '')}`).then((data) => {
                resolve(data.map(item => {
                  item.id = 'floor' + item.id;
                  item.leaf = false;
                  return item;
                }));
              });
            }
          } else if (node.level === 2) {
            if (node.children.length) {
              resolve(undefined);
            } else {
              // 加载房间
              this.$axios.get(`/v1/device/room/list/option/${node.data.id.replace('floor', '')}`).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);
          }
        }
      },
      typeList: [{id: 1, label: "机柜设备"}, {id: 99, label: "其他设备"}],
      dataRules: {
        'name': [{validator: validateNotEmpty, errorMessage: "设备名称不能为空", required: true, trigger: 'blur'}],
        'roomId': [{validator: validateNotEmpty, errorMessage: "房间名称不能为空", required: true, trigger: 'blur'}],
        'number': [{validator: validateNotEmpty, errorMessage: "设备编号不能为空", required: true, trigger: 'blur'}],
        'type': [{validator: validateNotEmpty, errorMessage: "设备类型不能为空", required: true, trigger: 'change'}],
        'layerTotal': [{validator: validateNotEmpty, errorMessage: "机柜层数不能为空", required: true, trigger: 'change'}],
      },

      checkItemDialogVisible: false
    }
  },

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

  methods: {
    validateNotEmpty,
    // 初始化数据
    initData() {
      this.id = this.$route.query.id;
      if (this.id) {
        this.getDetail(this.id);
      } else {
        this.$axios.get('/v1/device/building/list/option').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?.map(item => item.id);
          dataForm.params = dataForm.params.filter(item => item.trim() !== '').join(',');
          dataForm.images = JSON.stringify(dataForm.images);
          dataForm.files = JSON.stringify(dataForm.files);
          if (this.id) { // 更新
            this.$axios.put('/v1/device/update', dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$eventBus.$emit("DeviceDeviceUpdate");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post('/v1/device/add', dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$eventBus.$emit("DeviceDeviceAdd");
              this.onCancel();
            });
          }
        }
      });
    },

    // 获取详情
    getDetail(id) {
      // 加载设备信息
      this.$axios.get(`/v1/device/query/${id}`).then(data => {
        const deviceInfo = data;
        // 加载楼栋信息
        const buildingPromise = this.$axios.get('/v1/device/building/list/option');
        // 加载楼层信息
        const floorPromise = this.$axios.get(`/v1/device/floor/list/option/${deviceInfo.buildingId}`);
        // 加载房间信息
        const roomPromise = this.$axios.get(`/v1/device/room/list/option/${deviceInfo.floorId}`);
        Promise.all([buildingPromise, floorPromise, roomPromise]).then(data => {
          const roomInfo = data[2].map(item => {
            item.leaf = true;
            return item;
          });
          // 装配楼层树
          const floorInfo = data[1].map(item => {
            if (item.id === deviceInfo.floorId) {
              item.children = roomInfo;
            }
            item.leaf = false;
            item.id = 'floor' + item.id;
            return item;
          });
          // 装配楼栋树
          this.buildingTree = data[0].map(item => {
            if (item.id === deviceInfo.buildingId) {
              item.children = floorInfo;
            }
            item.leaf = false;
            item.id = "building" + item.id;
            return item;
          });
          deviceInfo.params = deviceInfo.params.split(',').filter(item => item.trim() !== '');

          deviceInfo.images = deviceInfo.images && JSON.parse(deviceInfo.images);
          deviceInfo.files = deviceInfo.files && JSON.parse(deviceInfo.files);
          // 添加默认设备参数输入框
          if (!deviceInfo.params.length) {
            deviceInfo.params = [''];
          }
          deviceInfo.buildingId = "building" + deviceInfo.buildingId;
          deviceInfo.floorId = "floor" + deviceInfo.floorId;
          if (deviceInfo.type === 1) {
            deviceInfo.layerTotal = deviceInfo.cabinet.layerTotal;
          }
          this.dataForm = deviceInfo;
        });
      })
    },

    // 新增设备参数
    addParams() {
      this.dataForm.params.push('');
    },

    // 删除设备参数
    removeParams(params) {
      this.dataForm.params.remove(params);
      this.$refs['dataForm'].clearValidate('params.' + (this.dataForm.params.length - 1));
    },

    // 选中选择项
    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">
.device-device-popper-class {
  .el-checkbox .is-disabled {
    display: none !important;
  }
}
</style>
<style scoped lang="scss">
.app-container {
  .input-width {
    width: 500px;
  }

  ::v-deep .el-textarea__inner {
    min-height: 38px !important;
    line-height: 26px !important;
  }
}
</style>
