import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import {
  getDeviceList,
  openDoor,
  setTemperature,
  setVolume,
  getDoorRecords,
  getDeviceReplenishers,
  bindDeviceReplenisher,
  unbindDeviceReplenisher,
  getDeviceDetailStatus,
  type DoorRecordItem
} from "@/api/device";
import { getEnabledShops } from "@/api/shop";
import { searchReplenishers } from "@/api/replenisher";
import { type Ref, computed, ref, toRaw, reactive, onMounted } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElSelect,
  ElOption,
  ElMessageBox
} from "element-plus";
import type { DeviceItem, DeviceSearchForm } from "./types";

export function useDevice(tableRef: Ref) {
  const form = reactive<DeviceSearchForm>({
    deviceId: "",
    shopId: "",
    status: "",
    name: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const shopOptions = ref([]);
  // 操作按钮的加载状态
  const operatingIds = ref<Set<number>>(new Set());
  
  // 开关门记录相关
  const dialogVisible = ref(false);
  const recordLoading = ref(false);
  const recordList = ref<DoorRecordItem[]>([]);
  const currentDeviceId = ref<string>("");
  const recordPagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "设备ID",
      prop: "deviceId",
      minWidth: 120
    },
    {
      label: "设备名称",
      prop: "name",
      minWidth: 120
    },
    {
      label: "所属门店",
      prop: "shopName",
      minWidth: 120
    },
    {
      label: "设备地址",
      prop: "address",
      minWidth: 150
    },
    {
      label: "温度(℃)",
      prop: "temperature",
      minWidth: 80
    },
    {
      label: "音量",
      prop: "volume",
      minWidth: 60
    },
    {
      label: "门状态",
      prop: "doorStatus",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <el-tag type={row.doorStatus === 1 ? "warning" : "success"}>
          {row.doorStatus === 1 ? "已开门" : "已关门"}
        </el-tag>
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <el-tag type={row.status === 1 ? "success" : "danger"}>
          {row.status === 1 ? "在线" : "离线"}
        </el-tag>
      )
    },
    {
      label: "最后在线时间",
      prop: "lastOnlineTime",
      minWidth: 160,
      formatter: ({ lastOnlineTime }) =>
        lastOnlineTime ? dayjs(lastOnlineTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  // 搜索
  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      // 只添加非空的搜索条件
      if (form.deviceId) searchParams.deviceId = form.deviceId;
      if (form.shopId) searchParams.shopId = form.shopId;
      if (form.status) searchParams.status = form.status;
      if (form.name) searchParams.name = form.name;
      
      const { data } = await getDeviceList(searchParams);
      dataList.value = data.list;
      pagination.total = Number(data.total);
    } catch (error) {
      console.error("获取设备列表失败:", error);
      dataList.value = [];
      pagination.total = 0;
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  // 重置表单
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    pagination.currentPage = 1;
    onSearch();
  };

  // 分页
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 远程开门
  async function handleOpenDoor(row: DeviceItem) {
    try {
      const deviceName = row.deviceName || row.storeName || `设备${row.deviceId}`;
      
      await ElMessageBox.confirm(`确认要远程开启 ${deviceName} 的门吗？`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });
  
      // 添加 loading 状态
      operatingIds.value.add(row.id);
        
      // 传递 doorIndex 参数，默认为 A 门
      const res = await openDoor(row.id, { doorIndex: "A" });
      if (res.code === 200 || res.code === 0) {
        message(`已发送开门指令到设备 ${deviceName}`, { type: "success" });
        // 开门成功后刷新列表，更新门状态
        await onSearch();
      } else {
        message(res.message || "开门失败", { type: "error" });
      }
    } catch (error) {
      // 用户取消或请求失败
      if (error !== "cancel") {
        console.error("开门失败:", error);
        message("操作失败", { type: "error" });
      }
    } finally {
      // 移除 loading 状态
      operatingIds.value.delete(row.id);
    }
  }

  // 设置温度
  const tempForm = reactive({ temperature: 0 });
  
  function handleSetTemperature(row: DeviceItem) {
    tempForm.temperature = row.temperature;
  
    addDialog({
      title: `设置 ${row.deviceName} 的温度`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <ElForm ref={ruleFormRef} model={tempForm} label-width="80px">
          <ElFormItem
            label="温度 (℃)"
            prop="temperature"
            rules={[
              { required: true, message: "请输入温度", trigger: "blur" },
              { 
                type: "number", 
                min: -30, 
                max: 30, 
                message: "温度范围为 -30℃ 到 30℃", 
                trigger: "blur" 
              }
            ]}
          >
            <ElInputNumber
              v-model={tempForm.temperature}
              min={-30}
              max={30}
              step={0.5}
              precision={1}
              class="w-full!"
              placeholder="请输入温度值"
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        try {
          // 添加 loading 状态
          operatingIds.value.add(row.id);
          
          const res = await setTemperature(row.id, { temperature: tempForm.temperature });
          if (res.code === 200 || res.code === 0) {
            message(`已设置温度为 ${tempForm.temperature}℃`, { type: "success" });
            done();
            // 温度设置成功后刷新列表，更新温度显示
            await onSearch();
          } else {
            message(res.message || "设置失败", { type: "error" });
          }
        } catch (error) {
          console.error("设置温度失败:", error);
          message("设置失败", { type: "error" });
        } finally {
          // 移除 loading 状态
          operatingIds.value.delete(row.id);
        }
      }
    });
  }

  // 设置音量
  const volumeForm = reactive({ volume: 0 });

  function handleSetVolume(row: DeviceItem) {
    volumeForm.volume = row.volume;

    addDialog({
      title: `设置 ${row.deviceName} 的音量`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <ElForm ref={ruleFormRef} model={volumeForm} label-width="80px">
          <ElFormItem
            label="音量"
            prop="volume"
            rules={[
              { required: true, message: "请输入音量", trigger: "blur" },
              { 
                type: "number", 
                min: 0, 
                max: 100, 
                message: "音量范围为 0 到 100", 
                trigger: "blur" 
              }
            ]}
          >
            <ElInputNumber
              v-model={volumeForm.volume}
              min={0}
              max={100}
              step={5}
              class="w-full!"
              placeholder="请输入音量值 (0-100)"
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        try {
          // 添加 loading 状态
          operatingIds.value.add(row.id);
          
          const res = await setVolume(row.id, { volume: volumeForm.volume });
          if (res.code === 200 || res.code === 0) {
            message(`已设置音量为 ${volumeForm.volume}`, { type: "success" });
            done();
            // 音量设置成功后刷新列表，更新音量显示
            await onSearch();
          } else {
            message(res.message || "设置失败", { type: "error" });
          }
        } catch (error) {
          console.error("设置音量失败:", error);
          message("设置失败", { type: "error" });
        } finally {
          // 移除 loading 状态
          operatingIds.value.delete(row.id);
        }
      }
    });
  }

  const recordColumns: TableColumnList = [
    {
      label: "活动 ID",
      prop: "activityId",
      minWidth: 180
    },
    {
      label: "用户 ID",
      prop: "userId",
      minWidth: 100
    },
    {
      label: "门索引",
      prop: "doorIndex",
      minWidth: 80
    },
    {
      label: "类型",
      prop: "openType",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <el-tag type={row.openType === "IN" ? "warning" : "info"}>
          {row.openType === "IN" ? "上货" : "消费"}
        </el-tag>
      )
    },
    {
      label: "门状态",
      prop: "doorStatus",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag 
          type={
            row.doorStatus === "OPENED" ? "danger" : 
            row.doorStatus === "CLOSED" ? "success" : "info"
          }
        >
          {
            row.doorStatus === "OPENED" ? "已开门" : 
            row.doorStatus === "CLOSED" ? "已关门" : "异常"
          }
        </el-tag>
      )
    },
    {
      label: "是否有消费",
      prop: "nobuy",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={row.nobuy === 0 ? "success" : "info"}>
          {row.nobuy === 0 ? "有消费" : "无消费"}
        </el-tag>
      )
    },
    {
      label: "开门时间",
      prop: "openTime",
      minWidth: 160,
      formatter: ({ openTime }) => dayjs(openTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "关门时间",
      prop: "closeTime",
      minWidth: 160,
      formatter: ({ closeTime }) => 
        closeTime ? dayjs(closeTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "持续时长 (秒)",
      prop: "duration",
      minWidth: 100
    },
    {
      label: "来源",
      prop: "source",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={row.source === "MINIAPP" ? "primary" : "info"} size="small">
          {row.source === "MINIAPP" ? "小程序" : row.source === "ADMIN" ? "管理后台" : row.source || "-"}
        </el-tag>
      )
    }
  ];
  
  // 查询开关门记录
  async function fetchDoorRecords() {
    if (!currentDeviceId.value) return;
    
    console.log('开始查询开关门记录 - deviceId:', currentDeviceId.value);
    recordLoading.value = true;
    try {
      const res = await getDoorRecords(currentDeviceId.value, {
        page: recordPagination.currentPage,
        pageSize: recordPagination.pageSize
      });
      
      console.log('后端返回完整数据:', JSON.stringify(res, null, 2));
      console.log('res.data:', res.data);
      console.log('res.data.list:', res.data?.list);
      
      // 注意：http.request 返回的数据已经在 data 字段中
      // 兼容 code === 0 和 code === 200 两种格式
      if ((res.code === 0 || res.code === 200) && res.data) {
        // res.data 就是后端返回的 {list, total, pageSize, currentPage}
        recordList.value = res.data.list || [];
        recordPagination.total = res.data.total || 0;
        console.log('✅ 记录列表:', recordList.value);
        console.log('✅ 总数:', recordPagination.total);
      } else {
        console.warn('查询失败或无数据 - code:', res.code, 'data:', res.data);
      }
    } catch (error) {
      console.error("查询开关门记录失败:", error);
      message("查询失败", { type: "error" });
    } finally {
      recordLoading.value = false;
    }
  }
  
  // 显示开关门记录弹窗
  function showDoorRecords(row: DeviceItem) {
    currentDeviceId.value = row.deviceId;
    recordPagination.currentPage = 1;
    recordPagination.pageSize = 10;
    dialogVisible.value = true;
    fetchDoorRecords();
  }
  
  // 记录分页大小变化
  function handleRecordSizeChange(val: number) {
    recordPagination.pageSize = val;
    recordPagination.currentPage = 1;
    fetchDoorRecords();
  }
  
  // 记录页码变化
  function handleRecordCurrentChange(val: number) {
    recordPagination.currentPage = val;
    fetchDoorRecords();
  }

  // 设备详细状态
  async function handleDeviceDetailStatus(row: DeviceItem) {
    try {
      const { data } = await getDeviceDetailStatus(row.deviceId);
      addDialog({
        title: `设备详细状态 - ${row.deviceId}`,
        width: "40%",
        draggable: true,
        closeOnClickModal: false,
        contentRenderer: () => (
          <div style="max-height: 60vh; overflow-y: auto;">
            {data ? (
              <div style="display: flex; flex-direction: column; gap: 8px;">
                {Object.entries(data).map(([key, value]: [string, any]) => (
                  <div style="display: flex; justify-content: space-between; padding: 8px 12px; background: #f9f9f9; border-radius: 6px;">
                    <span style="font-weight: 500; text-transform: capitalize;">
                      {key.replace(/_/g, " ")}
                    </span>
                    <span>{typeof value === "object" ? JSON.stringify(value) : String(value ?? "-")}</span>
                  </div>
                ))}
              </div>
            ) : (
              <div style="text-align: center; padding: 40px; color: #999;">暂无状态数据</div>
            )}
          </div>
        ),
        hideFooter: true
      });
    } catch {
      message("获取设备详细状态失败", { type: "error" });
    }
  }

  // ==================== 补货员绑定管理（勾选模式） ====================
  const replenisherDialogVisible = ref(false);
  const replenisherLoading = ref(false);
  const currentDeviceForReplenisher = ref<DeviceItem>(null);
  const boundReplenishers = ref<any[]>([]);
  const allReplenishers = ref<any[]>([]);
  const selectedReplenisherIds = ref<Set<number>>(new Set());
  const origBoundReplenisherIds = ref<Set<number>>(new Set());
  const replenisherFilterKeyword = ref("");
  const confirmReplenisherLoading = ref(false);

  const filteredReplenishers = computed(() => {
    const keyword = replenisherFilterKeyword.value.trim().toLowerCase();
    if (!keyword) return allReplenishers.value;
    return allReplenishers.value.filter((r: any) => {
      return (
        (r.name && r.name.toLowerCase().includes(keyword)) ||
        (r.phone && r.phone.includes(keyword)) ||
        (r.employeeId && r.employeeId.toLowerCase().includes(keyword))
      );
    });
  });

  // 全选状态（当前过滤列表）
  const replenisherAllSelected = computed(() => {
    const filtered = filteredReplenishers.value;
    return filtered.length > 0 && filtered.every((r: any) => selectedReplenisherIds.value.has(r.id));
  });

  const replenisherSelectPartial = computed(() => {
    const filtered = filteredReplenishers.value;
    return filtered.some((r: any) => selectedReplenisherIds.value.has(r.id)) && !replenisherAllSelected.value;
  });

  function toggleAllReplenishers() {
    const newSet = new Set(selectedReplenisherIds.value);
    if (replenisherAllSelected.value) {
      filteredReplenishers.value.forEach((r: any) => newSet.delete(r.id));
    } else {
      filteredReplenishers.value.forEach((r: any) => newSet.add(r.id));
    }
    selectedReplenisherIds.value = newSet;
  }

  async function handleBindReplenisher(row: DeviceItem) {
    currentDeviceForReplenisher.value = row;
    replenisherDialogVisible.value = true;
    replenisherFilterKeyword.value = "";
    replenisherLoading.value = true;

    try {
      // 并行获取所有补货员 + 已绑定的补货员
      const [allRes, boundRes] = await Promise.all([
        searchReplenishers(""),
        getDeviceReplenishers(row.deviceId)
      ]);

      allReplenishers.value = allRes.data || [];
      const boundList: any[] = boundRes.data || [];
      boundReplenishers.value = boundList;

      const boundIds = new Set<number>(boundList.map((r: any) => r.id));
      selectedReplenisherIds.value = new Set(boundIds);
      origBoundReplenisherIds.value = new Set(boundIds);
    } catch (error) {
      console.error("获取数据失败:", error);
      message("加载数据失败", { type: "error" });
      allReplenishers.value = [];
    } finally {
      replenisherLoading.value = false;
    }
  }

  function toggleReplenisherSelect(replenisherId: number) {
    const newSet = new Set(selectedReplenisherIds.value);
    if (newSet.has(replenisherId)) {
      newSet.delete(replenisherId);
    } else {
      newSet.add(replenisherId);
    }
    selectedReplenisherIds.value = newSet;
  }

  async function handleReplenisherConfirm() {
    if (!currentDeviceForReplenisher.value) return;

    const deviceId = currentDeviceForReplenisher.value.deviceId;
    const origSet = origBoundReplenisherIds.value;
    const newSet = selectedReplenisherIds.value;

    const toBind = [...newSet].filter(id => !origSet.has(id));
    const toUnbind = [...origSet].filter(id => !newSet.has(id));

    if (toBind.length === 0 && toUnbind.length === 0) {
      message("未做任何变更", { type: "info" });
      return;
    }

    confirmReplenisherLoading.value = true;
    try {
      // 批量绑定新选择的补货员
      if (toBind.length > 0) {
        await Promise.all(toBind.map(id =>
          bindDeviceReplenisher(deviceId, { replenisherId: id })
        ));
      }

      // 批量解绑被取消的补货员
      if (toUnbind.length > 0) {
        await Promise.all(toUnbind.map(id =>
          unbindDeviceReplenisher(deviceId, id)
        ));
      }

      message(`补货员更新完成（绑定${toBind.length}人，解绑${toUnbind.length}人）`, { type: "success" });
      replenisherDialogVisible.value = false;
      onSearch();
    } catch (error) {
      message("操作失败", { type: "error" });
    } finally {
      confirmReplenisherLoading.value = false;
    }
  }

  async function fetchShopOptions() {
    try {
      const { data } = await getEnabledShops();
      shopOptions.value = data || [];
    } catch (error) {
      console.error("获取门店列表失败:", error);
    }
  }

  onMounted(async () => {
    await fetchShopOptions();
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    shopOptions,
    onSearch,
    resetForm,
    handleOpenDoor,
    handleSetTemperature,
    handleSetVolume,
    handleSizeChange,
    handleCurrentChange,
    operatingIds,
    // 开关门记录相关
    dialogVisible,
    recordLoading,
    recordList,
    recordColumns,
    recordPagination,
    showDoorRecords,
    handleRecordSizeChange,
    handleRecordCurrentChange,
    // 补货员绑定相关（勾选模式）
    replenisherDialogVisible,
    replenisherLoading,
    currentDeviceForReplenisher,
    boundReplenishers,
    allReplenishers,
    selectedReplenisherIds,
    replenisherFilterKeyword,
    filteredReplenishers,
    replenisherAllSelected,
    replenisherSelectPartial,
    confirmReplenisherLoading,
    handleDeviceDetailStatus,
    handleBindReplenisher,
    toggleReplenisherSelect,
    toggleAllReplenishers,
    handleReplenisherConfirm
  };
}
