<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" :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="店铺名称" prop="storeName">
              <el-input v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="所属用户" prop="vestInUserId">
              <el-select v-model="queryParams.vestInUserId" placeholder="请选择" filterable clearable>
                <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="所属品牌" prop="brandId">
              <el-select v-model="queryParams.brandId" placeholder="请选择" filterable clearable>
                <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="到期时间" prop="expireDate">
              <el-date-picker clearable v-model="queryParams.expireDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择到期时间" />
            </el-form-item>
            <el-form-item label="商户状态" prop="storeStatus">
              <el-select v-model="queryParams.storeStatus" placeholder="请选择商户状态" clearable>
                <el-option v-for="dict in store_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @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 type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:sysShop:add']">添加门店</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="sysShopList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" type="index" width="80px" align="center" />
        <el-table-column label="门店信息" align="center" width="380px">
          <template #default="scope">
            <el-row style="height: 40px; display: flex; align-items: center">
              <el-col :span="6" style="width: 40px">
                <img :src="getStoreLogoUrl(scope.row.storeLogo)" style="width: 40px; height: 40px" class="qr-code" @error="handleImageError" />
              </el-col>
              <el-col :span="18" style="display: flex; align-items: center; height: 40px">
                <div>门店名称: {{ scope.row.storeName }}</div>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="门店地址" align="center" prop="storeAddress" />
        <el-table-column label="客服信息" align="center">
          <template #default="scope">
            <el-row style="height: 40px; display: flex; align-items: center">
              <el-col :span="6" style="width: 40px">
                <img :src="scope.row.serviceQrCode" style="width: 40px; height: 40px" class="qr-code"
              /></el-col>
              <el-col :span="18">
                <el-row>
                  <el-col :span="24">
                    <div>{{ scope.row.serviceName }} {{ scope.row.servicePhone }}</div>
                  </el-col>
                </el-row>
                <el-row v-if="scope.row.agentName || scope.row.agentPhone">
                  <el-col :span="24">
                    <div>代理:{{ scope.row.agentName || '-' }}/{{ scope.row.agentPhone || '-' }}</div>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="时间" align="center" width="230">
          <template #default="scope">
            <el-row>
              <el-col>
                <span>入驻:{{ formatDate(scope.row.createTime) }}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <span>
                  到期: <span :class="{ 'text-danger': isEndDateNear(scope.row.expireDate) }">{{ formatDate(scope.row.expireDate) }}</span>
                </span>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="店铺状态" align="center" width="230">
          <template #default="scope">
            <dict-tag :options="store_status" :value="scope.row.storeStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:sysShop:edit']">编辑</el-button>
            <el-button link type="primary" icon="Edit" @click="assignServiceInfo(scope.row)" v-hasPermi="['system:sysShop:edit']">服务</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:sysShop:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination 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="700px" append-to-body> </el-dialog>
    <!-- 指定服务弹出框 -->
    <el-dialog :title="serviceDialog.title" v-model="serviceDialog.visible" width="700px" append-to-body class="service-dialog">
      <div class="mb-[20px]">
        <el-input v-model="serviceForm.searchValue" placeholder="输入客服名称/手机号" clearable @keyup.enter="handleServiceQuery" class="!w-[240px]">
          <template #prefix>
            <el-icon class="el-input__icon"><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <el-table :data="serviceList" :border="false" highlight-current-row @current-change="handleCurrentChange" class="service-table">
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="客服名称" prop="serviceName" min-width="100" align="center" />
        <el-table-column label="客服二维码" prop="qrCode" width="140" align="center">
          <template #default="scope">
            <img :src="scope.row.qrCode" style="width: 35px; height: 35px" class="qr-code" />
          </template>
        </el-table-column>
        <el-table-column label="客服手机号" prop="phonenumber" min-width="120" align="center" />
        <el-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleSelectService(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex items-center justify-between mt-[15px] px-[10px]">
        <div class="text-[14px] text-[#606266]">共 {{ serviceTotal }} 条</div>
        <div class="flex items-center gap-[8px]">
          <el-pagination
            v-model:current-page="serviceQueryParams.pageNum"
            v-model:page-size="serviceQueryParams.pageSize"
            :total="serviceTotal"
            :pager-count="9"
            layout="prev, pager, next"
            @current-change="getServiceList"
            small
            background
            class="!m-0 custom-pagination"
          />
          <div class="text-[14px] text-[#606266]">
            前往
            <el-input v-model="serviceQueryParams.pageNum" class="!w-[40px] !mx-[4px] !text-center jump-page-input" @keyup.enter="getServiceList" />
            页
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="SysShop" lang="ts">
import { ref, reactive, toRefs, onMounted, getCurrentInstance, watch } from 'vue';
import { useRouter } from 'vue-router';
import { listSysShop, getSysShop, delSysShop, addSysShop, updateSysShop, assignService } from '@/api/store/sysShop/index';
import { SysShopVO, SysShopQuery, SysShopForm } from '@/api/store/sysShop/types';
import { listUser } from '@/api/system/user/index';
import { listTenant } from '@/api/system/tenant/index';
import { listSysService, getSysService } from '@/api/store/sysService/index';
import { SysServiceVO } from '@/api/store/sysService/types';
import { getFileInfo } from '@/api/file/info/index';
import { FileInfoVO } from '@/api/file/info/types';
import { regionData } from 'element-china-area-data';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { store_status } = toRefs<any>(proxy?.useDict('store_status'));
const router = useRouter();
const sysShopList = ref<SysShopVO[]>([]);
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 serviceList = ref<any[]>([]);
const serviceTotal = ref(0);
const currentService = ref<any>(null);

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

const userList = ref<any[]>([]);
const brandList = ref<any[]>([]);

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

// 指定服务弹出框相关数据
const serviceDialog = reactive<DialogOption>({
  visible: false,
  title: '指定服务'
});

const serviceForm = reactive({
  searchValue: ''
});

const serviceQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  searchValue: ''
});

