<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getAb98UserListApi, type Ab98UserDTO, Ab98UserQuery, bindWxMpUser, type BindWxMpUserCommand, getAb98UserListApiWithWx } from "@/api/ab98/user";
import { type PaginationProps } from "@pureadmin/table";
import { CommonUtils } from "@/utils/common";
import { useWxStore } from "@/store/modules/wx";
import { ElMessage, ElMessageBox } from "element-plus";

import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Plus from "@iconify-icons/ep/plus";
import { useRouter } from "vue-router";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { getMembershipTagListApi, type MembershipTagQuery } from "@/api/membership/membershipTag";
import { formatFenToYuan } from "@/utils/currency";

defineOptions({
  name: "Ab98User"
});

const router = useRouter();
const formRef = ref();
const wxStore = useWxStore();
const tagOptions = ref<{ label: string; value: number }[]>([]);
const searchFormParams = reactive<Ab98UserQuery & { search?: string; tagIds?: string }>({
  corpid: wxStore.corpid || "",
  name: undefined,
  tel: undefined,
  idnum: undefined,
  tagIds: undefined,
  hasAb98UserId: undefined,
  search: undefined
});

// 添加会员弹窗相关状态
const dialogVisible = ref(false);
const addMemberFormRef = ref();
const addMemberLoading = ref(false);
const addMemberForm = reactive<BindWxMpUserCommand>({
  corpid: wxStore.corpid || "",
  dynamicCode: "",
  name: "",
  idNum: ""
});

const pageLoading = ref(false);
const dataList = ref<Ab98UserDTO[]>([]);
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 12,
  currentPage: 1,
  background: true
});

async function onSearch() {
  handleSearchInput(searchFormParams.search);
  pagination.currentPage = 1;
  getList();
}

async function getList() {
  CommonUtils.fillPaginationParams(searchFormParams, pagination);

  // 处理标签ID数组转换为逗号分隔的字符串
  const params = { ...searchFormParams };
  if (params.tagIds && Array.isArray(params.tagIds) && params.tagIds.length > 0) {
    params.tagIds = params.tagIds.join(',');
  } else {
    Reflect.deleteProperty(params, 'tagIds');
  }

  pageLoading.value = true;
  const { data } = await getAb98UserListApiWithWx(params).finally(
    () => {
      pageLoading.value = false;
    }
  );

  dataList.value = data.rows;
  pagination.total = data.total;
}

const handleSearchInput = (value) => {
  // 身份证号正则(18位)
  const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
  // 手机号正则
  const phoneRegex = /^1[3-9]\d{9}$/;

  if (idCardRegex.test(value)) {
    searchFormParams.idnum = value;
    searchFormParams.name = '';
    searchFormParams.tel = '';
  } else if (phoneRegex.test(value)) {
    searchFormParams.tel = value;
    searchFormParams.name = '';
    searchFormParams.idnum = '';
  } else {
    searchFormParams.name = value;
    searchFormParams.tel = '';
    searchFormParams.idnum = '';
  }
};

const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  searchFormParams.hasAb98UserId = undefined;
  searchFormParams.tagIds = undefined;
  onSearch();
};

const handleViewDetail = (row: Ab98UserDTO) => {
  // 保存信息到标签页
  useMultiTagsStoreHook().handleTags("push", {
    path: `/user/ab98/detail`,
    name: "ab98Detail",
    query: row.ab98UserId ? { id: row.ab98UserId } : { wxId: row.wxUserId },
    meta: {
      title: `${row.name || row.wxNickName || '用户详情'}`,
      dynamicLevel: 3
    }
  });
  router.push({
    path: '/user/ab98/detail',
    query: row.ab98UserId ? { id: row.ab98UserId } : { wxId: row.wxUserId }
  });
};

// 打开添加会员弹窗
const openAddMemberDialog = () => {
  dialogVisible.value = true;
  // 重置表单
  addMemberForm.dynamicCode = "";
  addMemberForm.name = "";
  addMemberForm.idNum = "";
};

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  addMemberFormRef.value?.resetFields();
};

// 提交添加会员表单
const submitAddMember = async () => {
  if (!addMemberFormRef.value) return;

  await addMemberFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        addMemberLoading.value = true;
        await bindWxMpUser(addMemberForm);
        ElMessage.success("会员添加成功");
        closeDialog();
        // 刷新列表
        getList();
      } catch (error) {
        console.error("添加会员失败:", error);
        ElMessage.error("添加会员失败，请重试");
      } finally {
        addMemberLoading.value = false;
      }
    }
  });
};

// 表单验证规则
const addMemberRules = reactive({
  dynamicCode: [
    { required: true, message: "请输入动态码", trigger: "blur" }
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" }
  ],
  idNum: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: "请输入正确的身份证号", trigger: "blur" }
  ] as any
});

onMounted(() => {
  getList();
  getMembershipTagListApi({ corpid: wxStore.corpid || "" }).then(res => {
    tagOptions.value = res.data.rows.map(tag => ({
      label: tag.name || '',
      value: tag.id || 0
    }));
  });
});

const getIconByName = (name: string) => {
  switch (name) {
    case 'Search':
      return useRenderIcon(Search);
    case 'Refresh':
      return useRenderIcon(Refresh);
    case 'Plus':
      return useRenderIcon(Plus);
    default:
      return '';
  }
}
</script>

