<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" :inline="true" :model="queryParams">
            <el-form-item label="设备编号" prop="deviceNo">
              <el-input v-model="queryParams.deviceNo" clearable placeholder="请输入设备编号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="用户id" prop="userId">
              <el-input v-model="queryParams.userId" clearable placeholder="请输入用户id" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" clearable placeholder="请输入设备名称" @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="设备图片" prop="deviceImg">-->
            <!--              <el-input v-model="queryParams.deviceImg" clearable placeholder="请输入设备图片" @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="设备型号" prop="deviceEm">
              <el-input v-model="queryParams.deviceEm" clearable placeholder="请输入设备型号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备序列号" prop="deviceSn">
              <el-input v-model="queryParams.deviceSn" clearable placeholder="请输入设备序列号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="固件版本" prop="fwVer">
              <el-input v-model="queryParams.fwVer" clearable placeholder="请输入固件版本" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="mac地址" prop="macAddress">
              <el-input v-model="queryParams.macAddress" clearable placeholder="请输入mac地址" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['app:device:add']" icon="Plus" plain type="primary" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['app:device:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['app:device:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['app:device:qrcode']" :disabled="multiple" icon="Picture" plain type="primary" @click="handleGenerateQrCode()"
              >生成二维码</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['app:device:export']" icon="Download" plain type="warning" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="deviceList" border @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" label="设备编号" prop="deviceNo" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.deviceNo || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户id" prop="userId" width="100" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.userId || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备名称" prop="deviceName" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.deviceName || '-' }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column align="center" label="设备图片" prop="deviceImg" />-->
        <el-table-column align="center" label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getDeviceStatusType(scope.row.status)">
              {{ getDeviceStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="工作状态" prop="workStatus" width="100">
          <template #default="scope">
            <el-tag :type="getWorkStatusType(scope.row.workStatus)">
              {{ getWorkStatusLabel(scope.row.workStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="电量" prop="powerLevel" width="160">
          <template #default="scope">
            <div v-if="scope.row.powerLevel !== undefined && scope.row.powerLevel !== null && scope.row.powerLevel !== ''" class="power-level">
              <svg class="power-level__icon" :class="getPowerLevelClass(scope.row.powerLevel)" viewBox="0 0 48 24" width="48" height="24">
                <!-- 电池外壳 -->
                <rect x="0" y="2" width="42" height="20" rx="4" ry="4" fill="none" stroke="currentColor" stroke-width="2" />
                <!-- 电池正极 -->
                <rect x="42" y="8" width="4" height="8" rx="2" ry="2" fill="currentColor" />
                <!-- 电量填充 -->
                <rect
                  x="3"
                  y="5"
                  :width="Math.max((36 * formatPowerLevel(scope.row.powerLevel)) / 100, 0)"
                  height="14"
                  rx="2"
                  ry="2"
                  fill="currentColor"
                />
              </svg>
              <span class="power-level__text">{{ formatPowerLevel(scope.row.powerLevel) }}%</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="电量更新时间" prop="powerLevelUpdatatime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.powerLevelUpdatatime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column align="center" label="WiFi名称" prop="wifiName" min-width="120" show-overflow-tooltip>-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ scope.row.wifiName || '-' }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column align="center" label="WiFi密码" prop="wifiPassword" width="140">-->
        <!--          <template #default="scope">-->
        <!--            <div v-if="scope.row.wifiPassword" class="wifi-password">-->
        <!--              <span class="wifi-password__text">{{ showPassword[scope.row.id] ? scope.row.wifiPassword : maskedPassword }}</span>-->
        <!--              <el-button-->
        <!--                :icon="showPassword[scope.row.id] ? 'View' : 'Hide'"-->
        <!--                link-->
        <!--                type="primary"-->
        <!--                size="small"-->
        <!--                @click="togglePassword(scope.row.id)"-->
        <!--              />-->
        <!--            </div>-->
        <!--            <span v-else>-</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column align="center" label="设备型号" prop="deviceEm" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.deviceEm || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备序列号" prop="deviceSn" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.deviceSn || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="固件版本" prop="fwVer" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.fwVer" size="small" effect="plain" type="info">{{ scope.row.fwVer }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="MAC地址" prop="macAddress" width="160">
          <template #default="scope">
            <span v-if="scope.row.macAddress" class="mac-address">{{ formatMacAddress(scope.row.macAddress) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="二维码" prop="qrcode" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.qrcode"
              :src="scope.row.qrcode"
              :preview-src-list="[scope.row.qrcode]"
              fit="contain"
              style="width: 60px; height: 60px; border-radius: 4px; cursor: pointer"
              :preview-teleported="true"
            >
              <template #error>
                <span class="text-gray-400 text-xs">加载失败</span>
              </template>
            </el-image>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['app:device:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="生成二维码" placement="top">
              <el-button
                v-hasPermi="['app:device:qrcode']"
                icon="PictureFilled"
                link
                type="primary"
                @click="handleGenerateQrCode(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['app:device:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备信息
对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="500px">
      <el-form ref="deviceFormRef" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="设备编号" prop="deviceNo">-->
        <!--          <el-input v-model="form.deviceNo" placeholder="请输入设备编号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="用户id" prop="userId">-->
        <!--          <el-input v-model="form.userId" placeholder="请输入用户id" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="设备名称" prop="deviceName">-->
        <!--          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="设备图片" prop="deviceImg">-->
        <!--          <el-input v-model="form.deviceImg" placeholder="请输入设备图片" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="电量" prop="powerLevel">-->
        <!--          <el-input v-model="form.powerLevel" placeholder="请输入电量" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="电量更新时间" prop="powerLevelUpdatatime">-->
        <!--          <el-date-picker-->
        <!--            v-model="form.powerLevelUpdatatime"-->
        <!--            clearable-->
        <!--            placeholder="请选择电量更新时间"-->
        <!--            type="datetime"-->
        <!--            value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--          >-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="WiFi名称" prop="wifiName">-->
        <!--          <el-input v-model="form.wifiName" placeholder="请输入WiFi名称" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="WiFi密码" prop="wifiPassword">-->
        <!--          <el-input v-model="form.wifiPassword" placeholder="请输入WiFi密码" />-->
        <!--        </el-form-item>-->
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceEm">
          <el-input v-model="form.deviceEm" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="设备序列号" prop="deviceSn">
          <el-input v-model="form.deviceSn" placeholder="请输入设备序列号" />
        </el-form-item>
        <el-form-item label="MAC地址" prop="macAddress">
          <el-input v-model="form.macAddress" placeholder="请输入MAC地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="Device" setup>
import { listDevice, getDevice, delDevice, addDevice, updateDevice, generateDeviceQrCode } from '@/api/app/device';
import { DeviceVO, DeviceQuery, DeviceForm } from '@/api/app/device/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const deviceList = ref<DeviceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const deviceStatusMap: Record<string, { label: string; type: 'success' | 'info' | 'warning' | 'danger' }> = {
  '0': { label: '离线', type: 'info' },
  '1': { label: '工作中', type: 'success' },
  '2': { label: '待机', type: 'warning' },
  '3': { label: '故障', type: 'danger' }
};

const getDeviceStatusLabel = (status: string | number | undefined) => {
  if (status === undefined || status === null || status === '') {
    return '-';
  }
  return deviceStatusMap[String(status)]?.label ?? String(status);
};

const getDeviceStatusType = (status: string | number | undefined) => {
  return deviceStatusMap[String(status)]?.type ?? 'info';
};

const workStatusMap: Record<string, { label: string; type: 'success' | 'info' | 'warning' | 'danger' }> = {
  '0': { label: '空闲', type: 'info' },
  '1': { label: '工作中', type: 'success' },
  '2': { label: '未绑定用户', type: 'warning' }
};

const getWorkStatusLabel = (workStatus: string | number | undefined) => {
  if (workStatus === undefined || workStatus === null || workStatus === '') {
    return '-';
  }
  return workStatusMap[String(workStatus)]?.label ?? String(workStatus);
};

const getWorkStatusType = (workStatus: string | number | undefined) => {
  return workStatusMap[String(workStatus)]?.type ?? 'info';
};

const formatPowerLevel = (powerLevel: string | number | undefined) => {
  const value = Number(String(powerLevel ?? '').replace('%', ''));
  if (Number.isNaN(value)) {
    return 0;
  }
  return Math.min(Math.max(Math.round(value), 0), 100);
};

const getPowerLevelStatus = (powerLevel: string | number | undefined) => {
  const value = formatPowerLevel(powerLevel);
  if (value <= 20) {
    return 'exception';
  }
  if (value <= 50) {
    return 'warning';
  }
  return 'success';
};

const getPowerLevelClass = (powerLevel: string | number | undefined) => {
  const value = formatPowerLevel(powerLevel);
  if (value <= 20) {
    return 'power-level--low';
  }
  if (value <= 50) {
    return 'power-level--medium';
  }
  return 'power-level--high';
};

const formatMacAddress = (mac: string) => {
  const cleaned = mac.replace(/[^0-9a-fA-F]/g, '');
  const parts = cleaned.match(/.{1,2}/g);
  return parts ? parts.join(':').toLowerCase() : mac;
};

const showPassword = reactive<Record<string | number, boolean>>({});
const maskedPassword = '••••••••';

const togglePassword = (id: string | number) => {
  showPassword[id] = !showPassword[id];
};

const queryFormRef = ref<ElFormInstance>();
const deviceFormRef = ref<ElFormInstance>();

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

const initFormData: DeviceForm = {
  id: undefined,
  deviceNo: undefined,
  userId: undefined,
  deviceName: undefined,
  deviceImg: undefined,
  status: undefined,
  workStatus: undefined,
  powerLevel: undefined,
  powerLevelUpdatatime: undefined,
  wifiName: undefined,
  wifiPassword: undefined,
  deviceEm: undefined,
  deviceSn: undefined,
  fwVer: undefined,
  macAddress: undefined,
  expirationTime: undefined
};
const data = reactive<PageData<DeviceForm, DeviceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceNo: undefined,
    userId: undefined,
    deviceName: undefined,
    deviceImg: undefined,
    status: undefined,
    workStatus: undefined,
    powerLevel: undefined,
    powerLevelUpdatatime: undefined,
    wifiName: undefined,
    wifiPassword: undefined,
    deviceEm: undefined,
    deviceSn: undefined,
    fwVer: undefined,
    macAddress: undefined,
    expirationTime: undefined,
    orderByColumn: 'd.create_time',
    isAsc: 'desc',
    params: {}
  },
  rules: {
    // deviceNo: [{ required: true, message: '不能为空', trigger: 'blur' }],
    // userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }]
  }
});

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

/** 查询设备信息
列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDevice(queryParams.value);
  deviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceFormRef.value?.resetFields();
};

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加设备信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceVO) => {
  reset();
  const _id = row?.deviceNo || ids.value[0];
  const res = await getDevice(_id);
  Object.assign(form.value, res.data ?? res);
  dialog.visible = true;
  dialog.title = '修改设备信息';
};

/** 提交按钮 */
const submitForm = () => {
  deviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDevice(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDevice(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDevice(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 生成二维码按钮操作 */
const handleGenerateQrCode = async (row?: DeviceVO) => {
  const _ids = row?.deviceNo || ids.value;
  const targetIds = Array.isArray(_ids) ? _ids : [_ids];
  try {
    await proxy?.$modal.confirm(`是否确认为设备信息编号为【` + _ids + ` 】的设备生成二维码？`);
    // 逐个生成
    for (const id of targetIds) {
      await generateDeviceQrCode(id);
    }
    proxy?.$modal.msgSuccess('二维码生成成功');
    await getList();
  } catch {
    // 用户取消
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'app/device/export',
    {
      ...queryParams.value
    },
    `device_${new Date().getTime()}.xlsx`
  );
};

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

<style lang="scss" scoped>
.power-level {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.power-level__icon {
  flex-shrink: 0;
}

.power-level__text {
  font-weight: 600;
  font-variant-numeric: tabular-nums;
  min-width: 40px;
  text-align: left;
}

.power-level--high {
  color: #67c23a;
}

.power-level--medium {
  color: #e6a23c;
}

.power-level--low {
  color: #f56c6c;
}

.mac-address {
  font-family: 'Consolas', 'Menlo', 'Courier New', monospace;
  font-size: 13px;
  letter-spacing: 0.5px;
}

.wifi-password {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;
}

.wifi-password__text {
  font-family: 'Consolas', 'Menlo', 'Courier New', monospace;
  letter-spacing: 1px;
}
</style>
