<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="objType">
        <el-select v-model="queryParams.objType" placeholder="请选择对象类型" clearable>
          <el-option
            v-for="dict in dict.type.device_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="目标对象" prop="objName">
        <el-autocomplete
          v-model="queryParams.objName"
          placeholder="请输入对象名称"
          clearable
          :fetch-suggestions="querySearch"
          @select="handleSelect"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="创建时间" prop="recordTime">
        <el-date-picker clearable
                        v-model="queryParams.recordTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="维护标题" prop="maintainTitle">
        <el-input
          v-model="queryParams.maintainTitle"
          placeholder="请输入维护标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维护人" prop="maintainPerson">
        <el-input
          v-model="queryParams.maintainPerson"
          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-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="['ems:rbook:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ems:rbook:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rbookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="记录编号" align="center" prop="recordCode"/>
      <el-table-column label="目标对象" align="center" prop="objName">
        <template slot-scope="scope">
          <span v-if="scope.row.objType">({{ dict.type.device_type[scope.row.objType].label }}) {{
              scope.row.objName
            }}</span>
          <span v-else>({{ dict.type.device_type[scope.row.objType].label }}){{ scope.row.objName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装位置" align="center" prop="insLocation"/>
      <el-table-column label="维护标题" align="center" prop="maintainTitle"/>
      <el-table-column label="创建时间" align="center" prop="recordTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护人" align="center" prop="maintainPerson"/>
      <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-document" @click="handleViewRec(scope.row)">
            查看
          </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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="记录编号" prop="recordCode">
          <el-input v-model="form.recordCode" placeholder="请输入记录编号" :disabled="isViewOnly"/>
        </el-form-item>
        <el-form-item label="对象类型">
          <el-select v-model="form.objType" placeholder="请选择对象类型" @change="changeObjOptions"
                     :disabled="isViewOnly">
<!--            <el-option v-for = "item in objTypeOptions"-->
<!--                       :label="item.name"-->
<!--                       :value="item.code"-->
<!--                       :key="item.code" />-->
            <el-option
              v-for="dict in dict.type.device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="    " prop="objCode" v-if="showObjCode">
          <el-cascader
            v-model="form.objCode"
            :options="AllCode"
            placeholder="请选择具体数据"
            @change="handleSelect"
            :props="{ value: 'value', label: 'label', children: 'children' }"
            :disabled="isViewOnly"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="创建时间" prop="recordTime">
          <el-date-picker clearable
                          v-model="form.recordTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择日期 yyyy-MM-dd HH:mm:ss"
                          :disabled="isViewOnly"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="目标对象" prop="objName">
          <el-input v-model="form.objName" placeholder="请输入对象名称" :disabled="isViewOnly"/>
        </el-form-item>
        <el-form-item label="安装位置" prop="insLocation">
          <el-input v-model="form.insLocation" placeholder="请输入安装位置" :disabled="isViewOnly"/>
        </el-form-item>
        <el-form-item label="维护标题" prop="maintainTitle">
          <el-input v-model="form.maintainTitle" placeholder="请输入维护标题" :disabled="isViewOnly"/>
        </el-form-item>
        <el-form-item label="维护内容">
          <!-- 只读模式下显示内容 -->
          <div v-if="isViewOnly" v-html="form.maintainContent"></div>
          <!-- 编辑模式下显示编辑器 -->
          <editor v-else v-model="form.maintainContent" :min-height="192"></editor>
        </el-form-item>
        <el-form-item label="维护人" prop="maintainPerson">
          <el-input v-model="form.maintainPerson" placeholder="请输入维护人" :disabled="isViewOnly"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 只在非查看模式显示提交按钮 -->
        <el-button type="primary" v-if="!isViewOnly" @click="submitForm">确 定</el-button>
        <!-- 编辑按钮，点击切换到编辑模式 -->
        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit" v-hasPermi="['ems:rbook:edit']">
          编辑
        </el-button>
        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(selectedRow)"
                   v-hasPermi="['ems:rbook:remove']"
        >删除
        </el-button>
        <el-button v-if="isViewOnly" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改设备台账对话框 -->
    <el-dialog :title="title" :visible.sync="addOrUpdateOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="记录编号" prop="recordCode">
          <el-input v-model="form.recordCode" placeholder="请输入记录编号"/>
        </el-form-item>
        <el-form-item label="对象类型">
          <el-select v-model="form.objType" placeholder="请选择对象类型" @change="changeObjOptions">
            <el-option
              v-for="dict in dict.type.device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="   " prop="objCode" v-if="showObjCode">
          <el-cascader
            v-model="form.objCode"
            :options="AllCode"
            placeholder="请选择具体数据"
            @change="handleSelect"
            :props="{ value: 'value', label: 'label', children: 'children' }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="创建时间" prop="recordTime">
          <el-date-picker clearable
                          v-model="form.recordTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择日期 "
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="目标对象" prop="objName">
          <el-input v-model="form.objName" placeholder="请输入对象名称"/>
        </el-form-item>
        <el-form-item label="安装位置" prop="insLocation">
          <el-input v-model="form.insLocation" placeholder="请输入安装位置"/>
        </el-form-item>
        <el-form-item label="维护标题" prop="maintainTitle">
          <el-input v-model="form.maintainTitle" placeholder="请输入维护标题"/>
        </el-form-item>
        <el-form-item label="维护内容">
          <editor v-model="form.maintainContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="维护人" prop="maintainPerson">
          <el-input v-model="form.maintainPerson" placeholder="请输入维护人"/>
        </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 { listRbook, getRbook, delRbook, addRbook, updateRbook } from '@/api/device/rbook'
import { listAllFacs } from '@/api/basecfg/emsfacs'
import { devTreeByFacs, listDevice, listDevRecursionByArea } from '@/api/device/device'
import Treeselect from '@riophae/vue-treeselect'

export default {
  name: 'Rbook',
  components: { Treeselect },
  dicts: ['device_type'],
  data() {
    return {
      isViewOnly: false, // 添加这个标志变量
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备台账表格数据
      rbookList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      addOrUpdateOpen: false,
      //能源设施全部数据
      AllCode: [],
      objCodeOptions: [],
      areaCode: '',
      // 控制对象代码显示的变量
      showObjCode: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        selectedRow: null,
        recordTime: null,
        recordCode: null,
        objType: null,
        objCode: null,
        objName: null,
        insLocation: null,
        maintainTitle: null,
        maintainContent: null,
        maintainPerson: null,
        recordTimeRange: []
      },
      queryFacsParams: {
        areaCode: ''
      },
      objTypeOptions: [
      { code: 1, name: '设施' },
      { code: 0, name: '设备' },
    ],

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        recordCode: [
          { required: true, message: '记录编号不能为空', trigger: 'blur' }
        ],
        objType: [
          { required: true, message: '对象类型不能为空', trigger: 'change' }
        ],
        maintainTitle: [
          { required: true, message: '维护标题不能为空', trigger: 'blur' }
        ],
        recordTime: [
          { required: true, message: '日期 yyyy-MM-dd 不能为空', trigger: 'blur' }
        ]
      }
    }

  },
  created() {
    this.getList()
  },
  // 当对象类型有值时，显示对象代码输入框
  watch: {
    'form.objType'(newVal) {
      this.showObjCode = !!newVal
    }
  },
  methods: {
    /** 查询设备台账列表 */
    getList() {
      this.loading = true
      listRbook(this.queryParams).then(response => {
        console.log('设备台账搜索参数！！！！！', this.queryParams)
        this.rbookList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      // this.isViewOnly = true; // 切换回只读模式
      this.addOrUpdateOpen = false
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        recordCode: null,
        objType: null,
        objCode: null,
        objName: null,
        recordTime: null,
        insLocation: null,
        maintainTitle: null,
        maintainContent: null,
        maintainPerson: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm('form')
      this.dateRange = []
    },
    // 搜索建议的方法
    querySearch(queryString, cb) {
      const results = this.rbookList.filter(item => {
        return item.objName.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
      })
      // 调用回调函数，返回建议列表
      cb(results.map(item => ({ value: item.objName })))
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /**对象类型*/
    changeObjOptions(objType) {
      if (objType == 1) {
        this.queryFacsParams.areaCode = this.areaCode
        // 设施
        listAllFacs(this.queryFacsParams).then(response => {
          this.objCodeOptions = response.data
          console.log('设施多少数据！！！', this.objCodeOptions)
          this.AllCode = this.objCodeOptions.map(item => ({
            value: item.facsCode,
            label: item.facsName
          }))
        })
      } else if (objType == 0) {
        // 设备
        devTreeByFacs(this.areaCode).then(response => {
          this.objCodeOptions = response.data
          console.log('设备多少数据！！！', this.objCodeOptions)
          this.AllCode = this.buildTree(this.objCodeOptions)

        })

      }
    },
    buildTree(data) {
      return data.map(item => {
        const node = {
          value: item.id,
          label: item.label,
          children: item.children ? this.buildTree(item.children) : undefined
        }
        return node
      })
    },

    /** 数据自动填补*/
    handleSelect(value) {

      // 检查 value 是否为数组
      if (Array.isArray(value)) {
        // 检查数组是否至少有一个元素，并且第一个元素的首字母是否为字母
        if (value.length > 0 && /^[a-zA-Z]/.test(value[0][0])) {
          this.queryFacsParams.areaCode = this.areaCode

          // 获取能源设施所有信息
          listAllFacs(this.queryFacsParams).then(response => {
            const data = response.data
            console.log('data', data)
            // 循环输出
            for (let i = 0; i < data.length; i++) {
              if (value.includes(data[i].facsCode)) {
                this.form.objName = data[i].facsName
                this.form.insLocation = data[i].refAreaName
                console.log('设施名字', this.form.objName)
                console.log('设施地址', this.form.insLocation)
                return
              }
            }
          })
        } else if (value.length > 0) {
          // 获取能源设备所有信息
          devTreeByFacs(this.areaCode).then(response => {
            const data = response.data
            console.log('data', data)

            function findDeviceById(data, path = [], ids) {
              for (const item of data) {
                const currentPath = [...path, { label: item.label, tier: item.tier }]
                if (ids.includes(item.id)) {
                  // 找到 tier 为 'Device' 的层级，并获取最后一个“-”后面的数据
                  const deviceTierIndex = currentPath.findIndex(p => p.tier === 'Device')
                  let lastSegment = ''
                  let deviceLabel = ''
                  if (deviceTierIndex !== -1) {
                    deviceLabel = currentPath[deviceTierIndex].label
                    lastSegment = deviceLabel.split('-').pop()
                  }
                  return { labels: currentPath, lastSegment, deviceLabel, found: true }
                }
                if (item.children && item.children.length) {
                  const result = findDeviceById(item.children, currentPath, ids)
                  if (result.found) {
                    return result
                  }
                }
              }
              return { labels: [], lastSegment: null, deviceLabel: '', found: false }
            }

            let lastResult = { labels: [], lastSegment: null, deviceLabel: '', found: false }
            value.forEach(id => {
              const result = findDeviceById(data, [], [id])
              if (result.found) {
                lastResult = result
              }
            })

            if (lastResult.found) {
              // 构建 insLocation 和 objName
              let insLocationParts = [lastResult.labels[0].label] // 第一层的 label
              if (lastResult.deviceLabel) {
                let deviceLabelParts = lastResult.deviceLabel.split('-')
                deviceLabelParts.pop() // 移除最后一个“-”后面的数据
                insLocationParts = insLocationParts.concat(deviceLabelParts.join('-'))
              }

              this.form.insLocation = insLocationParts.join(' / ')
              this.form.objName = lastResult.lastSegment
              console.log('设备名字', this.form.objName)
              console.log('设备地址', this.form.insLocation)
            } else {
              console.log('没有找到匹配的设备')
            }
          })
        } else {
          console.log('value 为空数组或不满足条件')
        }
      } else {
        console.log('value 不是数组')
      }
    },

    /**编辑按钮操作*/
    handleEdit() {
      this.isViewOnly = false // 切换到编辑模式
      this.title = '编辑设备台账'
    },

    // /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.addOrUpdateOpen = true
      this.title = '添加设备台账'
    },
    /**查看按钮*/
    handleViewRec(row) {
      this.selectedRow = row
      const id = row.id || this.ids
      getRbook(id).then(response => {
        this.form = response.data
        console.log('this.form', this.form)
        this.form.objCode = this.form.objCode ? this.form.objCode.split(',') : []
        // 调用 changeObjOptions 来更新 AllCode
        this.changeObjOptions(this.form.objType)
        this.open = true
        this.title = '查看设备台账'
        this.isViewOnly = true // 设置为查看模式
        // if (this.form.objType === 1) {
        //   this.form.objType = "设施";
        // } else if (this.form.objType === 0) {
        //   this.form.objType = "设备";
        // }
      })
    },
    /** 提交按钮 */
    submitForm() {
      // 确保 objCode 是一个数组
      if (!Array.isArray(this.form.objCode)) {
        this.form.objCode = [this.form.objCode]
      }
      this.form.objCode = this.form.objCode.join(',')
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRbook(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              console.log('点击确认后response里面的内容', response)
              this.open = false
              this.addOrUpdateOpen = false
              this.getList()
            })
          } else {
            addRbook(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.addOrUpdateOpen = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除设备台账编号为"' + ids + '"的数据项？').then(function() {
        return delRbook(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/rbook/export', {
        ...this.queryParams
      }, `rbook_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