// 文件URL缓存
const fileUrlCache = ref<Map<string, string>>(new Map());

// 根据文件ID获取文件URL
const getFileUrlById = async (fileId: string | number): Promise<string> => {
  if (!fileId) return '';

  const idStr = String(fileId);

  // 如果已经是完整URL，直接返回
  if (idStr.startsWith('http://') || idStr.startsWith('https://')) {
    return idStr;
  }

  // 检查缓存
  if (fileUrlCache.value.has(idStr)) {
    return fileUrlCache.value.get(idStr) || '';
  }

  try {
    const fileInfo = await getFileInfo(Number(fileId));
    const url = fileInfo.data.url || fileInfo.data.path || '';

    // 缓存结果
    fileUrlCache.value.set(idStr, url);

    return url;
  } catch (error) {
    console.error('获取文件URL失败:', error);
    return '';
  }
};

// 获取门店logo URL（同步版本，用于模板）
const getStoreLogoUrl = (storeLogo: string | number): string => {
  if (!storeLogo) return '';

  const idStr = String(storeLogo);

  // 如果已经是完整URL，直接返回
  if (idStr.startsWith('http://') || idStr.startsWith('https://')) {
    return idStr;
  }

  //    检查缓存
  if (fileUrlCache.value.has(idStr)) {
    return fileUrlCache.value.get(idStr) || '';
  }

  // 如果缓存中没有，异步获取并更新
  getFileUrlById(storeLogo).then((url) => {
    if (url) {
      // 触发响应式更新
      fileUrlCache.value.set(idStr, url);
    }
  });

  // 返回空字符串，等待异步加载
  return '';
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.src = ''; // 清空src，显示默认占位符
};

const initFormData: SysShopForm = {
  id: undefined,
  storeLogo: undefined,
  storeName: undefined,
  storeDescribe: undefined,
  areaCode: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  vestInUserId: undefined,
  vestInUser: undefined,
  brandId: undefined,
  brandName: undefined,
  storeSort: undefined,
  storePhonenumber: undefined,
  miniSharePic: undefined,
  storeAddress: undefined,
  packageId: undefined,
  packageName: undefined,
  expireDate: undefined,
  storeStatus: '1',
  status: undefined,
  remark: undefined,
  codeArr: []
};
const data = reactive<PageData<SysShopForm, SysShopQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeName: undefined,
    areaCode: undefined,
    vestInUserId: undefined,
    vestInUser: undefined,
    brandId: undefined,
    brandName: undefined,
    storeSort: undefined,
    storePhonenumber: undefined,
    miniSharePic: undefined,
    storeAddress: undefined,
    packageId: undefined,
    packageName: undefined,
    expireDate: undefined,
    storeStatus: undefined,
    params: {}
  },
  rules: {
    storeLogo: [{ required: true, message: '店铺logo不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
    storeDescribe: [{ required: true, message: '店铺描述不能为空', trigger: 'blur' }],
    brandId: [{ required: true, message: '所属品牌不能为空', trigger: 'blur' }],
    storePhonenumber: [{ required: true, message: '店铺电话不能为空', trigger: 'blur' }],
    storeAddress: [{ required: true, message: '店铺地址不能为空', trigger: 'blur' }],
    expireDate: [{ required: true, message: '到期时间不能为空', trigger: 'blur' }]
  }
});

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

