<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="监控单元名称" prop="monitorUnitName">
        <el-input
          v-model="queryParams.monitorUnitName"
          placeholder="请输入监控单元名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="监控单元类型ID" prop="monitorUnitTypeId">
        <el-select v-model="queryParams.monitorUnitTypeId" placeholder="监控单元" clearable>
          <el-option
            v-for="item in MonitorUnitTypeName"
            :key="item.monitorUnitTypeId"
            :label="item.monitorUnitTypeName"
            :value="item.monitorUnitTypeId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属场景" prop="sceneId">
        <el-select v-model="queryParams.sceneId" placeholder="场景" clearable>
          <el-option
            v-for="item in SceneName"
            :key="item.sceneId"
            :label="item.sceneName"
            :value="item.sceneId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="isNeedTenant" label="所属租户" prop="tenantId">
        <el-select v-model="queryParams.tenantId" placeholder="租户" clearable>
          <el-option
            v-for="item in TenantName"
            :key="item.tenantId"
            :label="item.tenantName"
            :value="item.tenantId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区域ID" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="区域id" clearable>
          <el-option
            v-for="item in AreaId"
            :key="item.areaId"
            :label="item.areaName"
            :value="item.areaId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:monitorUnit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="monitorUnitList"
      row-key="monitorUnitId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="监控单元名称" prop="monitorUnitName" />
      <el-table-column label="所属场景" align="center" prop="sceneId" >
        <template slot-scope="scope">
            <span
              v-for="(item, index) in SceneName"
              :key="index"
              :value="item.sceneName"
              v-if="scope.row.sceneId == item.sceneId"
            >
              {{ item.sceneName }}
            </span>

        </template>
      </el-table-column>
      <el-table-column label="监控单元类型ID" align="center" prop="monitorUnitTypeId" >
        <template slot-scope="scope">
            <span
              v-for="(item, index) in MonitorUnitTypeName"
              :key="index"
              :value="item.monitorUnitTypeName"
              v-if="scope.row.monitorUnitTypeId == item.monitorUnitTypeId"
            >
              {{ item.monitorUnitTypeName }}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="区域ID" align="center" prop="areaId" >
        <template slot-scope="scope">
            <span
              v-for="(item, index) in AreaId"
              :key="index"
              :value="item.areaName"
              v-if="scope.row.areaId == item.areaId"
            >
              {{ item.areaName }}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:monitorUnit:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['business:monitorUnit:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:monitorUnit:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监控单元对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rulesList" label-width="120px">
        <el-form-item label="监控单元名称" prop="monitorUnitName">
          <el-input v-model="form.monitorUnitName" placeholder="请输入监控单元名称" />
        </el-form-item>
        <el-form-item label="监控单元类型" prop="monitorUnitTypeId">
          <el-select v-model="form.monitorUnitTypeId" placeholder="请选择监控单元类型" clearable >
            <el-option
              v-for="item in MonitorUnitTypeName"
              :key="item.monitorUnitTypeId"
              :label="item.monitorUnitTypeName"
              :value="item.monitorUnitTypeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父级监控单元ID" prop="parentId">
          <treeselect v-model="form.parentId" :options="monitorUnitOptions" :normalizer="normalizer" placeholder="请选择父级监控单元ID" :disabled="isDis"/>
        </el-form-item>
        <el-form-item label="所属场景" prop="sceneId" v-if="form.parentId ==0" >
            <el-select v-model="form.sceneId" placeholder="请选择场景" clearable :disabled="isDis" >
              <el-option
                v-for="item in SceneName"
                :key="item.sceneId"
                :label="item.sceneName"
                :value="item.sceneId">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="所属场景" prop="sceneId" v-if="form.parentId!=0"  >

            <el-select v-model="form.parentId" placeholder="请选择场景"  disabled="disabled">
              <el-option
                v-for="item in SceneName"
                :key="item.sceneId"
                :label="item.sceneName"
                :value="item.sceneId">
              </el-option>
            </el-select>

        </el-form-item>

<!--        <el-form-item label="父级监控单元ID" prop="parentId">-->
<!--          <el-input v-model="form.parentId" placeholder="请输入父级监控单元" />-->
<!--        </el-form-item>-->

        <el-form-item label="区域ID" prop="areaId">
            <treeselect v-model="form.areaId" :options="areaOptions" :normalizer="normalizerArea" placeholder="请选择区域" />
        </el-form-item>
        <el-form-item label="详细地址" prop="monitorAddress">
          <el-input v-model="form.monitorAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="监控单元图片地址" prop="monitorPic">
          <template>
            <div class="component-upload-image">
              <el-upload
                v-model="form.monitorPic"
                multiple
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleUploadSuccess"
                :before-upload="handleBeforeUpload"
                :limit="limit"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                ref="imageUpload"
                :on-remove="handleDeletes"
                :show-file-list="true"
                :headers="headers"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :class="{hide: this.fileList.length >= this.limit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>

              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>

              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>
            </div>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMonitorUnit, getMonitorUnit, delMonitorUnit,getSceneName, addMonitorUnit,selectAreaId,updateMonitorUnit,listMonitorUnitType,getMonitorIsRelevancy } from "@/api/business/monitorUnit";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getIsNeedTenant, getTenantName} from "@/api/business/monitorUnitType";
import result from "@/components/Crontab/result";
import { getToken } from "@/utils/auth";

