<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备ID" prop="deviceId">
              <el-input v-model="queryParams.deviceId" placeholder="请输入设备ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
                <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="安装位置" prop="installPosition">
              <el-cascader
                v-model="queryParams.installPosition"
                :options="floorOptions"
                :props="floorCascaderProps"
                placeholder="请选择安装位置"
                clearable
                filterable
              />
            </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-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        border
        :data="deviceTreeList"
        row-key="id"
        :tree-props="{ children: 'children' }"
        default-expand-all
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备ID" prop="deviceId" min-width="130" />
        <el-table-column label="设备名称" prop="deviceName" min-width="140" />
        <el-table-column label="设备编号" prop="deviceCode" min-width="140" />
        <el-table-column label="状态" prop="status" width="90">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">{{ formatDeviceStatus(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="安装位置" prop="installPositionName" min-width="220" show-overflow-tooltip />
        <el-table-column label="节点类型" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.isDeviceGroup === '1'" type="warning">设备组</el-tag>
            <el-tag v-else type="success">设备</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="所属设备组" prop="parentDeviceGroupName" min-width="140" show-overflow-tooltip />
        <el-table-column label="设备类型" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="device_type" :value="scope.row.deviceType" />
          </template>
        </el-table-column>
        <el-table-column label="计量参数" prop="standardUnitName" min-width="260" show-overflow-tooltip />
        <el-table-column label="已绑定报警规则" prop="alarmRuleNames" min-width="220" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.alarmRuleNames || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="规格型号" prop="specificationModel" min-width="120" />
        <el-table-column label="生产厂家" prop="manufacturer" min-width="140" />
        <el-table-column label="出厂编号" prop="factoryNo" min-width="130" />
        <el-table-column label="精度等级" prop="accuracyLevel" width="100" />
        <el-table-column label="量程" prop="measureRange" min-width="120" />
        <el-table-column label="通讯协议" prop="communicationProtocol" min-width="120" />
        <el-table-column label="通讯地址" prop="communicationAddress" min-width="120" />
        <el-table-column label="采集周期" prop="collectionCycle" width="100" />
        <el-table-column label="上次检定日期" prop="lastVerificationDate" align="center" width="120" />
        <el-table-column label="责任部门" prop="responsibleDept" min-width="120" />
        <el-table-column label="责任人" prop="responsiblePerson" width="100" />
        <el-table-column label="备注" prop="remark" min-width="160" show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" align="center" width="190">
          <template #default="scope">
            <el-tooltip v-if="scope.row.isDeviceGroup === '1'" content="挂载设备" placement="top">
              <el-button link type="primary" icon="Connection" @click="handleMountChildren(scope.row)" />
            </el-tooltip>
            <el-tooltip content="生成测控点" placement="top">
              <el-button link type="primary" icon="Aim" @click="handleGeneratePoint(scope.row)" />
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="780px">
      <el-form ref="deviceFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="是否设备组" prop="isDeviceGroup">
              <el-radio-group v-model="form.isDeviceGroup" @change="handleDeviceGroupChange">
                <el-radio-button label="1">设备组</el-radio-button>
                <el-radio-button label="0">设备</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="form.isDeviceGroup === '1' ? '设备组ID' : '设备ID'" prop="deviceId">
              <el-input v-model="form.deviceId" :placeholder="form.isDeviceGroup === '1' ? '请输入设备组ID' : '请输入设备ID'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="form.isDeviceGroup === '1' ? '设备组名称' : '设备名称'" prop="deviceName">
              <el-input v-model="form.deviceName" :placeholder="form.isDeviceGroup === '1' ? '请输入设备组名称' : '请输入设备名称'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="form.isDeviceGroup === '1' ? '设备组编号' : '设备编号'" prop="deviceCode">
              <el-input v-model="form.deviceCode" :placeholder="form.isDeviceGroup === '1' ? '请输入设备组编号' : '请输入设备编号'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="form.isDeviceGroup === '1' ? '设备组类型' : '设备类型'" prop="deviceType">
              <el-select v-model="form.deviceType" placeholder="请选择设备类型" @change="handleDeviceTypeChange">
                <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="规格型号">
              <el-input v-model="form.specificationModel" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="生产厂家">
              <el-input v-model="form.manufacturer" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="出厂编号">
              <el-input v-model="form.factoryNo" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="精度等级">
              <el-input v-model="form.accuracyLevel" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="量程">
              <el-input v-model="form.measureRange" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="通讯协议">
              <el-input v-model="form.communicationProtocol" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="采集周期">
              <el-input v-model="form.collectionCycle" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option v-for="item in deviceStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="上次检定日期">
              <el-date-picker v-model="form.lastVerificationDate" type="date" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="责任人">
              <el-input v-model="form.responsiblePerson" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="计量参数">
              <div class="unit-table-wrap">
                <el-table border :data="form.units || []">
                  <el-table-column label="参数名称" min-width="220">
                    <template #default="scope">
                      <el-select
                        v-model="scope.row.parameterName"
                        placeholder="请选择能源指标"
                        filterable
                        clearable
                        @change="handleUnitParameterChange(scope.row)"
                      >
                        <el-option v-for="item in standardUnitOptions" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="原始单位" min-width="140">
                    <template #default="scope">
                      <el-input v-model="scope.row.measuringUnit" placeholder="如 kWh、m3" />
                    </template>
                  </el-table-column>
                  <el-table-column label="标准单位" width="120">
                    <template #default="scope">
                      {{ getMetricUnit(scope.row.parameterName) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="换算倍率" width="170">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.conversionFactor" :min="0" :precision="6" controls-position="right" />
                    </template>
                  </el-table-column>
                  <el-table-column label="数据占比(%)" width="170">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.dataRatio" :min="1" :precision="4" controls-position="right" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="80">
                    <template #default="scope">
                      <el-button link type="primary" icon="Delete" @click="removeUnitRow(scope.$index)" />
                    </template>
                  </el-table-column>
                </el-table>
                <el-button class="mt-2" type="primary" plain icon="Plus" @click="addUnitRow">新增计量参数</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="mountDialog.visible" title="挂载设备" append-to-body width="860px">
      <el-form label-width="100px">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="设备组ID">
              <el-input :model-value="currentMountGroup?.deviceId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备组名称">
              <el-input :model-value="currentMountGroup?.deviceName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备组编号">
              <el-input :model-value="currentMountGroup?.deviceCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备组类型">
              <dict-tag :options="device_type" :value="currentMountGroup?.deviceType" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider content-position="left">新建挂载对象</el-divider>
      <el-form ref="mountFormRef" :model="mountForm" :rules="rules" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="是否设备组" prop="isDeviceGroup">
              <el-radio-group v-model="mountForm.isDeviceGroup" @change="handleMountDeviceGroupChange">
                <el-radio-button label="1">设备组</el-radio-button>
                <el-radio-button label="0">设备</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="mountForm.isDeviceGroup === '1' ? '设备组ID' : '设备ID'" prop="deviceId">
              <el-input v-model="mountForm.deviceId" :placeholder="mountForm.isDeviceGroup === '1' ? '请输入设备组ID' : '请输入设备ID'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="mountForm.isDeviceGroup === '1' ? '设备组名称' : '设备名称'" prop="deviceName">
              <el-input v-model="mountForm.deviceName" :placeholder="mountForm.isDeviceGroup === '1' ? '请输入设备组名称' : '请输入设备名称'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="mountForm.isDeviceGroup === '1' ? '设备组编号' : '设备编号'" prop="deviceCode">
              <el-input v-model="mountForm.deviceCode" :placeholder="mountForm.isDeviceGroup === '1' ? '请输入设备组编号' : '请输入设备编号'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="mountForm.isDeviceGroup === '1' ? '设备组类型' : '设备类型'" prop="deviceType">
              <el-select v-model="mountForm.deviceType" placeholder="请选择设备类型" @change="handleMountDeviceTypeChange">
                <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="规格型号">
              <el-input v-model="mountForm.specificationModel" />
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="生产厂家">
              <el-input v-model="mountForm.manufacturer" />
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="出厂编号">
              <el-input v-model="mountForm.factoryNo" />
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="精度等级">
              <el-input v-model="mountForm.accuracyLevel" />
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="量程">
              <el-input v-model="mountForm.measureRange" />
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="通讯协议">
              <el-input v-model="mountForm.communicationProtocol" />
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="采集周期">
              <el-input v-model="mountForm.collectionCycle" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="mountForm.status" placeholder="请选择状态">
                <el-option v-for="item in deviceStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="上次检定日期">
              <el-date-picker v-model="mountForm.lastVerificationDate" type="date" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col v-if="mountForm.isDeviceGroup !== '1'" :span="12">
            <el-form-item label="责任人">
              <el-input v-model="mountForm.responsiblePerson" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="mountForm.remark" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="计量参数">
              <div class="unit-table-wrap">
                <el-table border :data="mountForm.units || []">
                  <el-table-column label="参数名称" min-width="220">
                    <template #default="scope">
                      <el-select
                        v-model="scope.row.parameterName"
                        placeholder="请选择能源指标"
                        filterable
                        clearable
                        @change="handleUnitParameterChange(scope.row)"
                      >
                        <el-option v-for="item in mountStandardUnitOptions" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="原始单位" min-width="140">
                    <template #default="scope">
                      <el-input v-model="scope.row.measuringUnit" placeholder="如 kWh、m3" />
                    </template>
                  </el-table-column>
                  <el-table-column label="标准单位" width="120">
                    <template #default="scope">
                      {{ getMetricUnit(scope.row.parameterName) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="换算倍率" width="170">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.conversionFactor" :min="0" :precision="6" controls-position="right" />
                    </template>
                  </el-table-column>
                  <el-table-column label="数据占比(%)" width="170">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.dataRatio" :min="1" :precision="4" controls-position="right" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="80">
                    <template #default="scope">
                      <el-button link type="primary" icon="Delete" @click="removeMountUnitRow(scope.$index)" />
                    </template>
                  </el-table-column>
                </el-table>
                <el-button class="mt-2" type="primary" plain icon="Plus" @click="addMountUnitRow">新增计量参数 </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" icon="Plus" @click="submitMountChildren">新建并挂载</el-button>
              <el-button @click="resetMountForm">重 置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider content-position="left">已挂载</el-divider>
      <el-form label-width="100px">
        <el-form-item label="已挂载">
          <el-table border :data="currentMountGroup?.childDevices || []" empty-text="暂无挂载设备" max-height="320">
            <el-table-column label="ID" prop="deviceId" min-width="120" />
            <el-table-column label="名称" prop="deviceName" min-width="150" show-overflow-tooltip />
            <el-table-column label="编号" prop="deviceCode" min-width="130" />
            <el-table-column label="节点类型" width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.isDeviceGroup === '1'" type="warning">设备组</el-tag>
                <el-tag v-else type="success">设备</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="类型" align="center" width="100">
              <template #default="scope">
                <dict-tag :options="device_type" :value="scope.row.deviceType" />
              </template>
            </el-table-column>
            <el-table-column label="上次检定日期" prop="lastVerificationDate" align="center" width="120" />
            <el-table-column label="操作" width="80" align="center">
              <template #default="scope">
                <el-button link type="primary" icon="Delete" @click="handleUnmountChild(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="mountDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="pointDialog.visible" title="生成测控点" append-to-body width="620px">
      <el-form ref="pointFormRef" :model="pointForm" :rules="pointRules" label-width="120px">
        <el-form-item label="测控点编号" prop="pointCode">
          <el-input v-model="pointForm.pointCode" />
        </el-form-item>
        <el-form-item label="测控点名称" prop="pointName">
          <el-input v-model="pointForm.pointName" />
        </el-form-item>
        <el-form-item label="所属计量器具">
          <el-input v-model="pointForm.measuringDeviceName" disabled />
        </el-form-item>
        <el-form-item label="所属计量器具ID" prop="measuringDeviceId" class="hidden-form-item">
          <el-input v-model="pointForm.measuringDeviceId" />
        </el-form-item>
        <el-form-item label="参数名称" prop="parameterName">
          <el-select v-model="pointForm.parameterName" placeholder="请选择能源指标" filterable @change="handlePointParameterChange">
            <el-option v-for="item in pointMetricOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="标准单位" prop="standardUnit">
          <el-input v-model="pointForm.standardUnit" disabled />
        </el-form-item>
        <el-form-item label="换算倍率" prop="conversionFactor">
          <el-input-number v-model="pointForm.conversionFactor" :min="0" :precision="6" controls-position="right" />
        </el-form-item>
        <el-form-item label="数据占比(%)" prop="dataRatio">
          <el-input-number v-model="pointForm.dataRatio" :min="1" :precision="4" controls-position="right" />
        </el-form-item>
        <el-form-item label="原始单位" prop="originalUnit">
          <el-input v-model="pointForm.originalUnit" />
        </el-form-item>
        <el-form-item label="采集周期" prop="collectionCycle">
          <el-input v-model="pointForm.collectionCycle" />
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-input v-model="pointForm.dataType" />
        </el-form-item>
        <el-form-item label="寄存器地址/Tag" prop="registerAddress">
          <el-input v-model="pointForm.registerAddress" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="pointForm.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPointForm">确 定</el-button>
          <el-button @click="pointDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MeasuringDevice" lang="ts">
import {
  addMeasuringDevice,
  delMeasuringDevice,
  getMeasuringDevice,
  listMeasuringDevice,
  unmountMeasuringDeviceChild,
  updateMeasuringDevice
} from '@/api/ems/measuringDevice';
import { MeasuringDeviceForm, MeasuringDeviceQuery, MeasuringDeviceUnit, MeasuringDeviceVO } from '@/api/ems/measuringDevice/types';
import { listFloorInfo } from '@/api/system/floor';
import { FloorInfoVO } from '@/api/system/floor/types';
import { listEnergyMetric } from '@/api/ems/energyMetric';
import { EnergyMetricVO } from '@/api/ems/energyMetric/types';
import { addMeasurementControlPoint } from '@/api/ems/measurementControlPoint';
import { MeasurementControlPointForm } from '@/api/ems/measurementControlPoint/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { device_type } = toRefs<any>(proxy?.useDict('device_type'));

const deviceList = ref<MeasuringDeviceVO[]>([]);
const deviceTreeList = ref<MeasuringDeviceVO[]>([]);
const floorOptions = ref<any[]>([]);
const metricOptions = ref<EnergyMetricVO[]>([]);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const floorCascaderProps = { value: 'id', label: 'name', children: 'children', emitPath: false, checkStrictly: true };

const queryFormRef = ref<ElFormInstance>();
const deviceFormRef = ref<ElFormInstance>();
const mountFormRef = ref<ElFormInstance>();
const pointFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({ visible: false, title: '' });
const mountDialog = reactive<DialogOption>({ visible: false, title: '' });
const pointDialog = reactive<DialogOption>({ visible: false, title: '' });
const currentMountGroup = ref<MeasuringDeviceVO>();
const pointForm = ref<MeasurementControlPointForm & { measuringDeviceName?: string }>({});
const deviceStatusOptions = [
  { label: '离线', value: '0' },
  { label: '在线', value: '1' },
  { label: '故障', value: '2' }
];
const pointRules = {
  pointCode: [{ required: true, message: '测控点编号不能为空', trigger: 'blur' }],
  pointName: [{ required: true, message: '测控点名称不能为空', trigger: 'blur' }],
  measuringDeviceId: [{ required: true, message: '所属计量器具不能为空', trigger: 'blur' }],
  parameterName: [{ required: true, message: '参数名称不能为空', trigger: 'change' }]
};

const initFormData: MeasuringDeviceForm = {
  id: undefined,
  deviceId: '',
  deviceName: '',
  deviceCode: '',
  installPosition: undefined,
  deviceType: undefined,
  isDeviceGroup: '0',
  parentDeviceGroupId: undefined,
  units: [],
  specificationModel: '',
  manufacturer: '',
  factoryNo: '',
  accuracyLevel: '',
  measureRange: '',
  communicationProtocol: '',
  communicationAddress: '',
  collectionCycle: '',
  status: '',
  lastVerificationDate: '',
  responsibleDept: '',
  responsiblePerson: '',
  remark: ''
};

const data = reactive<PageData<MeasuringDeviceForm, MeasuringDeviceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: '',
    deviceCode: '',
    deviceId: '',
    deviceType: undefined,
    installPosition: undefined
  },
  rules: {
    deviceId: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    deviceCode: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
    deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const mountForm = ref<MeasuringDeviceForm>({ ...initFormData, isDeviceGroup: '0', units: [] });

const formatDeviceStatus = (value?: string | number) => {
  return deviceStatusOptions.find((item) => item.value === String(value ?? ''))?.label || '-';
};

const statusTagType = (value?: string | number) => {
  const status = String(value ?? '');
  if (status === '1') return 'success';
  if (status === '2') return 'danger';
  return 'info';
};

const standardUnitOptions = computed(() => {
  const type = form.value.deviceType === undefined || form.value.deviceType === null ? '' : String(form.value.deviceType);
  return metricOptions.value
    .filter((item) => !type || String(item.type) === type)
    .map((item) => ({
      label: `${item.metricName || item.collectionField}${item.unit ? `(${item.unit})` : ''}`,
      value: item.collectionField || ''
    }))
    .filter((item) => item.value);
});
const mountStandardUnitOptions = computed(() => {
  const type = mountForm.value.deviceType === undefined || mountForm.value.deviceType === null ? '' : String(mountForm.value.deviceType);
  return metricOptions.value
    .filter((item) => !type || String(item.type) === type)
    .map((item) => ({
      label: `${item.metricName || item.collectionField}${item.unit ? `(${item.unit})` : ''}`,
      value: item.collectionField || ''
    }))
    .filter((item) => item.value);
});
const pointMetricOptions = computed(() => {
  const type =
    currentPointDevice.value?.deviceType === undefined || currentPointDevice.value?.deviceType === null
      ? ''
      : String(currentPointDevice.value.deviceType);
  return metricOptions.value
    .filter((item) => !type || String(item.type) === type)
    .map((item) => ({
      label: `${item.metricName || item.collectionField}${item.unit ? `(${item.unit})` : ''}`,
      value: item.collectionField || ''
    }))
    .filter((item) => item.value);
});

const getMetricByField = (field?: string) => metricOptions.value.find((item) => item.collectionField === field);

const getMetricUnit = (field?: string) => getMetricByField(field)?.unit || '';
const normalizeFloorTree = (rows: FloorInfoVO[]): any[] =>
  rows
    .filter((row) => row.isDevice !== '1' && row.isDeviceGroup !== '1')
    .map((row) => ({
      id: row.id,
      name: row.name,
      children: normalizeFloorTree((row.children || []).filter((child) => child.isDevice !== '1' && child.isDeviceGroup !== '1'))
    }));

const buildDeviceTree = (rows: MeasuringDeviceVO[]) => {
  const map = new Map<string, MeasuringDeviceVO>();
  const roots: MeasuringDeviceVO[] = [];
  rows.forEach((row) => {
    map.set(String(row.id), { ...row, children: [] });
  });
  map.forEach((row) => {
    const parentId = row.parentDeviceGroupId === undefined || row.parentDeviceGroupId === null ? '' : String(row.parentDeviceGroupId);
    const parent = parentId ? map.get(parentId) : undefined;
    if (parent) {
      parent.children = parent.children || [];
      parent.children.push(row);
    } else {
      roots.push(row);
    }
  });
  const sortRows = (items: MeasuringDeviceVO[]) => {
    items.sort((left, right) => {
      if (left.isDeviceGroup !== right.isDeviceGroup) return left.isDeviceGroup === '1' ? -1 : 1;
      return String(left.deviceName || left.deviceCode || left.deviceId || '').localeCompare(
        String(right.deviceName || right.deviceCode || right.deviceId || ''),
        'zh-CN'
      );
    });
    items.forEach((item) => {
      if (item.children?.length) sortRows(item.children);
      else delete item.children;
    });
  };
  sortRows(roots);
  return roots;
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listMeasuringDevice({ ...queryParams.value, pageNum: 1, pageSize: 10000 });
    deviceList.value = res.rows || [];
    deviceTreeList.value = buildDeviceTree(deviceList.value);
    total.value = deviceList.value.length;
  } finally {
    loading.value = false;
  }
};

const loadOptions = async () => {
  const [floorRes, metricRes] = await Promise.all([listFloorInfo(), listEnergyMetric({ pageNum: 1, pageSize: 1000 })]);
  floorOptions.value = normalizeFloorTree((floorRes as any).rows || []);
  metricOptions.value = (metricRes as any).rows || [];
};

const reset = () => {
  form.value = { ...initFormData, isDeviceGroup: '0', parentDeviceGroupId: undefined, units: [], childDevices: [] };
  deviceFormRef.value?.resetFields();
};

const handleDeviceTypeChange = () => {
  form.value.units = [];
};

const handleMountDeviceTypeChange = () => {
  mountForm.value.units = [];
};

const clearDeviceOnlyFields = () => {
  form.value.installPosition = undefined;
  form.value.parentDeviceGroupId = undefined;
  form.value.specificationModel = '';
  form.value.manufacturer = '';
  form.value.factoryNo = '';
  form.value.accuracyLevel = '';
  form.value.measureRange = '';
  form.value.communicationProtocol = '';
  form.value.communicationAddress = '';
  form.value.collectionCycle = '';
  form.value.lastVerificationDate = '';
  form.value.responsibleDept = '';
  form.value.responsiblePerson = '';
};

const clearMountDeviceOnlyFields = () => {
  mountForm.value.installPosition = undefined;
  mountForm.value.specificationModel = '';
  mountForm.value.manufacturer = '';
  mountForm.value.factoryNo = '';
  mountForm.value.accuracyLevel = '';
  mountForm.value.measureRange = '';
  mountForm.value.communicationProtocol = '';
  mountForm.value.communicationAddress = '';
  mountForm.value.collectionCycle = '';
  mountForm.value.lastVerificationDate = '';
  mountForm.value.responsibleDept = '';
  mountForm.value.responsiblePerson = '';
};

const handleDeviceGroupChange = () => {
  if (form.value.isDeviceGroup === '1') {
    clearDeviceOnlyFields();
  }
};

const handleMountDeviceGroupChange = () => {
  if (mountForm.value.isDeviceGroup === '1') {
    clearMountDeviceOnlyFields();
  }
};

const addUnitRow = () => {
  if (!form.value.units) {
    form.value.units = [];
  }
  form.value.units.push({
    measuringUnit: '',
    parameterName: '',
    standardUnit: '',
    conversionFactor: 1,
    dataRatio: 100
  } as MeasuringDeviceUnit);
};

const removeUnitRow = (index: number) => {
  form.value.units?.splice(index, 1);
};

const addMountUnitRow = () => {
  if (!mountForm.value.units) {
    mountForm.value.units = [];
  }
  mountForm.value.units.push({
    measuringUnit: '',
    parameterName: '',
    standardUnit: '',
    conversionFactor: 1,
    dataRatio: 100
  } as MeasuringDeviceUnit);
};

const removeMountUnitRow = (index: number) => {
  mountForm.value.units?.splice(index, 1);
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: MeasuringDeviceVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  addUnitRow();
  dialog.visible = true;
  dialog.title = '新增计量器具';
};

const handleUpdate = async (row?: MeasuringDeviceVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getMeasuringDevice(id);
  form.value = { ...res.data, units: res.data.units || [] };
  dialog.visible = true;
  dialog.title = '修改计量器具';
};

const handleMountChildren = (row: MeasuringDeviceVO) => {
  currentMountGroup.value = row;
  resetMountForm();
  mountDialog.visible = true;
};

const refreshMountGroup = async () => {
  await getList();
  if (!currentMountGroup.value?.id) return;
  currentMountGroup.value = deviceList.value.find((item) => String(item.id) === String(currentMountGroup.value?.id));
};

const submitMountChildren = async () => {
  if (!currentMountGroup.value?.id) return;
  mountFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    if (mountForm.value.isDeviceGroup === '1') {
      clearMountDeviceOnlyFields();
    }
    const payload = {
      ...mountForm.value,
      parentDeviceGroupId: currentMountGroup.value?.id
    };
    await addMeasuringDevice(payload);
    proxy?.$modal.msgSuccess('新建并挂载成功');
    resetMountForm();
    await loadOptions();
    await refreshMountGroup();
  });
};

const resetMountForm = () => {
  mountForm.value = {
    ...initFormData,
    isDeviceGroup: '0',
    parentDeviceGroupId: currentMountGroup.value?.id,
    units: []
  };
  addMountUnitRow();
  mountFormRef.value?.clearValidate();
};

const handleUnmountChild = async (row: MeasuringDeviceVO) => {
  if (!currentMountGroup.value?.id || !row.id) return;
  await unmountMeasuringDeviceChild({ parentDeviceGroupId: currentMountGroup.value.id, childId: row.id });
  proxy?.$modal.msgSuccess('移除成功');
  await refreshMountGroup();
};

const handleUnitParameterChange = (row: MeasuringDeviceUnit & { parameterName?: string }) => {
  row.standardUnit = row.parameterName || '';
};

const handlePointParameterChange = (value?: string) => {
  const metric = getMetricByField(value);
  pointForm.value.standardUnit = metric?.unit || '';
  const matchedUnit = currentPointDevice.value?.units?.find((item: any) => (item.parameterName || item.standardUnit) === value);
  pointForm.value.originalUnit = matchedUnit?.measuringUnit || pointForm.value.originalUnit || '';
  pointForm.value.conversionFactor = matchedUnit?.conversionFactor ?? pointForm.value.conversionFactor ?? 1;
  pointForm.value.dataRatio = matchedUnit?.dataRatio ?? pointForm.value.dataRatio ?? 100;
};

const currentPointDevice = ref<MeasuringDeviceVO>();

const handleGeneratePoint = (row: MeasuringDeviceVO) => {
  currentPointDevice.value = row;
  const firstUnit = row.units?.[0] as any;
  pointForm.value = {
    pointCode: row.deviceCode ? `${row.deviceCode}_${firstUnit?.standardUnit || 'point'}` : '',
    pointName: firstUnit?.standardUnitName || row.deviceName || '',
    measuringDeviceId: row.id,
    measuringDeviceName: row.deviceName,
    parameterName: firstUnit?.standardUnit || '',
    standardUnit: firstUnit?.standardUnit ? getMetricUnit(firstUnit.standardUnit) : '',
    conversionFactor: firstUnit?.conversionFactor ?? 1,
    dataRatio: firstUnit?.dataRatio ?? 100,
    originalUnit: firstUnit?.measuringUnit || '',
    collectionCycle: row.collectionCycle || '',
    status: row.status || ''
  };
  pointDialog.visible = true;
};

const submitPointForm = () => {
  pointFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    const { measuringDeviceName, ...payload } = pointForm.value;
    await addMeasurementControlPoint(payload);
    proxy?.$modal.msgSuccess('生成成功');
    pointDialog.visible = false;
  });
};

const submitForm = () => {
  deviceFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    if (form.value.id && form.value.parentDeviceGroupId && String(form.value.id) === String(form.value.parentDeviceGroupId)) {
      proxy?.$modal.msgError('所属设备组不能选择自己');
      return;
    }
    if (form.value.isDeviceGroup === '1') {
      clearDeviceOnlyFields();
    }
    if (form.value.id) {
      await updateMeasuringDevice(form.value);
    } else {
      await addMeasuringDevice(form.value);
    }
    proxy?.$modal.msgSuccess('操作成功');
    dialog.visible = false;
    await loadOptions();
    await getList();
  });
};

const handleDelete = async (row?: MeasuringDeviceVO) => {
  const deleteIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除计量器具编号为"' + deleteIds + '"的数据项？');
  await delMeasuringDevice(deleteIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const cancel = () => {
  dialog.visible = false;
  reset();
};

onMounted(async () => {
  await loadOptions();
  await getList();
});
</script>

<style scoped>
.unit-table-wrap {
  width: 100%;
}

.bound-rule-table {
  width: 100%;
}

.hidden-form-item {
  display: none;
}
</style>
