<script setup lang="ts">
import { ref } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getShopList, ShopDTO, deleteShop, ShopQuery } from "@/api/shop/shop";
import EditPen from "@iconify-icons/ep/edit-pen";
import Delete from "@iconify-icons/ep/delete";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Qrcode from "@iconify-icons/ep/iphone";
import { ElMessage, ElMessageBox } from "element-plus";
import ShopFormModal from "./shop-form-modal.vue";
import ReQrcode from "@/components/ReQrcode";
import { copyTextToClipboard } from "@pureadmin/utils";
import { useWxStore } from "@/store/modules/wx";
import { useSysConfigStoreHook } from "@/store/modules/sysConfig";

defineOptions({
  name: "Shop"
});

const wxStore = useWxStore();
const sysConfigStore = useSysConfigStoreHook();
const formRef = ref();
const tableRef = ref();
const modalVisible = ref(false);
const handleRefresh = () => {
  getList();
  modalVisible.value = false;
  editVisible.value = false;
};

const searchFormParams = ref<ShopQuery>({
  corpid: wxStore.corpid,
  shopName: ""
});

const pagination = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0
});

const loading = ref(false);
const dataList = ref<ShopDTO[]>([]);
const multipleSelection = ref<number[]>([]);
const editVisible = ref(false);
const currentRow = ref<ShopDTO>();

const getList = async () => {
  try {
    loading.value = true;
    const { data } = await getShopList({
      ...searchFormParams.value,
      corpid: wxStore.corpid,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    dataList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    loading.value = false;
  }
};

const onSearch = () => {
  pagination.value.currentPage = 1;
  getList();
};

const resetForm = () => {
  formRef.value.resetFields();
  onSearch();
};

const onSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  getList();
};

const onCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  getList();
};

const handleDelete = async (row: ShopDTO) => {
  try {
    await deleteShop(row.shopId!.toString());
    ElMessage.success("删除成功");
    getList();
  } catch (error) {
    console.error("删除失败", error);
  }
};

const handleBulkDelete = async () => {
  if (multipleSelection.value.length === 0) return;

  try {
    await ElMessageBox.confirm(
      `确认删除选中的${multipleSelection.value.length}家地址吗？`,
      "警告",
      { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
    );

    await deleteShop(multipleSelection.value.join(","));
    ElMessage.success("批量删除成功");
    multipleSelection.value = [];
    getList();
  } catch (error) {
    console.error("删除取消或失败", error);
  }
};

const handleSelectionChange = (rows: ShopDTO[]) => {
  multipleSelection.value = rows.map(row => row.shopId!);
};

const handleEdit = (row: ShopDTO) => {
  currentRow.value = row;
  editVisible.value = true;
};

const qrVisible = ref(false);
const currentShopId = ref<number>(null);

const showQrCode = (shopId: number) => {
  currentShopId.value = shopId;
  qrVisible.value = true;
};

const copyLink = () => {
  const url = `${sysConfigStore.serverHost}/shop-api/api/shop/wechatAuth?shopId=${currentShopId.value}`;
  const success = copyTextToClipboard(url);
  success ? ElMessage.success('链接复制成功') : ElMessage.error('复制失败，请手动复制');
};

getList();
</script>

<template>
  <div class="main">
    <el-form ref="formRef" :inline="true" :model="searchFormParams"
      class="search-form bg-bg_color flex w-[99/100] pl-[22px] pt-[12px]">
      <el-form-item prop="shopName">
        <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.shopName" placeholder="请输入地址名称" clearable
          class="!w-[200px]" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" @click="onSearch">
          搜索
        </el-button>
      </el-form-item>
      <el-form-item class="space-item">
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="modalVisible = true"
          style="margin-right: 10px;">
          新增地址
        </el-button>
      </el-form-item>
    </el-form>

    <div class="table-container">
      <el-table ref="tableRef" v-loading="loading" :data="dataList" row-key="id"
        @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" />
        <el-table-column label="地址ID" prop="shopId" width="100" />
        <el-table-column label="地址名称" prop="shopName" />
        <el-table-column label="商品模式" prop="belongType" width="120">
          <template #default="{ row }">
            {{ row.belongType === 0 ? '借还模式' : '固资模式' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="useRenderIcon(EditPen)" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" link :icon="useRenderIcon(Qrcode)" @click="showQrCode(row.shopId)">
              二维码
            </el-button>
            <el-popconfirm :title="`确认删除【${row.shopName}】？`" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="danger" link :icon="useRenderIcon(Delete)">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        @size-change="onSizeChange" @current-change="onCurrentChange" class="pagination" />
    </div>
    <ShopFormModal :visible="modalVisible" @update:visible="val => modalVisible = val" @refresh="handleRefresh" />
    <ShopFormModal :visible="editVisible" :row="currentRow" @update:visible="val => editVisible = val"
      @refresh="handleRefresh" />
    <el-dialog v-model="qrVisible" title="微信扫码访问" width="300px">
      <div class="flex flex-col items-center">
        <ReQrcode :text="`${sysConfigStore.serverHost}/shop-api/api/shop/wechatAuth?shopId=${currentShopId}`"
          :options="{ width: 200 }" />
        <div class="mt-2 text-sm text-gray-500">微信扫码访问</div>
        <el-button class="mt-2" type="primary" size="small" @click="copyLink">
          复制链接
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
    margin-right: 12px;
  }
}
.space-item {
  flex: 1;
  width: 100%;
}
.table-container {
  margin-top: 8px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;

  .el-table {
    flex: 1;
    overflow: hidden;
  }

  .pagination {
    margin-top: 10px;
  }
}
</style>