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 { AmapWithSearch } from "@/components/AmapWithSearch";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { regionData, CodeToText, TextToCode } from "@/utils/chinaArea";
import {
  getShopList,
  createShop,
  updateShop,
  deleteShop,
  toggleShopStatus,
  getShopDevices,
  getShopReplenishers,
  addReplenisherToShop,
  linkDevice,
  unlinkDevice,
  getUnlinkedDevices
} from "@/api/shop";
import { getAllRoles } from "@/api/role";
import { getAdminList } from "@/api/admin";
import { searchReplenishers, unbindDevice } from "@/api/replenisher";
import { type Ref, ref, toRaw, reactive, onMounted, computed } from "vue";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadioButton,
  ElMessageBox,
  ElTransfer
} from "element-plus";
import type { ShopItem, ShopSearchForm, DeviceItem } from "./types";

export function useShop(tableRef: Ref) {
  const form = reactive<ShopSearchForm>({
    name: "",
    city: "",
    status: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "门店ID",
      prop: "id",
      width: 80
    },
    {
      label: "门店名称",
      prop: "name",
      minWidth: 150
    },
    {
      label: "所在城市",
      prop: "city",
      minWidth: 100,
      formatter: ({ province, city, district }) => `${province}${city}${district}`
    },
    {
      label: "详细地址",
      prop: "address",
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      label: "联系电话",
      prop: "contactPhone",
      minWidth: 120
    },
    {
      label: "设备数量",
      prop: "deviceCount",
      width: 90
    },
    {
      label: "补货员数量",
      prop: "replenisherCount",
      width: 100
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <el-tag type={row.status === 1 ? "success" : "danger"}>
          {row.status === 1 ? "营业中" : "已停业"}
        </el-tag>
      )
    },
    {
      label: "定位",
      width: 80,
      cellRenderer: ({ row }) => (
        <el-button
          size="small"
          type="primary"
          link
          onClick={() => handleShowLocation(row)}
        >
          查看
        </el-button>
      )
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];

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

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

  // 经纬度变化处理
  function handleLngLatChange(field: "longitude" | "latitude", value: string) {
    if (field === "longitude") {
      shopForm.longitude = value;
    } else {
      shopForm.latitude = value;
    }
  }

  // 查看门店位置
  function handleShowLocation(row: ShopItem) {
    addDialog({
      title: `门店位置 - ${row.name}`,
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      closeOnClickModal: true,
      hideFooter: true,
      contentRenderer: () => (
        <div class="p-4">
          <div class="mb-4 text-sm text-gray-600">
            <div class="mb-2">
              <strong>门店名称：</strong>{row.name}
            </div>
            <div class="mb-2">
              <strong>门店地址：</strong>{row.province}{row.city}{row.district}{row.address}
            </div>
            {row.longitude && row.latitude ? (
              <div class="text-green-600">
                <strong>坐标：</strong>经度 {row.longitude}，纬度 {row.latitude}
              </div>
            ) : (
              <div class="text-orange-500">
                <strong>提示：</strong>该门店暂无坐标信息，请在编辑页面设置位置
              </div>
            )}
          </div>
          <AmapWithSearch
            longitude={Number(row.longitude) || undefined}
            latitude={Number(row.latitude) || undefined}
            height="450px"
            zoom={15}
            enableClickMark={false}
            showSearch={false}
          />
        </div>
      )
    });
  }

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

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

  // 门店表单
  const shopForm = reactive({
    name: "",
    province: "",
    city: "",
    district: "",
    address: "",
    latitude: "",
    longitude: "",
    contactPhone: "",
    contactName: "",
    businessHours: "",
    status: 1
  });

  // 省市区联动选择器
  const selectedProvince = ref("440000"); // 广东省
  const selectedCity = ref("440300"); // 深圳市
  const selectedDistrict = ref("");

  // 完整的省市区信息（用于只读框显示）
  const fullRegionText = computed(() => {
    return `${shopForm.province || ''}${shopForm.city || ''}${shopForm.district || ''}`;
  });

  // 省份列表
  const provinceOptions = computed(() => regionData);

  // 城市列表（根据省份联动）
  const cityOptions = computed(() => {
    const province = regionData.find((p: any) => p.value === selectedProvince.value);
    return province?.children || [];
  });

  // 区县列表（根据城市联动）
  const districtOptions = computed(() => {
    const province = regionData.find((p: any) => p.value === selectedProvince.value);
    const city = province?.children?.find((c: any) => c.value === selectedCity.value);
    return city?.children || [];
  });

  // 详细地址的详细部分（不含省市区前缀）
  const addressDetail = ref("");

  // 更新详细地址前缀
  function updateAddressPrefix() {
    const provinceText = shopForm.province || "";
    const cityText = shopForm.city || "";
    const districtText = shopForm.district || "";
    const prefix = provinceText + cityText + districtText;
    
    // 更新详细地址：前缀 + 用户输入的详细部分
    shopForm.address = prefix + addressDetail.value;
  }

  
  // 省份变化时，清空城市和区县
  function handleProvinceChange(val: string) {
    selectedCity.value = "";
    selectedDistrict.value = "";
    shopForm.province = CodeToText[val] || "";
    shopForm.city = "";
    shopForm.district = "";
    addressDetail.value = "";
    updateAddressPrefix();
  }

  
  // 城市变化时，清空区县
  function handleCityChange(val: string) {
    selectedDistrict.value = "";
    shopForm.city = CodeToText[val] || "";
    shopForm.district = "";
    updateAddressPrefix();
  }
  
  // 区县变化时
  function handleDistrictChange(val: string) {
    shopForm.district = CodeToText[val] || "";
    updateAddressPrefix();
  }

  // 初始化省市区默认值
  function initDefaultRegion() {
    selectedProvince.value = "440000"; // 广东省
    selectedCity.value = "440300"; // 深圳市
    shopForm.province = CodeToText["440000"] || "广东省";
    shopForm.city = CodeToText["440300"] || "深圳市";
    shopForm.district = "";
    updateAddressPrefix();
  }

  // 打开新增/编辑弹窗
  function openDialog(title = "新增", row?: ShopItem) {
    // 初始化省市区选择器
    if (row?.province) {
      selectedProvince.value = TextToCode[row.province]?.code || "";
    } else {
      selectedProvince.value = "440000"; // 默认广东省
    }
    if (row?.city && selectedProvince.value) {
      selectedCity.value = TextToCode[row.province]?.[row.city]?.code || "";
    } else if (!row?.province) {
      selectedCity.value = "440300"; // 默认深圳市
    } else {
      selectedCity.value = "";
    }
    if (row?.district && selectedCity.value) {
      selectedDistrict.value = TextToCode[row.province]?.[row.city]?.[row.district]?.code || "";
    } else {
      selectedDistrict.value = "";
    }
    
    // 设置表单数据，新增时使用默认省市区
    Object.assign(shopForm, {
      name: row?.name ?? "",
      province: row?.province ?? CodeToText["440000"] ?? "广东省",
      city: row?.city ?? CodeToText["440300"] ?? "深圳市",
      district: row?.district ?? "",
      address: row?.address ?? "",
      latitude: row?.latitude ?? "",
      longitude: row?.longitude ?? "",
      contactPhone: row?.contactPhone ?? "",
      contactName: row?.contactName ?? "",
      businessHours: row?.businessHours ?? "",
      status: row?.status ?? 1
    });

    // 从地址中提取详细部分（去除省市区前缀）
    if (row?.address) {
      const prefix = (row.province || "") + (row.city || "") + (row.district || "");
      addressDetail.value = row.address.startsWith(prefix) 
        ? row.address.substring(prefix.length) 
        : row.address;
    } else {
      addressDetail.value = "";
    }

    addDialog({
      title: `${title}门店`,
      width: "900px",
      draggable: true,
      fullscreen: deviceDetection(),
      closeOnClickModal: false,
      center: true,
      contentRenderer: () => (
        <div class="p-6">
          <ElForm ref={ruleFormRef} model={shopForm} label-width="90px" size="default">
            <div class="grid grid-cols-2 gap-x-8 gap-y-2">
              <ElFormItem
                label="门店名称"
                prop="name"
                rules={[{ required: true, message: "请输入门店名称", trigger: "blur" }]}
              >
                <ElInput v-model={shopForm.name} placeholder="请输入门店名称" clearable />
              </ElFormItem>
              <ElFormItem label="状态" prop="status">
                <ElRadioGroup v-model={shopForm.status}>
                  <ElRadioButton value={1}>营业中</ElRadioButton>
                  <ElRadioButton value={0}>已停业</ElRadioButton>
                </ElRadioGroup>
              </ElFormItem>
            </div>
            
            <div class="grid grid-cols-3 gap-x-4 gap-y-2">
              <ElFormItem label="省份" prop="province">
                <ElSelect
                  v-model={selectedProvince.value}
                  placeholder="请选择省份"
                  clearable
                  filterable
                  onChange={handleProvinceChange}
                >
                  {provinceOptions.value.map((item: any) => (
                    <ElOption key={item.value} label={item.label} value={item.value} />
                  ))}
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="城市" prop="city">
                <ElSelect
                  v-model={selectedCity.value}
                  placeholder="请选择城市"
                  clearable
                  filterable
                  disabled={!selectedProvince.value}
                  onChange={handleCityChange}
                >
                  {cityOptions.value.map((item: any) => (
                    <ElOption key={item.value} label={item.label} value={item.value} />
                  ))}
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="区县" prop="district">
                <ElSelect
                  v-model={selectedDistrict.value}
                  placeholder="请选择区县"
                  clearable
                  filterable
                  disabled={!selectedCity.value}
                  onChange={handleDistrictChange}
                >
                  {districtOptions.value.map((item: any) => (
                    <ElOption key={item.value} label={item.label} value={item.value} />
                  ))}
                </ElSelect>
              </ElFormItem>
            </div>
            
            <ElFormItem
              label="详细地址"
              prop="address"
              rules={[{ required: true, message: "请输入详细地址", trigger: "blur" }]}
            >
              <div class="flex items-center gap-2 w-full">
                <ElInput
                  modelValue={fullRegionText.value}
                  placeholder="省市区"
                  readonly
                  class="w-[180px]!"
                  style="flex-shrink: 0"
                />
                <ElInput 
                  v-model={addressDetail.value} 
                  placeholder="请输入详细地址（如：xx 路 xx 号）" 
                  clearable 
                  class="flex-1"
                  onInput={() => updateAddressPrefix()}
                />
              </div>
            </ElFormItem>
            
            <div class="grid grid-cols-3 gap-x-4 gap-y-2">
              <ElFormItem label="联系人" prop="contactName">
                <ElInput v-model={shopForm.contactName} placeholder="请输入联系人" clearable />
              </ElFormItem>
              <ElFormItem label="联系电话" prop="contactPhone">
                <ElInput v-model={shopForm.contactPhone} placeholder="请输入联系电话" clearable />
              </ElFormItem>
              <ElFormItem label="营业时间" prop="businessHours">
                <ElInput v-model={shopForm.businessHours} placeholder="如: 08:00-22:00" clearable />
              </ElFormItem>
            </div>
            
            <div class="border-t border-gray-200 pt-4 mt-4">
              <div class="flex items-center gap-2 mb-4">
                <div class="w-1 h-4 bg-primary rounded"></div>
                <span class="text-sm font-medium text-gray-700">门店位置</span>
              </div>
              
              <div class="grid grid-cols-2 gap-x-8 gap-y-2 mb-4">
                <ElFormItem label="经度" prop="longitude">
                  <ElInput
                    v-model={shopForm.longitude}
                    placeholder="请输入经度"
                    clearable
                    onChange={(val: any) => handleLngLatChange("longitude", val)}
                  />
                </ElFormItem>
                <ElFormItem label="纬度" prop="latitude">
                  <ElInput
                    v-model={shopForm.latitude}
                    placeholder="请输入纬度"
                    clearable
                    onChange={(val: any) => handleLngLatChange("latitude", val)}
                  />
                </ElFormItem>
              </div>
              
              <AmapWithSearch
                longitude={Number(shopForm.longitude) || undefined}
                latitude={Number(shopForm.latitude) || undefined}
                height="280px"
                zoom={15}
                enableClickMark={true}
                showSearch={true}
                securityJsCode="bcfcaa8d8ef22452d4cf6d3892646262"
                onUpdate:longitude={(val: number) => (shopForm.longitude = String(val))}
                onUpdate:latitude={(val: number) => (shopForm.latitude = String(val))}
                onMarkerMoved={(lng: number, lat: number) => {
                  shopForm.longitude = String(lng);
                  shopForm.latitude = String(lat);
                }}
              />
              <div class="text-xs text-gray-500 mt-2 flex items-center gap-1">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                </svg>
                <span>可以通过地址搜索快速定位，也可以点击地图或拖动标记点来精确选择门店位置</span>
              </div>
            </div>
          </ElForm>
        </div>
      ),
      beforeSure: async (done, { closeLoading }) => {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) {
          closeLoading();
          return;
        }

        try {
          if (title === "新增") {
            const res = await createShop(toRaw(shopForm));
            if (res.code === 0 || res.code === 200) {
              message(`新增门店 ${shopForm.name} 成功`, { type: "success" });
              done();
              onSearch();
            } else {
              closeLoading();
              message(res.message || "新增失败", { type: "error" });
            }
          } else {
            const res = await updateShop(row.id, toRaw(shopForm));
            if (res.code === 0 || res.code === 200) {
              message(`修改门店 ${shopForm.name} 成功`, { type: "success" });
              done();
              onSearch();
            } else {
              closeLoading();
              message(res.message || "修改失败", { type: "error" });
            }
          }
        } catch (error) {
          closeLoading();
          message("操作失败", { type: "error" });
        }
      }
    });
  }

  // 删除门店
  async function handleDelete(row: ShopItem) {
    try {
      const res = await deleteShop(row.id);
      if (res.code === 0 || res.code === 200) {
        message(`已成功删除门店 ${row.name}`, { type: "success" });
        onSearch();
      } else {
        message(res.message || "删除失败", { type: "error" });
      }
    } catch (error) {
      message("删除失败", { type: "error" });
    }
  }
  
  // 切换门店状态
  async function handleToggleStatus(row: ShopItem) {
    const newStatus = row.status === 1 ? 0 : 1;
    const actionText = newStatus === 1 ? "营业" : "停业";
  
    try {
      await ElMessageBox.confirm(`确认要${actionText}门店 ${row.name} 吗？`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });
  
      const res = await toggleShopStatus(row.id, { status: newStatus });
      if (res.code === 0 || res.code === 200) {
        row.status = newStatus;
        message(`已${actionText}门店 ${row.name}`, { type: "success" });
      } else {
        message(res.message || `${actionText}失败`, { type: "error" });
      }
    } catch (error) {
      // 用户取消或请求失败
    }
  }

  // 设备关联
  async function handleDevices(row: ShopItem) {
    const [devicesRes, unlinkedRes] = await Promise.all([
      getShopDevices(row.id),
      getUnlinkedDevices()
    ]);

    const linkedDevices = devicesRes.data || [];
    const unlinkedDevices = unlinkedRes.data || [];
    const selectedDeviceIds = ref(linkedDevices.map(d => d.deviceId));

    addDialog({
      title: `管理 ${row.name} 的设备`,
      width: "60%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <div>
          <el-transfer
            v-model={selectedDeviceIds.value}
            data={unlinkedDevices.concat(linkedDevices)}
            titles={["可选设备", "已关联设备"]}
            props={{
              key: "deviceId",
              label: "deviceName"
            }}
          />
        </div>
      ),
      beforeSure: async (done, { closeLoading }) => {
        try {
          // 先解除所有关联
          for (const device of linkedDevices) {
            await unlinkDevice(row.id, device.id);
          }
          // 再添加新关联
          for (const deviceId of selectedDeviceIds.value) {
            const device = unlinkedDevices.find(d => d.deviceId === deviceId) ||
                          linkedDevices.find(d => d.deviceId === deviceId);
            if (device) {
              await linkDevice(row.id, { deviceId: device.id });
            }
          }
          message("设备关联更新成功", { type: "success" });
          done();
          onSearch();
        } catch (error) {
          closeLoading();
          message("操作失败", { type: "error" });
        }
      }
    });
  }

  // 补货员管理 V2
  async function handleReplenishers(row: ShopItem) {
    const replenishersRes = await getShopReplenishers(row.id);
    const currentReplenishers = ref<any[]>(replenishersRes.data || []);
    const searchKeyword = ref("");
    const searchResults = ref<any[]>([]);
    const searchLoading = ref(false);

    async function doSearch() {
      const keyword = searchKeyword.value.trim();
      if (!keyword) {
        message("请输入搜索关键词", { type: "warning" });
        return;
      }
      searchLoading.value = true;
      try {
        const res = await searchReplenishers(keyword);
        if (res.code === 0 || res.code === 200) {
          searchResults.value = res.data || [];
        }
      } catch {
        searchResults.value = [];
      } finally {
        searchLoading.value = false;
      }
    }

    async function doAdd(replenisher: any) {
      try {
        const res = await addReplenisherToShop(row.id, { replenisherId: replenisher.id });
        if (res.code === 0 || res.code === 200) {
          message(`已添加补货员 ${replenisher.name}`, { type: "success" });
          const updateRes = await getShopReplenishers(row.id);
          currentReplenishers.value = updateRes.data || [];
          searchKeyword.value = "";
          searchResults.value = [];
        } else {
          message(res.message || "操作失败", { type: "error" });
        }
      } catch {
        message("操作失败", { type: "error" });
      }
    }

    async function doRemove(replenisher: any) {
      try {
        // 获取门店所有设备并逐个解绑
        const devicesRes = await getShopDevices(row.id);
        const devices = devicesRes.data || [];
        if (devices.length === 0) {
          message("该门店下无设备", { type: "warning" });
          return;
        }
        for (const device of devices) {
          await unbindDevice(replenisher.id, device.deviceId);
        }
        message(`已移除补货员 ${replenisher.name}`, { type: "success" });
        const updateRes = await getShopReplenishers(row.id);
        currentReplenishers.value = updateRes.data || [];
      } catch {
        message("操作失败", { type: "error" });
      }
    }

    addDialog({
      title: `管理 ${row.name} 的补货员`,
      width: "500px",
      draggable: true,
      closeOnClickModal: false,
      hideFooter: true,
      contentRenderer: () => (
        <div class="p-2">
          <div class="text-sm font-medium mb-2 text-gray-600">当前绑定的补货员：</div>
          {currentReplenishers.value.length === 0 ? (
            <el-empty description="暂无绑定补货员" />
          ) : (
            <div class="space-y-2 mb-4">
              {currentReplenishers.value.map((r: any) => (
                <div class="flex items-center justify-between px-3 py-2 rounded bg-[var(--el-fill-color-light)]">
                  <div class="flex items-center gap-2">
                    <span class="text-sm font-medium">{r.name}</span>
                    {r.phone ? <span class="text-xs text-gray-400">{r.phone}</span> : null}
                    {r.employeeId ? <el-tag size="small" type="info">{r.employeeId}</el-tag> : null}
                  </div>
                  <el-button
                    type="danger"
                    link
                    size="small"
                    loading={false}
                    onClick={() => doRemove(r)}
                  >
                    移除
                  </el-button>
                </div>
              ))}
            </div>
          )}
          <el-divider />
          <div class="text-sm font-medium mb-2 text-gray-600">搜索并添加补货员：</div>
          <div class="flex gap-2 mb-2">
            <el-input
              v-model={searchKeyword.value}
              placeholder="输入姓名/手机号/工号搜索"
              clearable
              class="flex-1"
              onKeyupEnter={() => doSearch()}
            />
            <el-button type="primary" loading={searchLoading.value} onClick={() => doSearch()}>
              搜索
            </el-button>
          </div>
          {searchResults.value.length > 0 ? (
            <div>
              {searchResults.value.map((r: any) => (
                <div class="flex items-center justify-between px-3 py-2 mb-1 rounded bg-[var(--el-color-primary-light-9)]">
                  <div class="flex items-center gap-2">
                    <span class="text-sm">{r.name}</span>
                    {r.phone ? <span class="text-xs text-gray-400">{r.phone}</span> : null}
                  </div>
                  <el-button
                    type="primary"
                    link
                    size="small"
                    disabled={currentReplenishers.value.some(b => b.id === r.id)}
                    onClick={() => doAdd(r)}
                  >
                    {currentReplenishers.value.some(b => b.id === r.id) ? "已绑定" : "添加"}
                  </el-button>
                </div>
              ))}
            </div>
          ) : searchKeyword.value && !searchLoading.value ? (
            <div class="text-xs text-gray-400 text-center py-2">请输入关键词搜索补货员</div>
          ) : null}
        </div>
      )
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    handleLngLatChange,
    openDialog,
    handleDelete,
    handleToggleStatus,
    handleShowLocation,
    handleDevices,
    handleReplenishers,
    handleSizeChange,
    handleCurrentChange
  };
}
