<template>
  <div class="h-full flex flex-col p-2">
    <pageheader></pageheader>
    <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" label-width="70px" @submit.prevent="handleQuery" :model="queryParams" :inline="true">
            <!-- <el-form-item label="设备状态" prop="eleStatus">
              <el-select v-model="queryParams.eleStatus">
                <el-option v-for="(item, index) in com_waterdevice_on_status" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="分合状态" prop="status">
              <el-select v-model="queryParams.status">
                <el-option v-for="(item, index) in com_water_readrecord_status" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input maxlength="25" v-model="queryParams.deviceCode" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="房屋" prop="houseName">
              <el-input maxlength="20" clearable v-model="queryParams.houseName" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card class="flex-1" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8 flex-items-center">
          <el-col :span="1.5">
            <div style="font-size: 0.8rem">水表列表</div>
          </el-col>
          <right-toolbar :show-add="false" :show-edit="false" :show-delete="false">
            <template #dropdown>
              <el-dropdown-item @click="handleMarkqrcode" v-if="checkPermi(['equipment:addqrcode:waterdevice'])">
                <span>批量生成条形码</span>
              </el-dropdown-item>
              <el-dropdown-item @click="handleMarkQrcodeZip">
                <span>批量下载条形码</span>
              </el-dropdown-item>
              <!-- <el-dropdown-item v-has-permi="['equipment:updatehardware:waterdevice']">
                <div @click="handleMarkUpload">批量更新固件</div>
              </el-dropdown-item> -->
            </template>
          </right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="waterDeviceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备编码" width="250" align="center" prop="deviceCode" />
        <el-table-column label="设备状态" width="100" align="center" prop="eleStatus">
          <template #default="scope">
            <!-- 1 离线 0在线 -->
            <dict-tag v-if="scope.row.waterRecord" :options="com_waterdevice_on_status" :value="Number(scope.row.status)"></dict-tag>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column label="分合状态" width="100" align="center">
          <template #default="scope">
            <dict-tag v-if="scope.row.status !== null" :options="com_water_readrecord_status" :value="scope.row.waterRecord.status"></dict-tag>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column label="房屋" align="center" prop="houseName" />
        <el-table-column label="余额" width="120" align="center" prop="deviceCode">
          <template #default="scope">
            <span v-if="scope.row.waterRecord">{{ scope.row.waterRecord.balance }}</span>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column label="条码" width="250" align="center">
          <template #default="scope">
            <el-image
              v-if="scope.row.url && scope.row.url.includes('http')"
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
              style="width: 100%; height: 100%; border-radius: 4px"
              fit="cover"
              preview-teleported
            >
              <template #toolbar>
                <el-icon @click="download(scope.row.url)"><Download /></el-icon>
              </template>
            </el-image>
            <span v-else>暂未生成</span>
          </template>
        </el-table-column>
        <el-table-column label="抄表时间" align="center">
          <template #default="scope">
            <span>{{ scope.row.waterRecord ? scope.row.waterRecord.readTime : '---' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column width="150" label="启停" align="center" prop="deleted" v-has-permi="['equipment:isUse:waterdevice']">
          <template #default="scope">
            <el-switch
              @change="(val: string) => handleChangeWater(val, scope.row)"
              v-model="scope.row.deleted"
              active-text="启用"
              inactive-text="停止"
              active-value="0"
              inactive-value="1"
            ></el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" min-width="150" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="actions">
              <el-button link type="primary" @click="handleRecode(scope.row)" v-has-permi="['equipment:view:waterdevice']">充值记录</el-button>
              <el-button
                link
                type="primary"
                :loading="loadingQRCode.includes(scope.row.id)"
                @click="handleQrCode(scope.row)"
                v-has-permi="['equipment:addqrcode:waterdevice']"
                >生成条码</el-button
              >
              <el-button link type="primary" @click="handleOpenDialog('usedWater', scope.row)" v-has-permi="['equipment:useWater:waterdevice']"
                >用水量</el-button
              >
              <el-button link type="primary" @click="handleOpenDialog('Upload', scope.row)" v-has-permi="['equipment:updatehardware:waterdevice']"
                >更新固件</el-button
              >
              <!-- <el-button link type="primary" @click="handleUpdate(scope.row.deviceCode)">最新抄表记录</el-button> -->

              <el-button
                v-if="!scope.row.houseName"
                link
                type="primary"
                @click="handleOpenDialog('UpdateHouse', scope.row)"
                v-has-permi="['equipment:edithouse:waterdevice']"
                >绑定房屋</el-button
              >
              <el-button v-else link type="primary" @click="handleUnbind(scope.row)" v-has-permi="['equipment:edithouse:waterdevice']"
                >解绑房屋</el-button
              >

              <!-- <el-dropdown style="vertical-align: text-top">
                  <el-button link type="primary">
                    <div>
                      更多<el-icon><arrow-down /></el-icon>
                    </div>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <div @click="handleOpenDialog('usedWater', scope.row)" v-has-permi="['equipment:useWater:waterdevice']">用水量</div>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <div @click="handleOpenDialog('Upload', scope.row)" v-has-permi="['equipment:updatehardware:waterdevice']">更新固件</div>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <div @click="handleOpenDialog('UpdateHouse', scope.row)" v-has-permi="['equipment:edithouse:waterdevice']">修改</div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown> -->
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :pageSizes="[10, 30, 50, 100]"
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改水 设备对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <!-- water -->
      <el-form v-if="dialogType === 'usedWater'" :rules="rules" ref="UsedWaterformRef" :model="UsedWaterform" label-width="100px">
        <el-form-item label="设备编号" prop="deviceCode"> {{ UsedWaterform.deviceCode }} </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="UsedWaterform.startTime"
            type="datetime"
            @update:model-value="handleStarTime"
            placeholder="开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="UsedWaterform.endTime"
            type="datetime"
            @update:model-value="handleEndTime"
            placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">搜索</el-button>
        </el-form-item>
      </el-form>
      <!-- upload file -->
      <el-form v-else-if="dialogType === 'Upload'" ref="UploadFileformRef" :model="UploadFileform" :rules="UploadFileformRules" label-width="140px">
        <el-form-item label="LEN_A" prop="lenA">
          <el-input maxlength="40" v-model="UploadFileform.lenA"></el-input>
        </el-form-item>
        <el-form-item label="CRC32_HEX_A" prop="crcA">
          <el-input maxlength="40" v-model="UploadFileform.crcA"></el-input>
        </el-form-item>
        <el-form-item label="上传 A槽更新 文件" prop="urlA">
          <el-upload
            ref="uploadARef"
            accept=".bin"
            :action="uploadAUrl"
            name="file"
            :headers="headerToken()"
            :limit="1"
            :show-file-list="true"
            class="upload-demo"
            :on-exceed="handleExceedA"
            :on-success="handleAvatarSuccessA"
            :before-upload="beforeAvatarUpload"
          >
            <div class="uploadFileBox flex flex-items-center">
              <el-icon>
                <upload></upload>
              </el-icon>
              <div style="margin-left: 10px">上传A文件</div>
            </div>
            <template #tip>
              <div class="el-upload__tip">文件格式必须是 bin 格式</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="LEN_B" prop="lenB">
          <el-input maxlength="40" v-model="UploadFileform.lenB"></el-input>
        </el-form-item>
        <el-form-item label="CRC32_HEX_B" prop="crcB">
          <el-input maxlength="40" v-model="UploadFileform.crcB"></el-input>
        </el-form-item>
        <el-form-item label="上传 B槽更新 文件" prop="urlB">
          <el-upload
            ref="uploadBRef"
            accept=".bin"
            :action="uploadBUrl"
            name="file"
            :limit="1"
            :headers="headerToken()"
            :show-file-list="true"
            class="upload-demo"
            :on-exceed="handleExceedB"
            :on-success="handleAvatarSuccessB"
            :before-upload="beforeAvatarUpload"
          >
            <div class="uploadFileBox flex flex-items-center">
              <el-icon>
                <upload></upload>
              </el-icon>
              <div style="margin-left: 10px">上传B文件</div>
            </div>
            <template #tip>
              <div class="el-upload__tip">文件格式必须是 bin 格式</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="unSubmit">取消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">更新到设备</el-button>
        </el-form-item>
      </el-form>
      <!-- house -->
      <el-form v-else-if="dialogType === 'UpdateHouse'" ref="EditHouseformRef" :model="EditHouseform" :rules="EditHouseformRules" label-width="100px">
        <el-form-item label="更新户号" prop="houseId">
          <el-cascader v-model="userHousepath" :options="treedata" @change="handleChange" />
        </el-form-item>
        <el-form-item>
          <el-button @click="unSubmit">取消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">更新到设备</el-button>
        </el-form-item>
      </el-form>

      <div v-show="!usedWaterInfo" class="usedWaterbox">
        <div class="useditem">查询用水量开始时间</div>
        <div class="useditem value">{{ UsedWaterInfo.startTime }}</div>
        <div class="useditem">查询用水量结束时间</div>
        <div class="useditem value">{{ UsedWaterInfo.endTime }}</div>
        <div class="useditem">用水量</div>
        <div class="useditem value">{{ UsedWaterInfo.count }}</div>
      </div>

      <el-form v-if="dialogType === 'deviceLastRecord'" ref="deviceLastRecordformRef" :model="EditHouseform" label-width="100px">
        <el-form-item label="设备编号" prop="deviceCode"> {{ deviceLastRecordform.deviceCode }} </el-form-item>
        <el-form-item label="读表时间" prop="readTime"> {{ deviceLastRecordform.readTime }} </el-form-item>
        <el-form-item label="阀门状态" prop="status">
          <DictTag :options="com_water_readrecord_status" :value="deviceLastRecordform.status"></DictTag>
        </el-form-item>
        <el-form-item label="余额" prop="balance"> {{ deviceLastRecordform.balance }} </el-form-item>
        <el-form-item label="用水量" prop="totalWater"> {{ deviceLastRecordform.totalWater }} </el-form-item>
        <el-form-item>
          <el-button @click="unSubmit">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="WaterDevice" lang="ts">
import 'element-plus/theme-chalk/display.css';
import {
  listWaterDevice,
  getWaterDeviceTimeRangeUsedWater,
  WaterDeviceMakerQrcode,
  updateWaterDevice,
  WaterDeviceUpdateBin,
  latestRecord,
  waterDeviceUnbind
} from '@/api/system/SdbWaterDevice';
import { WaterDeviceVO } from '@/api/system/SdbWaterDevice/type';
import { useHouseStore } from '@/store/modules/house';
import { useUserStore } from '@/store/modules/user';
import { Upload } from '@element-plus/icons-vue';
import { CascaderValue, UploadProps, UploadRawFile } from 'element-plus';
import { checkPermi } from '@/utils/permission';
import { exportImagesToZip } from '@/utils/exportZip';
import { genFileId } from 'element-plus';

const uploadAUrl = import.meta.env.VITE_APP_BASE_API + '/waterDevice/uploadA';
const uploadBUrl = import.meta.env.VITE_APP_BASE_API + '/waterDevice/uploadB';

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

const waterDeviceList = ref<WaterDeviceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<WaterDeviceVO[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    eleStatus: '',
    houseName: '',
    status: '',
    deviceCode: ''
  }
});