/** 查询门店列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSysShop(queryParams.value);
  sysShopList.value = res.rows;
  total.value = res.total;
  loading.value = false;

  // 批量预加载门店logo URL
  preloadStoreLogoUrls(res.rows);
};

const getUserList = async () => {
  const res = await listUser(null);
  console.log(res);

  userList.value = res.rows;
};

const getBrandList = async () => {
  const res = await listTenant(null);
  console.log(res);
  brandList.value = res.rows;
};

// 批量预加载门店logo URL
const preloadStoreLogoUrls = async (shops: SysShopVO[]) => {
  const logoPromises = shops
    .filter((shop) => shop.storeLogo && !String(shop.storeLogo).startsWith('http'))
    .map((shop) => getFileUrlById(shop.storeLogo));

  try {
    await Promise.all(logoPromises);
  } catch (error) {
    console.error('预加载门店logo URL失败:', error);
  }
};

// 获取服务列表
const getServiceList = async () => {
  const res = await listSysService(serviceQueryParams);
  serviceList.value = res.rows;
  serviceTotal.value = res.total;
};

// 搜索服务
const handleServiceQuery = () => {
  serviceQueryParams.searchValue = serviceForm.searchValue;
  getServiceList();
};

// 选择当前行
const handleCurrentChange = (val: any) => {
  currentService.value = val;
};

// 选择服务
const handleSelectService = async (row: SysServiceVO) => {
  if (!form.value.id) {
    proxy?.$modal.msgError('门店信息不存在');
    return;
  }

  try {
    loading.value = true;
    currentService.value = row;

    // 构造完整的表单数据
    const params = {
      id: form.value.id,
      serviceId: row.id
    };

    const response = await assignService(params);

    proxy?.$modal.msgSuccess('指定服务成功');
    serviceDialog.visible = false;
    await getList();
  } catch (error: any) {
    console.error('指定服务失败:', error);

    // 尝试获取更详细的错误信息
    let errorMsg = '指定服务失败';
    if (error.response?.data?.msg) {
      errorMsg = error.response.data.msg;
    } else if (error.message) {
      errorMsg = error.message;
    }

    proxy?.$modal.msgError(`${errorMsg}，请重试`);
  } finally {
    loading.value = false;
  }
};

// 确认选择服务
const confirmSelectService = () => {
  if (!currentService.value) {
    proxy?.$modal.msgError('请选择一个服务');
    return;
  }
};

// 构建映射表：code => name
const areaCodeToName: Record<string, string> = {};

function buildAreaMap(data: any[]) {
  data.forEach((node) => {
    areaCodeToName[node.value] = node.label;
    if (node.children) buildAreaMap(node.children);
  });
}

// 初始化时构建一次
buildAreaMap(regionData);

// 然后 handleChange 改为：
const handleChange = (val: string[]) => {
  form.value.areaCode = val.join(',');
  form.value.province = areaCodeToName[val[0]] || '';
  form.value.city = areaCodeToName[val[1]] || '';
  form.value.district = areaCodeToName[val[2]] || '';
};

function formatDate(date) {
  if (!date) return '';
  const d = new Date(date);
  if (isNaN(d.getTime())) return ''; // 处理无效日期
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 打开指定服务弹出框
const assignServiceInfo = async (row: SysShopVO) => {
  form.value.id = row.id;
  serviceDialog.visible = true;
  getServiceList();
};

// 判断 endDate 是否 <= 今天 + 30天
const isEndDateNear = (endDate) => {
  if (!endDate) return false;

  const today = new Date();
  const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // 今天 00:00:00

  const thirtyDaysLater = new Date(startOfToday);
  thirtyDaysLater.setDate(startOfToday.getDate() + 30); // 今天 + 30天，也是 00:00:00

  const end = new Date(endDate);
  const endOfDate = new Date(end.getFullYear(), end.getMonth(), end.getDate()); // 忽略时间部分

  return endOfDate <= thirtyDaysLater;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  router.push('/store/shop-page/0');
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SysShopVO) => {
  const _shopId = row?.id || ids.value[0];
  router.push('/store/shop-page/' + _shopId);
};
/** 提交按钮 */
const submitForm = () => {
  sysShopFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSysShop(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSysShop(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

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

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

onMounted(() => {
  getList();
  getUserList();
  getBrandList();
});

// 监听路由变化，当从新增/编辑页面返回时刷新数据
watch(
  () => router.currentRoute.value.path,
  (newPath, oldPath) => {
    // 如果从新增/编辑页面返回到列表页面，刷新数据
    if (oldPath && oldPath.includes('/store/shop-page/') && newPath === '/store/sysShop') {
      getList();
    }
  }
);
</script>