<template>
  <div class="main">
    <div class="float-right w-full">
      <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="search">
          <el-input v-model="searchFormParams.search" placeholder="请输入姓名/手机号/身份证" clearable class="!w-[300px]"
            @keydown.enter.prevent="onSearch" @change="handleSearchInput" />
        </el-form-item>
        <el-form-item prop="tagIds">
          <el-select v-model="searchFormParams.tagIds" placeholder="会员标签" multiple clearable collapse-tags
            class="!w-[200px]">
            <el-option v-for="item in tagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="hasAb98UserId">
          <el-select v-model="searchFormParams.hasAb98UserId" placeholder="绑定汇邦云状态" clearable class="!w-[160px]">
            <el-option label="全部" :value="null" />
            <el-option label="已绑定" :value="true" />
            <el-option label="未绑定" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="getIconByName('Search')" :loading="pageLoading" @click="onSearch">
            搜索
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button :icon="getIconByName('Refresh')" @click="resetForm(formRef)">
            重置
          </el-button>
        </el-form-item>
        <el-form-item class="space-item">
        </el-form-item>
        <el-form-item>
          <el-button type="success" :icon="getIconByName('Plus')" @click="openAddMemberDialog">
            关联会员
          </el-button>
        </el-form-item>
      </el-form>

      <div class="grid-container">
        <el-row :gutter="12">
          <el-col v-for="(item, index) in dataList" :key="item.ab98UserId ? 'a' + item.ab98UserId : 'w' + item.wxUserId"
            :xs="24" :sm="12" :md="8" :lg="6">
            <el-card class="user-card" :body-style="{ padding: '8px 20px' }" @click="handleViewDetail(item)">
              <div class="card-content">
                <el-avatar :size="80" :src="item.faceImg || item.wxAvatar" fit="cover" shape="square" class="avatar">
                  <template v-if="!item.faceImg && !item.wxAvatar">
                    <svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
                      <circle cx="50" cy="50" r="48" fill="#f5f5f5" stroke="#e0e0e0" stroke-width="1" />
                      <circle cx="50" cy="40" r="12" fill="#9e9e9e" />
                      <rect x="40" y="52" width="20" height="30" rx="2" fill="#9e9e9e" />
                    </svg>
                  </template>
                </el-avatar>
                <div class="user-info">
                  <template v-if="item.ab98UserId">
                    <div class="name">姓名：{{ item.name }}</div>
                    <div class="gender">性别：{{ item.sex === '男' ? '男' : item.sex === '女' ? '女' : '' }}</div>
                    <div class="tel">电话：{{ item.tel }}</div>
                    <div class="balance">剩余借呗：{{ formatFenToYuan(item.balance) }}</div>
                  </template>
                  <template v-else>
                    <div class="nickname">昵称：{{ item.wxNickName || '微信用户' }}</div>
                    <div class="openid">OpenID：{{ item.wxUserOpenid || '未知' }}</div>
                  </template>
                </div>
              </div>
              <template v-if="item.ab98UserId">
                <div class="idnum">身份证号：{{ item.idnum }}</div>
                <div class="address">住 址：{{ item.address }}</div>
              </template>
            </el-card>
          </el-col>
        </el-row>
        <div class="pagination-wrapper">
          <el-pagination background layout="prev, pager, next" :page-size="pagination.pageSize"
            :total="pagination.total" v-model:current-page="pagination.currentPage" @current-change="getList"
            @size-change="getList" />
        </div>
      </div>
    </div>

    <!-- 关联会员弹窗 -->
    <el-dialog v-model="dialogVisible" title="关联会员" width="500px" :close-on-click-modal="false">
      <el-form ref="addMemberFormRef" :model="addMemberForm" :rules="addMemberRules" label-width="100px">
        <el-form-item label="动态码" prop="dynamicCode">
          <el-input v-model="addMemberForm.dynamicCode" placeholder="请输入动态码" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addMemberForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNum">
          <el-input v-model="addMemberForm.idNum" placeholder="请输入身份证号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" :loading="addMemberLoading" @click="submitAddMember">
            确认添加
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
    margin-right: 12px;
  }
}

.user-card {
  margin-bottom: 12px;
  min-height: 210px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
  border-radius: 8px;

  &:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
    transform: translateY(-4px);
    border-color: #409eff;
  }

  .card-content {
    flex: 1;
    display: flex;
    flex-direction: row;
    margin: 15px 0px;
    gap: 15px;

    .avatar {
      align-self: flex-start;
    }

    .user-info {
      text-align: left;
      flex: 1;

      .name,
      .gender,
      .tel,
      .balance,
      .nickname,
      .openid {
        font-size: 14px;
        color: #606266;
        margin-bottom: 6px;
        line-height: 1.5;
      }

      .name,
      .nickname {
        font-weight: 500;
        color: #303133;
      }
    }

  }

  .idnum,
  .address {
    font-size: 13px;
    color: #606266;
    margin: 4px 0;
    line-height: 1.5;
    word-break: break-all;
  }

}

.grid-container {
  margin: 12px 0;
  padding-bottom: 0px;
  position: relative;

  .el-row {
    margin-bottom: -20px;
  }
}

.pagination-wrapper {
  position: relative;
  background: var(--el-bg-color);
  padding: 9px 12px;
  margin-top: 20px;
  text-align: center;

  :deep(.el-pagination) {
    margin: 0;
    padding: 0;
  }
}

.space-item {
  flex: 1;
  width: 100%;
}
</style>