const { queryParams } = toRefs(data);

/** 查询水 设备列表 */
const getList = async (callback?: (vals: WaterDeviceVO[]) => void) => {
  loading.value = true;
  const res = await listWaterDevice(queryParams.value);
  waterDeviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  callback && callback(waterDeviceList.value);
};
// ! 用水量 =============================================================================
const usedWaterInfo = ref(true);
const UsedWaterformRef = ref(null);
const UsedWaterform = ref({
  deviceCode: '',
  startTime: '',
  endTime: ''
});
function handleStarTime(val: string) {
  if (!val) return;
  const current = new Date(val).getTime();
  if (UsedWaterform.value.endTime && UsedWaterform.value.startTime) {
    if (current > new Date(UsedWaterform.value.endTime).getTime()) {
      UsedWaterform.value.endTime = '';
      ElMessage.warning('开始时间不能大于结束时间');
    }
  }
}
function handleEndTime(val: string) {
  if (!val) return;
  const current = new Date(val).getTime();
  if (UsedWaterform.value.startTime && UsedWaterform.value.endTime) {
    if (current < new Date(UsedWaterform.value.startTime).getTime()) {
      UsedWaterform.value.startTime = '';
      ElMessage.warning('结束时间不能小于开始时间');
    }
  }
}

const UsedWaterInfo = ref({
  count: '',
  startTime: '',
  endTime: ''
});
const rules = {
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }]
};

