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
} from "@/api/device";
import { getEnabledShops } from "@/api/shop";
import { type Ref, 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: "",
    storeName: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const shopOptions = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "设备ID",
      prop: "deviceId",
      minWidth: 120
    },
    {
      label: "设备名称",
      prop: "deviceName",
      minWidth: 120
    },
    {
      label: "所属门店",
      prop: "shopName",
      minWidth: 120
    },
    {
      label: "货柜名称",
      prop: "storeName",
      minWidth: 100
    },
    {
      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.storeName) searchParams.storeName = form.storeName;
      
      const { data } = await getDeviceList(searchParams);
      dataList.value = data.list;
      pagination.total = 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 {
      await ElMessageBox.confirm(`确认要远程开启设备 ${row.deviceName} 的门吗?`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });

      const res = await openDoor(row.id);
      if (res.code === 0) {
        message(`已发送开门指令到设备 ${row.deviceName}`, { type: "success" });
      } else {
        message(res.message || "开门失败", { type: "error" });
      }
    } catch (error) {
      // 用户取消或请求失败
    }
  }

  // 设置温度
  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" }]}
          >
            <ElInputNumber
              v-model={tempForm.temperature}
              min={-30}
              max={30}
              class="w-full!"
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        try {
          const res = await setTemperature(row.id, { temperature: tempForm.temperature });
          if (res.code === 0) {
            row.temperature = tempForm.temperature;
            message(`已设置温度为 ${tempForm.temperature}℃`, { type: "success" });
            done();
          } else {
            message(res.message || "设置失败", { type: "error" });
          }
        } catch (error) {
          message("设置失败", { type: "error" });
        }
      }
    });
  }

  // 设置音量
  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" }]}
          >
            <ElInputNumber
              v-model={volumeForm.volume}
              min={0}
              max={100}
              class="w-full!"
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        try {
          const res = await setVolume(row.id, { volume: volumeForm.volume });
          if (res.code === 0) {
            row.volume = volumeForm.volume;
            message(`已设置音量为 ${volumeForm.volume}`, { type: "success" });
            done();
          } else {
            message(res.message || "设置失败", { type: "error" });
          }
        } catch (error) {
          message("设置失败", { type: "error" });
        }
      }
    });
  }

  // 获取门店列表
  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
  };
}
