<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--公司数据-->
      <el-col :span="4" :xs="24">
        <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 :data="deptOptions" :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="equipmenttype">
            <el-input v-model="queryParams.equipmenttype" placeholder="请输入装备分类" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="装备名称" prop="equipmentName">
            <el-input v-model="queryParams.equipmentName" placeholder="请输入装备名称" clearable style="width: 240px"
                      @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>

        <!-- 优化后的当前公司显示区域 -->
        <div class="current-dept-info" v-if="currentDeptName">
          <div class="dept-title">当前公司</div>
          <div class="dept-name">{{ currentDeptName }}</div>
        </div>
        <div v-else class="dept-placeholder">
          请从左侧选择公司
        </div>

        <el-table
          v-loading="loading"
          :data="userList"
          @row-dblclick="handleRowDblClick"
          :row-class-name="getRowClassName"
          height="546"
        >
          <el-table-column label="装备分类" align="center" key="equipmentName" prop="equipmentName"
                           :show-overflow-tooltip="true"
          />
          <el-table-column label="装备名称" align="center" key="equipmenttype" prop="equipmenttype"/>
          <el-table-column label="基本配置" align="center" prop="configStatus"/>
          <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="handleRowDblClick(scope.row)"
                v-hasPermi="['system:whitelist:edit']"
              >装备配置
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination  :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 基本配置编辑弹窗 -->
    <el-dialog
      title="编辑基本配置"
      :visible.sync="inputDialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
     <!-- 新增装备名称显示区域 -->
        <div class="equipment-title">
          <span class="title-label">装备名称：</span>
          <span class="title-value">{{ currentEquipmentName }}</span>
        </div>
      <el-form ref="configForm" :model="configForm" :rules="configRules">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addConfig" style="margin-bottom:10px;">
          添加配置
        </el-button>
         <div class="config-table-header">
                  <span class="config-th" style="width:180px;">配置类型</span>
                  <span class="config-th" style="width:180px;">基本配置标准(台/套)</span>
                  <span class="config-th" style="width:180px;">装备配置率</span>
                  <span class="config-th" style="width:180px;">配置说明</span>
                  <span class="config-th" style="width:80px;">操作</span>
                </div>
        <div v-for="(item, index) in configForm.configs" :key="index"
             style="border:1px solid #eee;padding:10px;margin-bottom:10px;"
        >
          <el-form-item style="margin:auto" :prop="`configs.${index}.configurationType`">
            <el-select v-model="item.configurationType" placeholder="请选择配置类型" clearable style="width: 180px">
              <el-option v-for="dict in dict.type.config_type" :key="dict.value" :label="dict.label"
                         :value="dict.value"
              />
            </el-select>
            <el-input style="width: 180px;margin-left: 10px"
                      v-model="item.basicConfig"
                      placeholder="请输入基本配置标准"
                      clearable
            />
            <el-input style="width: 180px ;margin-left: 10px"
                      v-model="item.configurationRate"
                      placeholder="请输入装备配置率"
                      clearable
            />
            <el-input style="width: 180px ;margin-left: 10px"
                      v-model="item.configurationDescription"
                      placeholder="请输入配置说明"
                      clearable
            />
            <el-button style="margin-left: 10px" type="danger" size="mini" @click="removeConfig(index)">删除</el-button>
          </el-form-item>


        </div>


      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="inputDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitConfig">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, updateEquipmentConfig, deptTreeSelect, selectConfigList } from '@/api/system/equipment'

