<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="风机编号" prop="equipmentCode">
        <el-input
          v-model="queryParams.equipmentCode"
          placeholder="请输入风机编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="维保中心" prop="maintenanceCenter">
        <el-select 
          v-model="queryParams.maintenanceCenter" 
          placeholder="请选择维保中心" 
          clearable 
          @change="handleMaintenanceCenterChange"
          style="width: 200px"
        >
          <el-option
            v-for="item in maintenanceCenterOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="场站" prop="station">
        <el-select 
          v-model="queryParams.station" 
          placeholder="请选择场站" 
          clearable
          :disabled="!queryParams.maintenanceCenter"
          style="width: 200px"
        >
          <el-option
            v-for="item in stationOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-select 
          v-model="queryParams.brand" 
          placeholder="请选择品牌" 
          clearable 
          @change="handleBrandChange"
          style="width: 200px"
        >
          <el-option
            v-for="item in brandOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="机型" prop="model">
        <el-select 
          v-model="queryParams.model" 
          placeholder="请选择机型" 
          clearable
          :disabled="!queryParams.brand"
          style="width: 200px"
        >
          <el-option
            v-for="item in modelOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['gxt:equipment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gxt:equipment:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gxt:equipment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['gxt:equipment:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['gxt:equipment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 测试设备选择组件 -->
<!--    <el-row :gutter="10" class="mb8">
      <el-col :span="4">
        <div style="display: flex; align-items: center;">
          <el-input v-model="singleEquipmentCode" placeholder="单选设备编号" readonly>
            <template #append>
              <el-button @click="handleSingleEquipmentSelect" icon="Search"></el-button>
            </template>
          </el-input>
        </div>
      </el-col>
      <el-col :span="4">
        <div style="display: flex; align-items: center;">
          <el-input v-model="multiEquipmentCodes" placeholder="多选设备编号" readonly>
            <template #append>
              <el-button @click="handleMultiEquipmentSelect" icon="Search"></el-button>
            </template>
          </el-input>
        </div>
      </el-col>
    </el-row>-->

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="维保中心" align="center" prop="maintenanceCenter" />
      <el-table-column label="场站" align="center" prop="station" />
      <el-table-column label="风机编号" align="center" prop="equipmentCode" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="机型" align="center" prop="model" />
      <el-table-column label="责任人" align="center" prop="responsiblePersonName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['gxt:equipment:edit']">修改</el-button> -->
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['gxt:equipment:query']">查看</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['gxt:equipment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="equipmentRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="风机编号" prop="equipmentCode">
              <el-input v-model="form.equipmentCode" :readonly="optType === 'view'" placeholder="请输入风机编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保中心" prop="maintenanceCenter">
              <el-input v-model="form.maintenanceCenter" :readonly="optType === 'view'" placeholder="请输入维保中心" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场站" prop="station">
              <el-input v-model="form.station" :readonly="optType === 'view'" placeholder="请输入场站" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" :readonly="optType === 'view'" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机型" prop="model">
              <el-input v-model="form.model" :readonly="optType === 'view'" placeholder="请输入机型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任人" prop="responsiblePersonName">
              <el-input v-model="form.responsiblePersonName" :readonly="optType === 'view'" placeholder="请输入责任人" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- 根据optType决定是否显示提交按钮 -->
          <el-button v-if="optType !== 'view'" type="primary" @click="submitForm">确 定</el-button>
          <el-button v-if="optType !== 'view'" @click="cancel">取 消</el-button>
          <el-button v-if="optType === 'view'" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-change="handleFileChange" :on-remove="handleFileRemove" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的设备数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 单选设备选择组件 -->
    <equipment-select-single v-model="singleEquipmentSelectVisible" @onSelected="onSingleEquipmentSelected"></equipment-select-single>
    
    <!-- 多选设备选择组件 -->
    <equipment-select-multi v-model="multiEquipmentSelectVisible" @onSelected="onMultiEquipmentSelected"></equipment-select-multi>
  </div>
</template>

<script setup name="Equipment">
import { getToken } from "@/utils/auth"
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment, listBrands, listModelsByBrand } from "@/api/gxt/equipment"
import { listDept } from "@/api/system/dept"
import EquipmentSelectSingle from "@/components/equipmentSelect/single.vue"
import EquipmentSelectMulti from "@/components/equipmentSelect/multi.vue"

const { proxy } = getCurrentInstance()

const equipmentList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 添加optType变量用于区分操作类型
const optType = ref("") // 'add' | 'edit' | 'view'
const codes = ref([])

// 维保中心和场站选项
const maintenanceCenterOptions = ref([])
const stationOptions = ref([])

// 品牌和机型选项
const brandOptions = ref([])
const modelOptions = ref([])

// 设备选择相关变量
const singleEquipmentCode = ref("") // 单选设备编号
const multiEquipmentCodes = ref("") // 多选设备编号
const singleEquipmentSelectVisible = ref(false) // 单选设备选择组件可见性
const multiEquipmentSelectVisible = ref(false) // 多选设备选择组件可见性