export default {
  name: "MonitorUnit",
  components: {
    Treeselect
  },
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 监控单元表格数据
      monitorUnitList: [],
      // 监控单元树选项
      monitorUnitOptions: [],
      //区域树选项
      areaOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      //
      MonitorUnitTypeName:"",
      AreaId:"",
      SceneName:"",
      isNeedTenant:"",
      TenantName:"",
      isDis:false,
      // 查询参数
      queryParams: {
        monitorUnitName: null,
        sceneId: null,
        parentId: null,
        monitorUnitTypeId: null,
        tenantId: null,
        areaId: null,
        monitorAddress: null,
        monitorPic: null,
        preserveTime: null,
        monitorUnitStatus: null,
        monitorUnitField: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        monitorUnitName: [
          { required: true, message: "监控单元名称不能为空", trigger: "blur" }
        ],
        sceneId: [
          { required: true, message: "所属场景不能为空", trigger: "blur" }
        ],
        monitorUnitTypeId: [
          { required: true, message: "监控单元类型ID不能为空", trigger: "blur" }
        ],
        monitorUnitStatus: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      },
      rules2:{
        monitorUnitName: [
          { required: true, message: "监控单元名称不能为空", trigger: "blur" }
        ],
        monitorUnitTypeId: [
          { required: true, message: "监控单元类型ID不能为空", trigger: "blur" }
        ],
        monitorUnitStatus: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      },
    };

  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    rulesList: function () {
      console.log(this.form.parentId)
      if (this.form.parentId==0) {
        return this.rules
      } else {
        return this.rules2
      }
    },
  },
  created() {
    this.getList();
    this.listMonitorUnitType();
    this.selectAreaId();
    this.getSceneName();
    this.getIsNeedTenant();
    this.getTenantName();
  },
  methods: {
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.data.url, url: res.data.url });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除图片
    handleDeletes(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        // this.$emit("input", this.listToString(this.fileList));
      }
      this.form.monitorPic = '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));

        this.form.monitorPic = this.fileList[0].url;
        this.$modal.closeLoading();
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    /** 查询监控单元列表 */
    getList() {
      this.loading = true;
      listMonitorUnit(this.queryParams).then(response => {
        console.log(response)
        this.monitorUnitList = this.handleTree(response.rows, "monitorUnitId", "parentId");
        this.loading = false;
      });
    },
    /** 转换监控单元数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.monitorUnitId,
        label: node.monitorUnitName,
        children: node.children
      };
    },
    /** 转换区域数据结构 */
    normalizerArea(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.areaId,
        label: node.areaName,
        children: node.children
      };
    },
    /** 查询监控单元下拉树结构 */
    getTreeselect() {
      listMonitorUnit().then(response => {
        this.monitorUnitOptions = [];
        const data = { monitorUnitId: 0, monitorUnitName: '顶级节点', children: [] };
        data.children = this.handleTree(response.rows, "monitorUnitId", "parentId");
        this.monitorUnitOptions.push(data);
      });
    },
    /** 查询区域下拉树结构*/
    getTreeselectArea() {
      selectAreaId().then(response => {
        this.areaOptions = [];
        const data = { areaId: 0, areaName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "areaId", "parentId");
        this.areaOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        monitorUnitId: null,
        monitorUnitName: null,
        sceneId: null,
        parentId: null,
        monitorUnitTypeId: null,
        tenantId: null,
        areaId: null,
        monitorAddress: null,
        monitorPic: null,
        preserveTime: null,
        remark: null,
        monitorUnitStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        monitorUnitField: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      this.getTreeselectArea();
      this.fileList = [];

      this.isDis = false;
      if (row != null && row.monitorUnitId) {
        this.form.parentId = row.monitorUnitId;
        let isRelevancy = this.getMonitorIsRelevancy(row.monitorUnitId)
        isRelevancy.then((result)=>
        {
          // console.log(result)
          if((result==="y")){
            // console.log("????????????????????")
            this.form.parentId = 0;
          }
        })


      }
      else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加监控单元";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.fileList = [];
      this.reset();
      this.getTreeselect();
      this.getTreeselectArea();
        this.isDis = true;
      if (row != null) {
        this.form.parentId = row.monitorUnitId;
      }
      getMonitorUnit(row.monitorUnitId).then(response => {
        if (response.data.monitorPic != null) {
          let previewFile = {};
          previewFile.url = response.data.monitorPic
          this.fileList.push(previewFile);
        }
        this.form = response.data;
        this.form.parentId = 0;
        this.open = true;
        this.title = "修改监控单元";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.monitorUnitId != null) {
            updateMonitorUnit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMonitorUnit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除监控单元编号为"' + row.monitorUnitId + '"的数据项？').then(function() {
        return delMonitorUnit(row.monitorUnitId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    listMonitorUnitType(){
      listMonitorUnitType().then(response=>{
        console.log(response)
        this.MonitorUnitTypeName = response.rows;
      })
    },
    selectAreaId(){
      selectAreaId().then(response=>{
        console.log(response)
        this.AreaId = response.data;
      })
    },
    //查询场景
    getSceneName(){
      getSceneName().then(response =>{
        this.SceneName = response.rows;
      })
    },
    getIsNeedTenant(){
      getIsNeedTenant().then(response => {{
        // console.log("??????????????????????"+response)
        this.isNeedTenant = response;
        // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+this.isNeedTenant)
      }})
    },
    getTenantName() {
      getTenantName().then(response => {

        // console.log(response)
        this.TenantName = response.rows;
        // console.log(this.TenantName)
      });
    },
    //查询监控单元是否有关联
    async getMonitorIsRelevancy(monitorUnitId) {
      let isRelevancy = 100;
      await getMonitorIsRelevancy(monitorUnitId).then(response => {
        // console.log(response)
        isRelevancy = response;
      });
      // console.log(qqq)
      return isRelevancy;
      },

  }
};

</script>
