<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="areaName" placeholder="请输入区块名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="areaOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree"
            node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="设施名称" prop="facsName">
            <el-input v-model="queryParams.facsName" placeholder="请输入设施名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="设施分类" prop="facsType">
            <el-select v-model="queryParams.facsType" @change="handleFacsTypeChange">
              <el-option v-for="item in facsTypeOptions" :label="item.name" :value="item.code" :key="item.code" />
            </el-select>
          </el-form-item>
          <el-form-item label="设施子类" prop="facsSubtype">
            <el-select v-model="queryParams.facsSubtype">
              <el-option v-for="item in facsSubTypeOptions" :label="item.name" :value="item.code" :key="item.code" />
            </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="['basecfg:emsfacs:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['basecfg:emsfacs:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['basecfg:emsfacs:remove']">删除</el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="facsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="设施代码" align="center" prop="facsCode" />
          <el-table-column label="设施名称" align="center" prop="facsName" />
          <el-table-column label="设施分类" align="center" prop="facsTypeName" />
          <el-table-column label="设施子类" align="center" prop="facsSubtypeName" />
          <el-table-column label="启用状态" align="center" prop="enable">
            <template slot-scope="scope">
              <span
                :style="{
                    padding: '6px 12px',
                    borderRadius: '4px',
                    display: 'inline-block',
                    textAlign: 'center',
                    cursor: 'pointer',
                    color: scope.row.enable === 0 ? 'rgb(255,159,159)' : 'rgb(117,186,255)',
                    backgroundColor: scope.row.enable === 0 ? 'rgb(255,235,235)' : 'rgb(232,244,255)'
        }"
              >
        {{ scope.row.enable === 0 ? '关闭' : '启用' }}
      </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" @click="handleDetail(scope.row)" v-hasPermi="['basecfg:emsfacs:edit']">
                详情</el-button>
              <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['basecfg:emsfacs:edit']">
                修改</el-button>
              <el-button size="mini" type="text" class="deleteBtn" @click="handleDelete(scope.row)" v-hasPermi="['basecfg:emsfacs: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="450px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="归属区域" prop="refArea">
              <treeselect v-model="form.refArea" :options="areaOptions" :show-count="true" placeholder="请选择归属园区" />
            </el-form-item>
            <el-form-item label="设施代码" prop="facsCode">
              <el-input v-model="form.facsCode" placeholder="请输入设施代码" />
            </el-form-item>
            <el-form-item label="设施名称" prop="facsName">
              <el-input v-model="form.facsName" placeholder="请输入设施名称" />
            </el-form-item>
            <el-form-item label="设施分类" prop="facsType">
              <el-select v-model="form.facsType" @change="handleFacsTypeChange" style="width:100%">
                <el-option v-for="item in facsTypeOptions" :label="item.name" :value="item.code" :key="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item label="设施子类" prop="facsSubtype">
              <el-select v-model="form.facsSubtype" style="width:100%">
                <el-option v-for="item in facsSubTypeOptions" :label="item.name" :value="item.code" :key="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item label="启用状态" prop="enable">
              <el-select v-model="form.enable" style="width:100%">
                <el-option v-for="item in enableOptions"
                           :label="item.name"
                           :value="item.code"
                           :key="item.code" />
              </el-select>
            </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>
      </el-col>
    </el-row>
    <el-drawer :title="curRow.facsName" size="80%" :visible.sync="showDrawer" direction="rtl">
      <div class="drawer-content">
        <el-tabs v-model="subKey">
          <el-tab-pane label="属性定义" name="attr">
            <el-button type="primary" class="mb8" icon="el-icon-plus" size="mini" @click="addSub">新增
            </el-button>
            <el-table class="sub-table" :data="attrData">
              <el-table-column label="序号" align="center" type="index" />
              <el-table-column label="属性名称" align="center" prop="attrName" />
              <el-table-column label="属性描述" align="center" prop="attrDesc" />
              <el-table-column label="属性值" align="center" prop="attrValue" />
              <el-table-column label="属性单位" align="center" prop="attrUnit" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="editSub(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" class="deleteBtn" @click="deleteSub(scope.row)">
                    删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="能力定义" name="ability">
            <el-button type="primary" class="mb8" icon="el-icon-plus" size="mini" @click="addSub">新增
            </el-button>
            <el-table class="sub-table" :data="abilityData">
              <el-table-column label="序号" align="center" type="index" />
              <el-table-column label="能力名称" align="center" prop="abilityName" />
              <el-table-column label="下发参数" align="center" prop="abilityParam" />
              <el-table-column label="描述" align="center" prop="abilityDesc" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="editSub(scope.row)">
                    修改</el-button>
                  <el-button size="mini" type="text" class="deleteBtn" @click="deleteSub(scope.row)">
                    删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="事件定义" name="event">
            <el-button type="primary" class="mb8" icon="el-icon-plus" size="mini" @click="addSub">新增
            </el-button>
            <el-table class="sub-table" :data="eventData">
              <el-table-column label="序号" align="center" type="index" />
              <el-table-column label="事件名称" align="center" prop="eventName" />
              <el-table-column label="事件类型" align="center" prop="eventType">
                <template slot-scope="scope">
                  <span>{{ scope.row.eventType === 1 ? '消息上报' : '异常告警' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="事件代码" align="center" prop="eventCode" />
              <el-table-column label="外部事件代码" align="center" prop="extEventCode" />
              <el-table-column label="描述" align="center" prop="eventDesc" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="editSub(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" class="deleteBtn" @click="deleteSub(scope.row)">
                    删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
    <el-dialog :title="subTitle" :visible.sync="subDialogShow" width="450px" append-to-body>
      <el-form v-if="subKey=='attr'" ref="subForm" :model="attrForm" label-width="100px">
        <el-form-item label="属性名称" prop="attrName" required :rules="[{ required: true, message: '属性名称不能为空'}]">
          <el-input v-model="attrForm.attrName" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="属性值" prop="attrValue">
          <el-input v-model="attrForm.attrValue" placeholder="请输入属性值" />
        </el-form-item>
        <el-form-item label="属性单位" prop="attrUnit">
          <el-input v-model="attrForm.attrUnit" placeholder="请输入属性单位" />
        </el-form-item>
        <el-form-item label="描述" prop="attrDesc">
          <el-input v-model="attrForm.attrDesc" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <el-form v-else-if="subKey=='ability'" ref="subForm" :model="abilityForm" label-width="100px">
        <el-form-item label="能力名称" prop="abilityName" required :rules="[{ required: true, message: '能力名称不能为空'}]">
          <el-input v-model="abilityForm.abilityName" placeholder="请输入能力名称" />
        </el-form-item>
        <el-form-item label="能力下发参数" prop="abilityParam">
          <el-input v-model="abilityForm.abilityParam" placeholder="请输入能力下发参数" />
        </el-form-item>
        <el-form-item label="描述" prop="abilityDesc">
          <el-input v-model="abilityForm.abilityDesc" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <el-form v-else-if="subKey=='event'" ref="subForm" :model="eventForm" label-width="100px">
        <el-form-item label="事件名称" prop="eventName" required :rules="[{ required: true, message: '事件名称不能为空'}]">
          <el-input v-model="eventForm.eventName" placeholder="请输入事件名称" />
        </el-form-item>
        <el-form-item label="事件类型" prop="eventType" required :rules="[{ required: true, message: '事件类型不能为空'}]">
          <el-select v-model="eventForm.eventType" style="width:100%" placeholder="请选择事件类型">
            <el-option label="消息上报" :value="1" />
            <el-option label="异常告警" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="事件代码" prop="eventCode">
          <el-input v-model="eventForm.eventCode" placeholder="请输入事件代码" />
        </el-form-item>
        <el-form-item label="外部事件代码" prop="extEventCode">
          <el-input v-model="eventForm.extEventCode" placeholder="请输入外部事件代码" />
        </el-form-item>
        <el-form-item label="描述" prop="eventDesc">
          <el-input v-model="eventForm.eventDesc" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="subFormSubmit">确 定</el-button>
        <el-button @click="subFormCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFacs,
  getFacs,
  delFacs,
  addFacs,
  updateFacs,
  getSubtable,
  addSubtable,
  updateSubtable,
  delSubtable
} from '@/api/basecfg/emsfacs'
import { listAllFacsType } from '@/api/basecfg/facstype'
import { areaTreeSelect } from '@/api/basecfg/area'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Facs',
  components: { Treeselect },
  data() {
    return {
      showDrawer: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 能源设施/系统表格数据
      facsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 区域名称
      areaName: undefined,
      // 区域树选项
      areaOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 设施分类列表
      facsTypeOptions: undefined,
      facsSubTypeOptions: undefined,
      enableOptions: [
        { code: 0, name: '关闭' },
        { code: 1, name: '启用' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        facsCode: null,
        facsName: null,
        facsType: null,
        facsSubtype: null,
        enable: null,
        refArea: null
      },
      // 表单参数
      form: {
        id: null,
        facsCode: null,
        facsName: null,
        facsType: null,
        facsSubtype: null,
        enable: null,
        refArea: null,
        createTime: null,
        updateTime: null
      },
      // 表单校验
      rules: {
        facsCode: [{ required: true, message: '设施代码不能为空', trigger: 'blur' }],
        facsName: [{ required: true, message: '设施名称不能为空', trigger: 'blur' }],
        facsType: [{ required: true, message: '设施分类不能为空', trigger: 'change' }],
        refArea: [{ required: true, message: '归属区域代码不能为空', trigger: 'blur' }]
      },
      curRow: {},
      attrData: [],
      abilityData: [],
      eventData: [],
      attrForm: {
        attrName: '',
        attrValue: '',
        attrUnit: '',
        attrDesc: ''
      },
      abilityForm: {
        abilityName: '',
        abilityDesc: '',
        abilityParam: ''
      },
      eventForm: {
        eventName: '',
        eventCode: '',
        eventType: '',
        extEventCode: '',
        eventDesc: ''
      },
      subDialogShow: false,
      subTitle: '',
      subKey: 'attr',
      subMap: {
        attr: '属性',
        ability: '能力',
        event: '事件'
      }
    }
  },
  watch: {
    // 根据名称筛选区域树
    areaName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList()
    this.getAreaTree('Area')
    this.getAllFacsType()
  },
  methods: {
    /** 查询能源设施/系统列表 */
    getList() {
      this.loading = true
      listFacs(this.queryParams).then(response => {
        this.facsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.refArea = null
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加能源设施'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getFacs(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改能源设施'
        this.handleFacsTypeChange(response.data.facsType)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFacs(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addFacs(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 设配详情
    handleDetail(row) {
      this.showDrawer = true
      this.curRow = row
      this.subKey = this.$options.data().subKey
      getFacs(row.id).then(({ code, data }) => {
        if (code === 200) {
          const { facsAttrs = [], facsAbilities = [], facsEvents = [] } = data
          this.attrData = facsAttrs
          this.abilityData = facsAbilities
          this.eventData = facsEvents
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除能源设施编号为"' + ids + '"的数据项？')
        .then(function() {
          return delFacs(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'ems/basecfg/emsfacs/export',
        {
          ...this.queryParams
        },
        `facs_${new Date().getTime()}.xlsx`
      )
    },
    /** 查询区域树结构 */
    getAreaTree(tier) {
      areaTreeSelect(tier).then(response => {
        this.areaOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.refArea = data.id
      this.handleQuery()
    },
    /** 获取设施分类 **/
    getAllFacsType() {
      listAllFacsType().then(response => {
        this.facsTypeOptions = response.data
      })
    },
    handleFacsTypeChange(code) {
      const obj = {}
      this.facsTypeOptions.forEach(item => {
        if (item.code && Array.isArray(item.subtypeList)) {
          obj[item.code] = item.subtypeList
        }
      })
      this.facsSubTypeOptions = obj[code] || []
    },
    getSubtableList() {
      getSubtable(this.subKey, { facsCode: this.curRow.facsCode }).then(({ code, rows }) => {
        if (code === 200) {
          this[`${this.subKey}Data`] = rows
        }
      })
    },
    addSub() {
      this.subDialogShow = true
      this.subTitle = `新增${this.subMap[this.subKey]}`
    },
    editSub(row) {
      this.subDialogShow = true
      this.subTitle = `修改${this.subMap[this.subKey]}`
      this[`${this.subKey}Form`] = row
    },
    deleteSub(row) {
      this.$modal.confirm('是否确认删除').then(() => {
        delSubtable(this.subKey, row.id).then(({ code }) => {
          if (code === 200) {
            this.getSubtableList()
            this.$modal.msgSuccess('删除成功')
          } else {
            this.$modal.msgError('删除失败')
          }
        })
      })
    },
    subFormSubmit() {
      this.$refs['subForm'].validate(valid => {
        if (valid) {
          const params = Object.assign({}, this[`${this.subKey}Form`], { facsCode: this.curRow.facsCode })
          if (this.subTitle.includes('新增')) {
            addSubtable(this.subKey, params).then(({ code }) => {
              if (code === 200) {
                this.$modal.msgSuccess('新增成功')
                this.subDialogShow = false
                this.getSubtableList()
              } else {
                this.$modal.msgError('新增失败')
              }
            })
          } else {
            updateSubtable(this.subKey, params).then(({ code }) => {
              if (code === 200) {
                this.$modal.msgSuccess('修改成功')
                this.subDialogShow = false
                this.getSubtableList()
              } else {
                this.$modal.msgError('修改失败')
              }
            })
          }
        }
      })
    },
    subFormCancel() {
      this[`${this.subKey}Form`] = this.$options.data()[`${this.subKey}Form`]
      this.resetForm('subForm')
      this.subDialogShow = false
    }
  }
}
</script>
<style lang="scss" scoped>
.sub-table {
  .el-icon-delete {
    cursor: pointer;
  }
  .operateBtns {
    cursor: pointer;
    i {
      color: #1990ff;
      margin-left: 5px;
    }
  }
}
.drawer-content {
  padding: 0 20px;
}
</style>