/*** 设备导入参数 */
const upload = reactive({
  // 是否显示弹出层（设备导入）
  open: false,
  // 弹出层标题（设备导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的设备数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/gxt/equipment/importData"
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipmentCode: null,
    maintenanceCenter: null,
    station: null,
    brand: null,
    model: null,
    equipmentType: null,
    status: null,
  },
  rules: {
    /*equipmentCode: [
      { required: true, message: "风机编号不能为空", trigger: "blur" }
    ],*/
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询设备管理列表 */
function getList() {
  loading.value = true
  listEquipment(queryParams.value).then(response => {
    equipmentList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询维保中心和场站列表 */
function getMaintenanceCenterAndStationList() {
  listDept({}).then(response => {
    const depts = response.data;
    
    // 筛选出维保中心(level=2)
    maintenanceCenterOptions.value = depts.filter(dept => dept.level === "2");
    
    // 筛选出场站(level=3)
    const stations = depts.filter(dept => dept.level === "3");
    
    // 如果已选择维保中心，则筛选出该维保中心下的场站
    if (queryParams.value.maintenanceCenter) {
      const selectedMaintenanceCenter = maintenanceCenterOptions.value.find(
        center => center.deptName === queryParams.value.maintenanceCenter
      );
      
      if (selectedMaintenanceCenter) {
        stationOptions.value = stations.filter(
          station => station.ancestors.includes(selectedMaintenanceCenter.deptId)
        );
      } else {
        stationOptions.value = [];
      }
    } else {
      // 如果未选择维保中心，则清空场站选项
      stationOptions.value = [];
    }
  });
}

/** 维保中心选择变化时 */
function handleMaintenanceCenterChange(selectedCenter) {
  // 清空场站选择
  queryParams.value.station = null;
  
  // 如果选择了维保中心，则加载对应的场站
  if (selectedCenter) {
    listDept({}).then(response => {
      const depts = response.data;
      const stations = depts.filter(dept => dept.level === "3");
      
      // 找到选中的维保中心
      const selectedMaintenanceCenter = maintenanceCenterOptions.value.find(
        center => center.deptName === selectedCenter
      );
      
      if (selectedMaintenanceCenter) {
        // 筛选出该维保中心下的场站
        stationOptions.value = stations.filter(
          station => station.ancestors.includes(selectedMaintenanceCenter.deptId)
        );
      }
    });
  } else {
    // 如果未选择维保中心，则清空场站选项
    stationOptions.value = [];
  }
}

/** 查询品牌列表 */
function getBrandList() {
  listBrands().then(response => {
    brandOptions.value = response.data
  })
}

/** 根据品牌查询机型列表 */
function getModelListByBrand(brand) {
  if (!brand) {
    modelOptions.value = []
    return
  }
  listModelsByBrand(brand).then(response => {
    modelOptions.value = response.data
  })
}

// 品牌选择变化时，清空机型选择并加载对应机型
function handleBrandChange(brand) {
  queryParams.value.model = null
  getModelListByBrand(brand)
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    equipmentId: null,
    equipmentCode: null,
    maintenanceCenter: null,
    station: null,
    brand: null,
    model: null,
    equipmentType: null,
    status: null,
    responsiblePersonName: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("equipmentRef")
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.equipmentId)
  codes.value = selection.map(item => item.equipmentCode)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  optType.value = "add"
  open.value = true
  title.value = "添加设备"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _equipmentId = row.equipmentId || ids.value
  getEquipment(_equipmentId).then(response => {
    form.value = response.data
    optType.value = "edit"
    open.value = true
    title.value = "修改设备"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["equipmentRef"].validate(valid => {
    if (valid) {
      if (form.value.equipmentId != null) {
        updateEquipment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addEquipment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _equipmentIds = row.equipmentId || ids.value
  const _equipmentCodes = row.equipmentCode || codes.value
  proxy.$modal.confirm('是否确认删除设备编号为"' + _equipmentCodes + '"的数据项？').then(function() {
    return delEquipment(_equipmentIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('gxt/equipment/export', {
    ...queryParams.value
  }, `equipment_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "设备导入"
  upload.open = true
  upload.selectedFile = null
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("gxt/equipment/importTemplate", {
  }, `equipment_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件选择处理 */
const handleFileChange = (file, fileList) => {
  upload.selectedFile = file
}

/** 文件删除处理 */
const handleFileRemove = (file, fileList) => {
  upload.selectedFile = null
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  const file = upload.selectedFile
  if (!file || file.length === 0 || !file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx')) {
    proxy.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
    return
  }
  proxy.$refs["uploadRef"].submit()
}

/** 查看按钮操作 */
function handleView(row) {
  reset()
  const _equipmentId = row.equipmentId || ids.value
  getEquipment(_equipmentId).then(response => {
    form.value = response.data
    optType.value = "view" // 设置为查看模式
    open.value = true
    title.value = "查看设备"
  })
}

// 单选设备选择按钮
function handleSingleEquipmentSelect() {
  singleEquipmentSelectVisible.value = true
}

// 多选设备选择按钮
function handleMultiEquipmentSelect() {
  multiEquipmentSelectVisible.value = true
}

// 单选设备选择回调
function onSingleEquipmentSelected(row) {
  if (row != null) {
    singleEquipmentCode.value = row.equipmentCode
  }
  singleEquipmentSelectVisible.value = false
}

// 多选设备选择回调
function onMultiEquipmentSelected(rows) {
  if (rows != null && rows.length > 0) {
    multiEquipmentCodes.value = rows.map(item => item.equipmentCode).join(", ")
  } else {
    multiEquipmentCodes.value = ""
  }
  multiEquipmentSelectVisible.value = false
}

getMaintenanceCenterAndStationList()
getBrandList()
getList()
</script>