<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div v-if="activeTab === 'area'">
          <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="areaList" :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>
        </div>
        <div v-if="activeTab === 'organ'">
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入区块名称" clearable size="small" prefix-icon="el-icon-search"
                      style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree  :key="treeKey" :data="deptList" :props="defaultDeptProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree"
                     node-key="deptId" default-expand-all highlight-current   @node-click="handleDeptNodeClick"/>
          </div>
        </div>
        <div v-if="activeTab === 'facs'">
          <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 :key="tableKey" :data="facsOptions" :props="defaultFacsProps" :expand-on-click-node="false"
                     :filter-node-method="filterNode" ref="tree"
                     node-key="id" default-expand-all highlight-current @node-click="handleFacsNodeClick"
            />
          </div>
        </div>
        <div v-if="activeTab === 'device'">
          <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 :key="tableKey" :data="deviceOptions" :props="defaultFacsProps" :expand-on-click-node="false"
                     :filter-node-method="filterNode" ref="tree"
                     node-key="id" default-expand-all highlight-current @node-click="handleDeviceNodeClick"
            />
          </div>
        </div>

      </el-col>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="地理位置" name="area"></el-tab-pane>
        <el-tab-pane label="组织机构" name="organ"></el-tab-pane>
        <el-tab-pane label="设施" name="facs"></el-tab-pane>
        <el-tab-pane label="设备" name="device"></el-tab-pane>
      </el-tabs>
      <el-col :span="20" :xs="24">

    <!-- 地理位置  -->
        <div v-if="activeTab === 'area'">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="区域名称" prop="areaName">
              <el-input
                  v-model="queryParams.areaName"
                  placeholder="请输入区域名称"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </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-table
              :key="tableKey"
              v-if="refreshTable"
              v-loading="loading"
              :data="areaOptions"
              :default-expand-all="isExpandAll"
              row-key="areaCode"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >

            <el-table-column label="区域名称" align="left" prop="areaName" />
            <el-table-column label="区域简称" align="left" prop="shortName" />
            <el-table-column label="区域编码" align="left" prop="areaCode" />
            <el-table-column label="区域状态" align="center" >
              <template slot-scope="scope">
                {{ objStatusMapping[scope.row.status] }}
              </template>
            </el-table-column>
            <el-table-column label="区块标签" align="center">
              <template slot-scope="scope">
          <span v-for="tag in (scope.row.tagNames && scope.row.tagNames.split(',')) || []" :key="tag" :style="getTagStyle(tag.trim())" class="tag-label">
            {{ tag.trim() }}
          </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-reading"
                    @click="handleDevice(scope.row)"
                    v-hasPermi="['ems:area:edit']"
                >计量设备</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

    <!-- 组织机构   -->
        <div v-if="activeTab === 'organ'">
          <el-form  :model="DeptQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="部门名称" prop="deptName">
              <el-input
                  v-model="DeptQueryParams.deptName"
                  placeholder="请输入部门名称"
                  clearable
                  @keyup.enter.native="handleDeptQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="DeptQueryParams.status" placeholder="部门状态" clearable>
                <el-option
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDeptQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetDeptQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table
              v-if="refreshTable"
              v-loading="loading"
              :data="organOptions"
              row-key="deptId"
              :default-expand-all="isExpandAll"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
            <el-table-column prop="deptName" label="部门名称" width="260"></el-table-column>
            <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="200">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</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-reading"
                      @click="handleDeptDevice(scope.row)"
                      v-hasPermi="['ems:area:edit']"
                  >计量设备</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

    <!-- 设施  -->
        <div v-if="activeTab === 'facs'">
          <el-tabs v-model="FacsQueryParams.facsCategory" @tab-click="facsCategoryChange">
            <el-tab-pane label="产能设施" name="E"></el-tab-pane>
            <el-tab-pane label="储能设施" name="C"></el-tab-pane>
            <el-tab-pane label="输能设施" name="W"></el-tab-pane>
            <el-tab-pane label="用能设施" name="Z"></el-tab-pane>
          </el-tabs>
          <el-form :model="FacsQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                   label-width="68px"
          >
            <el-form-item label="设施子类" prop="facsSubtype">
              <el-select v-model="FacsQueryParams.facsSubCategory">
                <el-option v-for="item in facsSubCategoryOptions" :label="item.name" :value="item.code" :key="item.code"/>
              </el-select>
            </el-form-item>
            <el-form-item label="设施名称" prop="facsName">
              <el-input v-model="FacsQueryParams.facsName" placeholder="请输入设施名称" clearable
                        @keyup.enter.native="handleFacsQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleFacsQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetFacsQuery">重置</el-button>
            </el-form-item>
          </el-form>


          <el-table  :key="tableKey" 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="facsCategoryName"/>
            <el-table-column label="设施子类" align="center" prop="facsSubCategoryName"/>
            <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"
                    icon="el-icon-reading"
                    @click="handleFacsDevice(scope.row)"
                    v-hasPermi="['ems:area:edit']"
                >计量设备</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
     <!--设备    -->
        <div v-if="activeTab === 'device'">
          <el-tabs  v-model="DeviceQueryParams.deviceCategory" @tab-click="deviceCategoryChange">
            <el-tab-pane label="产能设备" name="E"></el-tab-pane>
            <el-tab-pane label="储能设备" name="C"></el-tab-pane>
            <el-tab-pane label="输能设备" name="W"></el-tab-pane>
            <el-tab-pane label="用能设备" name="Z"></el-tab-pane>
          </el-tabs>
          <el-form :model="DeviceQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                   label-width="68px"
          >
            <el-form-item label="设备分类" prop="deviceSubCategory">
              <el-select v-model="DeviceQueryParams.deviceSubCategory">
                <el-option v-for="item in subCategoryOptions" placeholder="设备分类" :label="item.name" :value="item.code"
                           :key="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="归属设施" prop="refFacs">
              <el-select v-model="DeviceQueryParams.refFacs">
                <el-option v-for="item in facsAllOptions" :label="item.facsName" :value="item.facsCode"
                           :key="item.facsCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="子系统" prop="subsystemCode">
              <el-select v-model="DeviceQueryParams.subsystemCode">
                <el-option v-for="item in subsystemOptions" :label="item.systemName" :value="item.systemCode"
                           :key="item.systemCode"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="设备工艺" prop="psCode" v-if="DeviceQueryParams.deviceCategory === 'W'">
              <el-select v-model="DeviceQueryParams.psCode">
                <el-option v-for="item in devOptions" :label="item.psName" :value="item.psCode" :key="item.psCode"/>
              </el-select>
            </el-form-item>


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

          <el-table  :key="tableKey" v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="设备名称" align="left" prop="deviceName"/>
            <el-table-column label="安装位置" align="left" prop="areaPath" width="220px"/>
            <el-table-column label="归属设施" align="center" prop="refFacsName"/>
            <el-table-column label="设备分类" align="center" prop="deviceCategoryName"/>
            <el-table-column label="子系统" align="center" prop="subsystemName"/>
            <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-reading"
                    @click="handleAllDevice(scope.row)"
                    v-hasPermi="['ems:area:edit']"
                >计量设备</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

      </el-col>
      <!-- 计量设备弹框 -->
      <el-dialog :title="dialogTitle" :visible.sync="deviceDialogVisible" width="1000px" append-to-body>
        <el-tabs v-model="activeDeviceTab" @tab-click="handleADTabClick">
          <el-tab-pane label="电表" name="electricMeter"></el-tab-pane>
          <el-tab-pane label="水表" name="waterMeter"></el-tab-pane>
        </el-tabs>

        <!-- 水表和电表的已绑定和未绑定表格 -->
        <SubTitle title="已绑定列表" />
        <el-table  v-loading="loading"  :data="Bound" style="width: 100%">
          <el-table-column label="表计编号" align="left" prop="meterDevice" />
          <el-table-column label="表计名称" align="left" prop="meterDeviceName" />
          <el-table-column label="边界类型" align="left" prop="objType">
            <template slot-scope="scope">
              {{ getObjTypeLabel(scope.row.objType) }}
            </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-arrow-down" @click="downToDevice(scope.row)">取消绑定</el-button>
            </template>
          </el-table-column>
        </el-table>
        <SubTitle title="未绑定列表" />
        <el-table  v-loading="loading"  :data="Unbound" style="width: 100%">
          <el-table-column label="表计编号" align="left" prop="deviceCode" />
          <el-table-column label="表计名称" align="left" prop="deviceName" width="200px"/>
          <el-table-column label="安装位置" align="left" prop="deviceLocation" width="200px"/>
          <el-table-column label="计量标签" align="center" prop="objTag">
            <template slot-scope="scope">
              {{formatDict(scope.row.objTag,'objTagOptions')}}
            </template>
          </el-table-column>
          <el-table-column label="采集方式" align="center" prop="colMode">
            <template slot-scope="scope">
              <span>{{ getColModeName(scope.row.colMode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采集周期" align="center" prop="colCycle">
            <template slot-scope="scope">
              <span>{{ getColCycleName(scope.row.colCycle) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <!-- 检查是否已绑定 -->
              <div v-if="isAlreadyBound(scope.row.deviceCode)">
                <span>已绑定</span>
              </div>
              <div v-else>
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-arrow-up"
                    @click="moveToDevice(scope.row)"
                >绑定</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="MeterQueryParams.pageNum" :limit.sync="MeterQueryParams.pageSize"
                    @pagination="getMeterData" />

        <div slot="footer" class="dialog-footer">
          <el-button @click="saveByObj">保 存</el-button>
          <el-button @click="MeterCancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { areaTreeSelect, listDetailArea } from '@/api/basecfg/area'
import SubTitle from '@/components/SubTitle/index.vue'
import { getDevProcess, getEmsTag } from '@/api/commonApi'
import { delDevice, listDevice } from '@/api/device/meterDevice'
import { addAllByObj, listByObj } from '@/api/basecfg/meterBoundary'
import { listDept } from '@/api/system/dept'
import { getFacsCategorygetByCode, listAllFacs, listFacs } from '@/api/basecfg/emsfacs'
import { listDevRecursionByArea } from '@/api/device/device'
import { listSubsystemAll } from '@/api/adapter/subsystem'


export default {
  name: 'Device',
  dicts: ['sys_normal_disable'],
  components: { SubTitle, Treeselect },
  data() {
    return {
      activeTab: 'area',
      areaOptions: [],
      organOptions: [],
      facsOptions: undefined,
      facsAllOptions:undefined,
      deviceOptions:undefined,
      // 区域名称
      areaName: undefined,
      deptName:undefined,
      defaultProps: {
        children: 'children',
        label: 'areaName'
      },
      defaultDeptProps: {
        children: 'children',
        label: 'deptName'
      },
      defaultFacsProps: {
        children: 'children',
        label: 'label'
      },
      treeKey: 0,
      tableKey: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 区域对象表格数据
      areaList: [],
      deptList:[],
      facsList:[],
      deviceList:[],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 标签选项
      emsTagOptions: [],
      tagCodeToColorMap:{},
      // 地理位置查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaCode: null,
        parentCode: null,
        ancestors: null,
        areaName: null,
        shortName: null,
        desc: null,
        orderNum: null,
        status: null,
        tagNames:null,
        areaAttr:{}
      },
      // 组织机构查询参数
      DeptQueryParams: {
        deptName: undefined,
        status: undefined
      },
      // 设施 查询参数
      FacsQueryParams: {
        pageNum: 1,
        pageSize: 10,
        facsCode: null,
        facsName: null,
        facsCategory: 'E',
        facsSubCategory: null,
        enable: null,
        refArea: null,
        customAttrs: null
      },
      // 设备查询参数
      DeviceQueryParams: {
        psCode: null,
        pageNum: 1,
        pageSize: 10,
        deviceCode: null,
        deviceSubCategory: '',
        deviceCategory: 'E',
        locationRef: null,
        refFacs: null,
        customAttrs: null
      },
      // 水表、电表查询参数
      MeterQueryParams: {
        pageNum: 1,
        pageSize: 10,
        areaCode: null,
        bldgCode: null,
        deviceCode: null,
        meterCls: null,
        objTag: null,
        colCycle: null,
        colMode: null,
        magnification: null,
        specDesc: null
      },
      objStatusMapping: {
        0: '正常',
        1: '停用',
      },
      // 表单参数
      form: {
        areaAttr: {
          areaCode:null,
          attrOrg: null,
          mgrOrg: null,
          leader: null,
          phone: null,
          openDate: null,
          floorArea: null,
          usableArea: null,
          floor: null,
          tagCodes:null,
          tagNames:null,
          tagCodeList:[]
        }

      },
      // 表单校验
      rules: {
        areaCode: [
          { required: true, message: "区域代码不能为空", trigger: "blur" }
        ],
        areaName: [
          { required: true, message: "区域名称不能为空", trigger: "blur" }
        ],
      },
      objTagOptions: [
        { code: 0, name: '公摊表' },
        { code: 1, name: '个户表' }
      ],
      allAreaNode: {
        id: 'all',
        areaName: '全部',
        children: []
      },
      allDeptNode: {
        deptId: 'all',
        deptName: '全部',
        children: []
      },
      // 设施分类列表
      facsCategoryOptions: undefined,
      facsSubCategoryOptions: undefined,
      // 设备分类
      subCategoryOptions: undefined,
      subsystemOptions: undefined,
      subcategoryCode: '',
      devOptions: undefined,
      parentAreaCode:'',
      dialogTitle: '',
      deviceDialogVisible: false,
      activeDeviceTab: 'electricMeter',
      Bound: [], // 已绑定数据
      Unbound: [], // 未绑定数据
    }
  },
  mounted() {
    this.getList();
    this.getFacsList();
    this.getDeviceList();
  },
  created() {
    this.getDeviceSubCategorygetByCode();
    this.getFacsSubCategorygetByCode();
    this.getAreaFacsTree('0', false)
    this.getAreaDeviceTree('0', false)
    this.getAllDevProcess(this.subcategoryCode)
    this.getEmsTag('Area');
    this.getFacsOptions()
    this.getSubsystem()
    this.form.areaAttr = {};
    this.getList();
    this.getDeptList();
  },
  methods: {
    getAreaFacsTree(areaCode, recursion) {
      areaTreeSelect(areaCode, recursion).then(response => {
        this.facsOptions = [{
          id: '-1',
          label: '全部',
          children: response.data
        }]
      })
    },
    getAreaDeviceTree(areaCode, recursion) {
      areaTreeSelect(areaCode, recursion).then(response => {
        this.deviceOptions =  [{
          id: null,
          label: '全部',
          children: response.data
        }]
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getObjTypeLabel(objType) {
      const typeLabels = {
        1: '区域位置',
        2: '设施',
        3: '设备',
        4: '组织'
      };
      return typeLabels[objType] || '未知类型';
    },
    formatDict(val, options, key = 'code', text = 'name') {
      if (!this[options] || !Array.isArray(this[options])) {
        console.error(`Expected an array for this[${options}], but got ${typeof this[options]}`);
        return '';
      }
      let name = '';
      this[options].forEach(item => {
        if (val === item[key]) {
          name = item[text];
        }
      });
      return name;
    },

    getColCycleName(colCycle) {
      const cycleMap = {
        0: '实时',
        1: '分钟',
        2: '小时',
        3: '天',
        4: '月'
      }
      return cycleMap[colCycle] || ''
    },
    getColModeName(colMode) {
      const modeMap = {
        0: '自动抄表',
        1: '手动抄表'
      }
      return modeMap[colMode] || '未知'
    },
    /**分页*/
    handleTabClick(tab) {
      this.reset();
      if (tab.name === 'area') {
        this.showSearch = true;
        this.getList();
      } else if (tab.name === 'organ') {
        this.showSearch = true;
        this.getDeptList();
      } else if (tab.name === 'facs') {
        this.showSearch = true;
        this.getFacsList()
      }else if (tab.name === 'device') {
        this.showSearch = true;
        this.getDeviceList();
      }
    },
    /**电表、水表分页*/
    handleADTabClick(tab){
      this.activeDeviceTab = tab.name;
      this.getMeterData();
    },

    //地理位置
    handleNodeClick(data) {
      if (data.id === 'all') {
        this.areaOptions = this.areaList.slice(1).map(item => {
          const { children, ...rest } = item;
          return rest;
        });
      } else {
        // 判断是否为叶子节点
        if (!data.children || data.children.length === 0) {
          // 叶子节点，展示该节点的数据
          this.areaOptions = [data];
        } else {
          this.areaOptions = data.children.map(child => {
            const { children, ...rest } = child;
            return rest;
          });
        }
      }
    },


    //组织机构
    handleDeptNodeClick(data) {
      if (data.deptId === 'all') {
        this.organOptions = this.deptList.slice(1).map(item => {
          const { children, ...rest } = item;
          return rest;
        });
      } else {
        // 判断是否为叶子节点
        if (!data.children || data.children.length === 0) {
          this.organOptions = [data];
        } else {
          this.organOptions = data.children.map(child => {
            const { children, ...rest } = child;
            return rest;
          });
        }
      }
    },
    //设施
    handleFacsNodeClick(data) {
      this.FacsQueryParams.refArea = data.id
      this.handleFacsQuery()
    },
    //设备
    handleDeviceNodeClick(data) {
      this.DeviceQueryParams.locationRef = data.id
      this.handleDeviceQuery()
    },

    /** 查询区域对象列表 */
    getList() {
      this.loading = true;
      listDetailArea(this.queryParams).then(response => {
        this.areaList = this.handleTree(response.data, "areaCode", "parentCode");
         this.areaList = this.extractTagNames(this.areaList);
        this.tableKey += 1; // 改变 key 值以强制重新渲染
        // 将“全部”节点添加到区域列表的顶部
        this.areaList.unshift(this.allAreaNode);
        this.loading = false;
        this.Node();
      });
    },
    Node() {
      if (this.areaList.length > 0) {
        this.handleNodeClick(this.areaList[0]);}
      if (this.areaList[0].children && this.areaList[0].children.length > 1) {
        this.handleNodeClick(this.areaList[0].children[1]);
      }
    },

    // 递归提取 tagNames
    extractTagNames(list) {
      return list.map(item => {
        if (item.areaAttr && item.areaAttr.tagNames) {
          item.tagNames = item.areaAttr.tagNames;
        } else {
          item.tagNames = '';
        }
        if (item.children) {
          item.children = this.extractTagNames(item.children);
        }
        return item;
      });
    },

    /** 查询部门列表 */
    getDeptList() {
      this.loading = true;
      listDept(this.DeptQueryParams).then(response => {
        this.deptList = this.handleTree(response.data, "deptId");
        this.deptList = this.extractTagNames(this.deptList);
        this.treeKey += 1;
        this.loading = false;
        this.deptList.unshift(this.allDeptNode);
        this.deptNode();

      });
    },
    deptNode() {
      if (this.deptList.length > 0) {
        this.handleDeptNodeClick(this.deptList[0]);}
      if (this.deptList[0].children && this.deptList[0].children.length > 1) {
        this.handleDeptNodeClick(this.deptList[0].children[1]);
      }
    },

    /** 查询能源设施/系统列表 */
    getFacsList() {
      this.loading = true
      listFacs(this.FacsQueryParams).then(response => {
        this.facsList = response.rows
        this.total = response.total
        this.loading = false
        // 确保在数据更新后更新 key
        this.tableKey += 1;
      })
    },
    /** 查询能源设备列表 */
    getDeviceList() {
      this.loading = true
      listDevRecursionByArea(this.DeviceQueryParams).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false
        this.tableKey += 1;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    MeterCancel() {
      this.deviceDialogVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        areaCode: null,
        parentCode: null,
        ancestors: null,
        areaName: null,
        shortName: null,
        desc: null,
        orderNum: null,
        status: null,
        areaAttr: {
          areaCode: null,
          attrOrg: null,
          mgrOrg: null,
          leader: null,
          phone: null,
          openDate: null,
          floorArea: null,
          usableArea: null,
          floor: null,
          tagCodes: null,
          tagNames: null,
          tagCodeList: []
        }// 确保 areaAttr 始终为一个空对象
      };
      this.resetForm("form");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        areaCode: null, // 确保这里也重置areaCode
        parentCode: null,
        ancestors: null,
        areaName: null,
        shortName: null,
        desc: null,
        orderNum: null,
        status: null,
        tagNames:null,
        areaAttr:{}
      };
    },
    /** 地理位置搜索按钮操作 */
    handleQuery() {
      this.loading = true;
      listDetailArea(this.queryParams).then(response => {
        this.areaOptions = this.handleTree(response.data, "areaCode", "parentCode");
        this.areaOptions = this.extractTagNames(this.areaOptions);
        this.loading = false;
      });
    },
    filterDataByAreaCode(list, areaCode) {
      let result = [];
      for (let i = 0; i < list.length; i++) {
        if (list[i].areaCode === areaCode) {
          if (list[i].children && list[i].children.length > 0) {
            list[i].children.forEach(child => {
              result.push(child);
              if (child.children && child.children.length > 0) {
                result = result.concat(this.filterDataByAreaCode(child.children, areaCode));
              }
            });
          }
          return result;
        } else if (list[i].children && list[i].children.length > 0) {
          const foundChildren = this.filterDataByAreaCode(list[i].children, areaCode);
          if (foundChildren.length > 0) {
            return foundChildren;
          }
        }
      }
      return result;
    },
    /** 地理位置重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 组织机构搜索按钮操作 */
    handleDeptQuery() {
      this.getDeptList();
    },
    resetDeptQuery() {
      this.resetForm("queryForm");
      this.handleDeptQuery();
    },
    /** 设施搜索按钮操作 */
    handleFacsQuery() {
      this.FacsQueryParams.pageNum = 1
      this.getFacsList()
    },
    resetFacsQuery() {
      this.FacsQueryParams.refArea = null
      this.resetForm('queryForm')
      this.handleFacsQuery()
    },
    /**设备搜索按钮操作 */
    handleDeviceQuery() {
      this.DeviceQueryParams.pageNum = 1
      this.getDeviceList()
    },
    resetDeviceQuery() {
      this.DeptQueryParams.locationRef = null
      this.resetForm('queryForm')
      this.handleDeviceQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /**计量设备*/
    handleDevice(row) {
      this.queryParams.areaCode = row.areaCode;
        if (row && row.ancestors) {
          const ancestorsArray = row.ancestors.split(',');
          if (ancestorsArray.length > 1) {
            // 当 ancestors 长度大于 1 时，取第二个 areaCode 作为父级 areaCode
            this.MeterQueryParams.areaCode= ancestorsArray[1];
          } else if (ancestorsArray.length === 1) {
            // 当 ancestors 长度等于 1 时，取该对象本身的 areaCode 作为父级 areaCode
            this.MeterQueryParams.areaCode = row.areaCode;
          }
        }
      this.dialogTitle = `计量设备 - ${row.areaName}`;
      this.deviceDialogVisible = true;
      this.getMeterData(row);
    },
    /**组织结构计量设备*/
    handleDeptDevice(row) {
      this.queryParams.areaCode = row.deptId;
      if (row && row.ancestors) {
        const ancestorsArray = row.ancestors.split(',');
        if (ancestorsArray.length > 1) {
          this.MeterQueryParams.areaCode= ancestorsArray[1];
        } else if (ancestorsArray.length === 1) {
          this.MeterQueryParams.areaCode = row.deptId;
        }
      }
      this.dialogTitle = `计量设备 - ${row.deptName}`;
      this.deviceDialogVisible = true;
      this.getMeterData();
    },
    /**设施计量设备*/
    handleFacsDevice(row) {
      this.queryParams.areaCode = row.facsCode;
      this.MeterQueryParams.areaCode = row.refArea;

      this.dialogTitle = `计量设备 - ${row.facsName}`;
      this.deviceDialogVisible = true;
      this.getMeterData();
    },
    /**设备计量设备*/
    handleAllDevice(row) {
      console.log("row",row)
      this.queryParams.areaCode = row.deviceCode;
      this.MeterQueryParams.areaCode = row.areaCode;

      this.dialogTitle = `计量设备 - ${row.deviceName}`;
      this.deviceDialogVisible = true;
      this.getMeterData();
    },
    getMeterData() {
      this.loading = true;
      let meterCls = '';
      if (this.activeDeviceTab === 'electricMeter') {
        meterCls = 45;
      } else if (this.activeDeviceTab === 'waterMeter') {
        meterCls = 70;
      }
      let objType;
      if (this.activeTab === 'area') {
        objType = 1;
      } else if (this.activeTab === 'organ') {
        objType = 4;
      } else if (this.activeTab === 'facs') {
        objType = 2;
      } else if (this.activeTab === 'device') {
        objType = 3;
      }
      listDevice({ ...this.MeterQueryParams, meterCls}).then(response => {
        this.Unbound = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listByObj(objType,meterCls,this.queryParams.areaCode).then(response=>{
        this.Bound = response.data;
      })
    },

    /**绑定设备*/
    moveToDevice(row) {
      let objType;
      if (this.activeTab === 'area') {
        objType = 1;
      } else if (this.activeTab === 'organ') {
        objType = 4;
      } else if (this.activeTab === 'facs') {
        objType = 2;
      } else if (this.activeTab === 'device') {
        objType = 3;
      }
      const index = this.Unbound.indexOf(row);
      if (index !== -1) {
        this.Unbound.splice(index, 1);
      }
      const boundRow = {
        meterDeviceName: row.deviceName,
        meterDevice: row.deviceCode,
        boundaryObj: this.queryParams.areaCode,
        objType: objType
      };
      this.Bound.push(boundRow);
    },
    isAlreadyBound(deviceCode) {
      return this.Bound.some(boundDevice => boundDevice.meterDevice === deviceCode);
    },
    /**取消绑定设备*/
    downToDevice(row){
      const index = this.Bound.indexOf(row);
      if (index !== -1) {
        this.Bound.splice(index, 1);
      }
      this.Unbound.push(row);
      delete row.boundaryObj;
      delete row.meterDevice;
      delete row.objType;
    },

    /**保存绑定的设备*/
    saveByObj() {
      // 构建要保存的数据数组
      const dataToSave = this.Bound.map(item => {
        return {
          boundaryObj: item.boundaryObj,
          id: item.id,
          meterCls: item.meterCls || (this.activeDeviceTab === 'electricMeter' ? 45 : 70),
          meterDevice: item.meterDevice,
          objType: item.objType
        };
      });
      // 构建查询参数
      const RequestQueryParams = this.Bound.map(item => {
        return {
          objType: item.objType,
          boundaryObj: item.boundaryObj,
          meterCls: item.meterCls || (this.activeDeviceTab === 'electricMeter' ? 45 : 70),
        };
      });
      const objType = RequestQueryParams.length > 0 ? RequestQueryParams[0].objType : null;
      const boundaryObj = RequestQueryParams.length > 0 ? RequestQueryParams[0].boundaryObj : null;
      const meterCls = RequestQueryParams.length > 0 ? RequestQueryParams[0].meterCls : null;

      addAllByObj(objType, meterCls,boundaryObj,  dataToSave)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('保存成功');
              this.deviceDialogVisible = false;
              this.getMeterData();
            } else {
              this.$message.error('保存失败');
            }
          })
          .catch(error => {
            console.error('保存失败:', error);
            this.$message.error('保存失败');
          });
    },
    facsCategoryChange() {
      this.FacsQueryParams.facsSubCategory = ''
      this.getFacsSubCategorygetByCode()
      this.handleFacsQuery()
    },

    getFacsSubCategorygetByCode() {
      getFacsCategorygetByCode(this.FacsQueryParams.facsCategory).then(response => {
        this.facsSubCategoryOptions = response.data.subtypeList || []
      })
    },
    getDeviceSubCategorygetByCode() {
      getFacsCategorygetByCode(this.DeviceQueryParams.deviceCategory).then(response => {
        this.subCategoryOptions = response.data.subtypeList || []
      })
    },
    // 设施下拉框选项
    getFacsOptions() {
      const getFacsParams = {
        facsCategory: this.DeviceQueryParams.deviceCategory,
        subCategory: this.DeviceQueryParams.deviceSubCategory
      }
      listAllFacs(getFacsParams).then(response => {
        this.facsAllOptions = response.data
      })
    },
    deviceCategoryChange() {
      this.DeviceQueryParams.deviceSubCategory = ''
      //this.queryParams.psCode = null; // 重置设备工艺选择
      if (this.DeviceQueryParams.deviceCategory === 'E' || this.DeviceQueryParams.deviceCategory === 'W'
          || this.DeviceQueryParams.deviceCategory === 'T' || this.DeviceQueryParams.deviceCategory === 'C') {
        this.getAreaDeviceTree('0', false)
      } else if (this.DeviceQueryParams.deviceCategory === 'Z') {
        this.getAreaDeviceTree('0', true)
      }
      this.getDeviceSubCategorygetByCode()
      this.getFacsOptions()
      this.handleDeviceQuery()
    },
    getSubsystem() {
      listSubsystemAll().then(response => {
        this.subsystemOptions = response.data
      })
    },
    getAllDevProcess(subcategoryCode) {
      getDevProcess(subcategoryCode).then(response => {
        this.devOptions = response.data
      })
    },
    getEmsTag(tagModel) {
      console.log("tagModel", tagModel)
      getEmsTag(tagModel).then(response => {
        if (response && response.data) {
          this.emsTagOptions = response.data.map(item => ({
            label: item.tagName,
            value: item.tagCode,
            color: item.tagColor
          }));
          //颜色映射
          this.tagCodeToColorMap = {};
          this.emsTagOptions.forEach(item => {
            this.tagCodeToColorMap[item.value] = item.color;
          });

        }
      })
    },
    getTagStyle(tagName) {
      // 从tagName找到对应的tagCode
      const tagCode = this.emsTagOptions.find(tag => tag.label === tagName)?.value;
      const color = this.tagCodeToColorMap[tagCode] || '#FFFFFF'; // 默认白色
      return {
        backgroundColor: color,
        color:'#808080',
        padding: '4px 8px',
        borderRadius: '4px',
        width: '80px',
        height: '30px',
        margin: '4px 8px 4px 0',
        display: 'inline-block',
        verticalAlign: 'top'
      };
    },
  }
}
</script>