// ! =======================================================================================

// ? 上传固件  ==============================================================================================
const UploadFileformRef = ref(null);
const uploadBRef = ref();
const uploadARef = ref();
const UploadFileform = ref({
  deviceCodes: [],
  urlA: '',
  lenA: '',
  crcA: '',
  urlB: '',
  crcB: '',
  lenB: ''
});
const UploadFileformRules = {
  urlA: [{ required: true, message: 'A更新文件不能为空', trigger: 'blur' }],
  urlB: [{ required: true, message: 'B更新文件不能为空', trigger: 'blur' }]
};
function headerToken() {
  const useStore = useUserStore();
  return {
    Authorization: 'Bearer ' + useStore.token
  };
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {
  // 1. 校验后缀
  if (!rawFile.name.endsWith('.bin')) {
    ElMessage.warning('请上传 .bin 后缀的文件');
    return false;
  }

  // 2. 校验文件类型（bin 文件类型）
  if (rawFile.type !== 'application/octet-stream' && rawFile.type !== '') {
    ElMessage.warning('文件类型不正确，请上传标准 bin 文件');
    return false;
  }

  // 3. 校验文件大小（不能空）
  if (rawFile.size === 0) {
    ElMessage.warning('上传 bin 文件不能为空');
    return false;
  }
  return true;
};
const handleAvatarSuccessA: UploadProps['onSuccess'] = (response: any) => {
  UploadFileform.value.urlA = response.data.url;
};
const handleAvatarSuccessB: UploadProps['onSuccess'] = (response: any) => {
  UploadFileform.value.urlB = response.data.url;
};
const handleExceedB: UploadProps['onExceed'] = (files) => {
  uploadBRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadBRef.value!.handleStart(file);
  uploadBRef.value!.submit();
};
const handleExceedA: UploadProps['onExceed'] = (files) => {
  uploadARef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadARef.value!.handleStart(file);
  uploadARef.value!.submit();
};

// ? 上传固件  ==============================================================================================

// * 编辑房屋  ==============================================================================================
// 编辑房屋
const EditHouseformRef = ref(null);
const EditHouseformRules = {};
const EditHouseform = ref({
  id: '',
  deviceCode: '',
  houseId: ''
});
// * 编辑房屋  ==============================================================================================
const deviceLastRecordformRef = ref(null);
const deviceLastRecordform = ref({
  id: '',
  deviceCode: '',
  balance: '',
  eleStatus: '',
  readTime: '',
  status: '',
  totalWater: '',
  type: ''
});

const imageRefs = ref([]);
/** 批量生成 条形码 */
function handleMarkqrcode() {
  if (ids.value.length > 0) {
    WaterDeviceMakerQrcode(ids.value).then(() => {
      ElMessage.success('批量生成成功');
      getList();
    });
  } else {
    ElMessage.warning('请选择设备');
  }
}

function handleMarkQrcodeZip() {
  if (ids.value.length > 0) {
    const selectedIds = new Set(ids.value.map((item) => item.id));
    const matchedList = waterDeviceList.value.filter((item) => {
      return selectedIds.has(item.id) && item.url;
    });
    produceQRzip(matchedList);
  } else {
    ElMessage.warning('请选择设备');
  }
}
function handleMarkUpload() {
  if (ids.value.length > 0) {
    reset();
    UploadFileform.value.deviceCodes = ids.value.map((item) => item.deviceCode).filter((item) => item);
    dialog.title = '固件上传';
    dialog.visible = true;
    dialogType.value = 'Upload';
  } else {
    ElMessage.warning('请选择设备');
  }
}

function produceQRzip(vals: WaterDeviceVO[]) {
  const arr = vals.map((item) => {
    return {
      name: item.deviceCode,
      url: item.url
    };
  });
  exportImagesToZip(arr);
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: WaterDeviceVO[]) => {
  ids.value = selection.map((item) => {
    return item;
  });
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const loadingQRCode = ref([]);
/** 生成二维码 */
const handleQrCode = (row: WaterDeviceVO) => {
  loadingQRCode.value.push(row.id);
  setTimeout(() => {
    // 1.电表 2.水表
    WaterDeviceMakerQrcode([
      {
        id: row.id,
        deviceCode: row.deviceCode
      }
    ])
      .then(() => {
        ElMessage.success('生成成功');
        getList();
      })
      .finally(() => {
        loadingQRCode.value = loadingQRCode.value.filter((item) => item !== row.id);
      });
  }, 1000);
};
// * house
const treedata = ref([]);
const houseStore = useHouseStore();
const userHousepath = ref<CascaderValue>([]);
function handleChange(val: CascaderValue) {
  userHousepath.value = val;
  EditHouseform.value.houseId = val[2];
}
// * house
const dialogType = ref<'usedWater' | 'Upload' | 'UpdateHouse' | 'deviceLastRecord'>('usedWater');
/** 用水量 更新固件 编辑房屋*/
const handleOpenDialog = (type: 'usedWater' | 'Upload' | 'UpdateHouse' | 'deviceLastRecord', row?: WaterDeviceVO) => {
  reset();
  if (type === 'usedWater') {
    UsedWaterform.value.deviceCode = row.deviceCode;
    UsedWaterform.value.startTime = '';
    UsedWaterform.value.endTime = '';
    usedWaterInfo.value = true;
    dialog.title = '用水量查询';
  } else if (type === 'Upload') {
    UploadFileform.value.deviceCodes = [row.deviceCode];
    dialog.title = '固件上传';
  } else if (type === 'UpdateHouse') {
    EditHouseform.value.id = row.id;
    EditHouseform.value.deviceCode = row.deviceCode;
    EditHouseform.value.houseId = '';
    dialog.title = '编辑户号';
    getTree();
  } else if (type === 'deviceLastRecord') {
    // 处理设备最后记录的逻辑
    dialog.title = '设备最新抄表记录';
  }
  dialog.visible = true;
  dialogType.value = type;
};

function getTree() {
  treedata.value = [];
  houseStore.getCurrentVilageTreeHouse().then((res) => {
    treedata.value = res;
    userHousepath.value = [];
  });
}

/** 水表 启停*/
const handleChangeWater = (val: string, row: WaterDeviceVO) => {};

function handleUpdate(id: string) {
  latestRecord(id).then((res) => {
    console.log('设备最新抄表记录', res);
    deviceLastRecordform.value = {
      id: '',
      deviceCode: '',
      balance: '',
      eleStatus: '',
      readTime: '',
      status: '',
      totalWater: '',
      type: ''
    };
    deviceLastRecordform.value = {
      ...res.data
    };
    handleOpenDialog('deviceLastRecord');
  });
}

// 解绑房屋
function handleUnbind(data: WaterDeviceVO) {
  // 提示
  proxy?.$modal.confirm('确认解绑房屋吗？').then(() => {
    waterDeviceUnbind(data.deviceCode)
      .then(() => {
        ElMessage.success('解绑成功');
      })
      .finally(() => {
        getList();
      });
  });
}

/** 提交按钮 */
const submitForm = () => {
  if (dialogType.value === 'usedWater') {
    if (UsedWaterform.value.startTime === '' || UsedWaterform.value.endTime === '') {
      ElMessage.warning('请选择时间');
      return;
    }
    UsedWaterformRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        await getWaterDeviceTimeRangeUsedWater(UsedWaterform.value)
          .then((res) => {
            UsedWaterInfo.value.endTime = res.data.endTime;
            UsedWaterInfo.value.startTime = res.data.startTime;
            UsedWaterInfo.value.count = res.data.count;
          })
          .finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('操作成功');
        usedWaterInfo.value = false;
      }
    });
  } else if (dialogType.value === 'UpdateHouse') {
    EditHouseformRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        await updateWaterDevice(EditHouseform.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('操作成功');
        getList();
        unSubmit();
      }
    });
  } else if (dialogType.value === 'Upload') {
    UploadFileformRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        await WaterDeviceUpdateBin(UploadFileform.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('操作成功');
        unSubmit();
      }
    });
  }
};
const unSubmit = () => {
  reset();
  dialog.visible = false;
  dialog.title = '';
};
/** 表单重置 */
const reset = () => {
  usedWaterInfo.value = true;
  UsedWaterform.value = {
    deviceCode: '',
    startTime: '',
    endTime: ''
  };
  UsedWaterInfo.value = {
    count: '',
    startTime: '',
    endTime: ''
  };
  EditHouseform.value = {
    id: '',
    deviceCode: '',
    houseId: ''
  };

  UploadFileform.value.deviceCodes = [];
  UploadFileform.value.urlA = '';
  UploadFileform.value.urlB = '';
  UploadFileform.value.lenA = '';
  UploadFileform.value.crcA = '';
  UploadFileform.value.lenB = '';
  UploadFileform.value.crcB = '';

  // 上传 清空
  UploadFileformRef.value?.resetFields();
  // 使用水量 清空
  EditHouseformRef.value?.resetFields();
  // 使用水量 清空
  UsedWaterformRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const router = useRouter();
/** 充值记录 */
const handleRecode = (row: WaterDeviceVO) => {
  // 1.电表 2.水表
  router.push({
    path: '/equipment/waterTopupRecord',
    query: {
      type: '2',
      id: row.id,
      houseName: row.houseName,
      deviceCode: row.deviceCode
    }
  });
};
onMounted(() => {
  getList();
});

const download = (url: string) => {
  if (!url) return;
  if (!url.includes('http')) return;
  // 创建一个隐藏的 a 标签，直接跳转下载
  const link = document.createElement('a');
  link.href = url;
  link.download = ''; // 自动获取文件名
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style lang="scss" scoped>
.actions {
  :deep(.el-button > span) {
    font-weight: 650;
  }
}

.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
.el-table {
  height: calc(100% - 80px);
  :deep(.waterDevice_online) {
    color: #3dd4a7;
    background: transparent;
    border: none;
  }
  :deep(.waterDevice_offline) {
    color: #ee1c25;
    background: transparent;
    border: none;
  }
}

.usedWaterbox {
  width: 100%;
  border: 1px solid #eef0ff;
  .useditem {
    height: 42px;
    line-height: 42px;
    background-color: rgba(26, 117, 255, 0.1);
    color: rgba(16, 16, 16, 1);
    font-size: 14px;
    padding: 0 10px;

    &.value {
      background-color: #fff;
    }
  }
}
.uploadFileBox {
  width: 276px;
  height: 35px;
  line-height: 20px;
  border-radius: 4px 4px 4px 4px;
  background-color: rgba(255, 255, 255, 1);
  color: rgba(16, 16, 16, 1);
  border: 1px solid #ccc;
  padding-left: 20px;
  font-size: 14px;
}
</style>