export default {
  name: 'User',
  dicts: ['config_type'],
  data() {
    // 自定义数字验证规则
    const validateNumber = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入配置值'))
      } else if (isNaN(Number(value))) {
        callback(new Error('必须输入数字'))
      } else {
        callback()
      }
    }

    return {
      // 新增两个数据项
      dialogTitle: "编辑基本配置", // 弹窗标题
      currentEquipmentName: "",    // 当前编辑的装备名称
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 装备表格数据
      userList: null,
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 当前选择的部门ID
      currentDeptId: null,
      // 当前选择的部门名称
      currentDeptName: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        equipmentName: undefined,
        equipmenttype: undefined
      },
      // 弹窗相关
      inputDialogVisible: false,
      // 配置表单
      configForm: {
        equipmentId: null,
        deptId: null,
        configs: []
      },
      // 配置表单验证规则
      configRules: {
        configs: {
          type: 'array',
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              return callback(new Error('请至少添加一个配置模块'))
            }
            for (const [i, item] of value.entries()) {
              if (!item.configurationType) {
                return callback(new Error(`第 ${i + 1} 个模块：配置类型不能为空`))
              }
              if (!item.basicConfig || isNaN(Number(item.basicConfig))) {
                return callback(new Error(`第 ${i + 1} 个模块：数字配置必须是数字`))
              }
              if (!item.configurationRate) {
                return callback(new Error(`第 ${i + 1} 个模块：装备配置率不能为空`))
              }
              if (!item.configurationDescription) {
                return callback(new Error(`第 ${i + 1} 个模块：配置说明不能为空`))
              }
            }
            callback()
          },
          trigger: 'blur'
        }
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
  },
  methods: {
    addConfig() {
      this.configForm.configs.push({
        configurationType: '',
        basicConfig: '',
        configurationRate: '',
        configurationDescription: ''
      })
    },
    removeConfig(index) {
      this.configForm.configs.splice(index, 1)
    },
    /** 双击行事件 */
    handleRowDblClick(row) {
      // 在打开弹窗前设置当前装备名称
      this.currentEquipmentName = row.equipmentName;
      // 更新弹窗标题
      this.dialogTitle = `编辑基本配置 - ${row.equipmentName}`;
      this.configForm.deptId = this.currentDeptId;
      this.configForm.equipmentId = row.equipmentId;
      this.configForm.configs =[]
      // 检查是否选择了部门
      if (!this.currentDeptId) {
        this.$message.warning('请先在左侧选择公司')
        return
      }

      // 检查是否可编辑
      if (!this.checkSelectable(row)) return
      selectConfigList({
        typeId: row.equipmentId,
        deptId: this.currentDeptId
      }).then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.configForm.configs.push(item);
          });
        }
      })
      this.inputDialogVisible = true

      // 清除验证
      this.$nextTick(() => {
        if (this.$refs.configForm) {
          this.$refs.configForm.clearValidate()
        }
      })
    },

    /** 提交配置 */
    submitConfig() {
      this.$refs.configForm.validate(valid => {
        if (valid) {
          this.saveConfig()
        }
      })
    },

    /** 保存配置到后端 */
    saveConfig() {
      /*   console.log(this.configForm)
        this.loading = true
        // 转换为数字类型
        const params = {
          equipmentId: this.configForm.equipmentId,
          deptId: this.configForm.deptId,
          basicConfig: Number(this.configForm.basicConfig)
        }
   */

      updateEquipmentConfig(this.configForm).then(response => {
        this.$message.success('配置保存成功')
        this.getList()
        /*  // 更新前端显示
         const index = this.userList.findIndex(item => item.equipmentId === params.equipmentId)
         if (index !== -1) {
           this.$set(this.userList[index], 'basicConfig', params.basicConfig)
         }
  */
        this.inputDialogVisible = false
        this.loading = false
      }).catch(error => {
        console.error('保存配置失败:', error)
        this.$message.error('保存配置失败')
        this.loading = false
      })
    },

    /** 查询装备列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = (response.rows || []).map(item => {
          // 确保每行都有basicConfig属性
          if (item.basicConfig === undefined) {
            item.basicConfig = ''
          }
          return item
        })
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取装备列表失败:', error)
        this.loading = false
      })
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        // 根据API实际响应结构处理
        let treeData = response.data

        // 如果API返回的是标准响应格式
        if (response.code && response.data) {
          treeData = response.data
        }

        this.deptOptions = treeData || []
      }).catch(error => {
        console.error('获取部门树失败:', error)
        this.$message.error('获取部门树失败')
      })
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.currentDeptId = data.id // 保存当前选择的部门ID
      this.currentDeptName = data.label // 保存当前选择的部门名称
      this.queryParams.deptId = data.id
      this.handleQuery()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.equipmentName = undefined
      this.queryParams.equipmenttype = undefined
      this.currentDeptId = null // 重置部门ID
      this.currentDeptName = '' // 重置部门名称
      if (this.$refs.tree) {
        this.$refs.tree.setCurrentKey(null)
      }
      this.handleQuery()
    },

    // 检查行是否可编辑
    checkSelectable(row) {
      // 这里保留原有的不可编辑逻辑
      return !(row.userId === 1 || row.isBuiltIn === '0' || this.hasSystemOrAuditrRole(row.roles))
    },

    hasSystemOrAuditrRole(roles) {
      if (!roles || !Array.isArray(roles)) return false
      return roles.some(role => role.roleKey === 'systemAdmin' || role.roleKey === 'audit')
    },

    getRowClassName({ row }) {
      return !this.checkSelectable(row) ? 'disabled-row' : ''
    }
  }
}
</script>

<style>
/* 修复被动事件监听器警告 */
.el-dialog__wrapper {
  touch-action: none;
}

.disabled-row {
  background-color: #f5f7fa !important;
  color: #909399;
  cursor: not-allowed;
}

.disabled-row:hover td {
  background-color: #f5f7fa !important;
}

/* 优化后的部门信息样式 */
.current-dept-info {
  display: flex;
  align-items: center;
  margin: 0 0 20px 0;
  padding: 12px 15px;
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f7ff 100%);
  border-radius: 6px;
  border-left: 4px solid #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.dept-title {
  font-weight: 600;
  color: #606266;
  margin-right: 10px;
  font-size: 14px;
}

.dept-name {
  font-weight: 700;
  font-size: 16px;
  color: #1a73e8;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}

.dept-placeholder {
  margin: 0 0 20px 0;
  padding: 12px 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  color: #909399;
  font-style: italic;
  font-size: 14px;
  border: 1px dashed #dcdfe6;
}
/* 配置弹窗表头样式 */
.config-table-header {
  display: flex;
  background: #f5f7fa;
  border-radius: 4px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  padding: 8px 0 8px 8px;
  border: 1px solid #ebeef5;
}
.config-th {
  display: inline-block;
  text-align: center;
  font-size: 14px;
  margin-right: 10px;
}
.config-table-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
/* 新增装备名称显示样式 */
.equipment-title {
  margin-bottom: 20px;
  padding: 10px 15px;
  background-color: #f0f7ff;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.title-label {
  font-weight: bold;
  color: #606266;
}

.title-value {
  font-weight: bold;
  color: #1a73e8;
  margin-left: 8px;
}
</style>
