<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { type QyUserDTO, getQyUserDetailApi, updateQyUserApi } from "@/api/qy/qyUser";
import { getOrderListApi, type OrderDTO } from "@/api/shop/order";
import BalanceEditModal from "./BalanceEditModal.vue";
import { getRoleListApi, RoleDTO } from "@/api/system/role";

defineOptions({
  name: "QyUserDetail"
});

const route = useRoute();
const router = useRouter();
const userInfo = ref<QyUserDTO>({});
const loading = ref(false);
const balanceVisible = ref(false);
const roleVisible = ref(false);
const roleList = ref<RoleDTO[]>([]);
const selectedRoleId = ref<number>();

// 基础信息
const basicInfo = ref({
  registerTime: "",
  lastLogin: "",
  loginCount: 0,
  device: ""
});

// 订单记录
const orderRecords = ref<OrderDTO[]>([]);
const pagination = ref({
  pageSize: 5,
  currentPage: 1,
  total: 0
});
const orderLoading = ref(false);
const activeTab = ref('basic');

async function fetchOrders() {
  try {
    orderLoading.value = true;
    const { data } = await getOrderListApi({
      openid: userInfo.value.openid,
      userid: userInfo.value.userid,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    orderRecords.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    orderLoading.value = false;
  }
}

watch(activeTab, (newVal) => {
  if (newVal === 'orders') {
    fetchOrders();
  }
});

async function handleModifyRole() {
  try {
    const { data } = await getRoleListApi({});
    roleList.value = data.rows;
    selectedRoleId.value = userInfo.value.roleId;
    roleVisible.value = true;
  } catch (error) {
    console.error(error);
  }
}

async function handleRoleConfirm() {
  try {
    await updateQyUserApi(userInfo.value.id!, {
      ...userInfo.value,
      id: userInfo.value.id,
      roleId: selectedRoleId.value,
      sysRoleId: selectedRoleId.value
    });
    roleVisible.value = false;
    await fetchUserDetail();
  } catch (error) {
    console.error(error);
  }
}

async function fetchUserDetail() {
  try {
    loading.value = true;
    const userId = route.query.id;
    const { data } = await getQyUserDetailApi(Number(userId));
    userInfo.value = data;
    basicInfo.value.registerTime = data.createTimeStr || "";
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  fetchUserDetail();
});
async function handleModifyBalance(row: QyUserDTO) {
  balanceVisible.value = true;
}

</script>

<template>
  <div class="detail-container">
    <div class="flex-container">
      <el-card class="user-info-card">
        <div class="user-header">
          <el-avatar :size="100" :src="userInfo.avatar" fit="cover" shape="square">
            <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>
          </el-avatar>
          <div class="user-name">{{ userInfo.name }}</div>
        </div>

        <el-divider />

        <el-descriptions class="user-details" :column="1" border>
          <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ userInfo.mobile }}</el-descriptions-item>
          <!-- <el-descriptions-item label="借呗">¥{{ userInfo.balanceLimit?.toFixed(2) }}
            <el-button type="primary" size="small" @click="handleModifyBalance(userInfo)">
              修改
            </el-button>
          </el-descriptions-item>
          <el-descriptions-item label="已用借呗">{{ userInfo.useBalance?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="剩余借呗">¥{{ userInfo.balance?.toFixed(2) }}</el-descriptions-item> -->
        </el-descriptions>
      </el-card>
      <el-card class="info-card">
        <div class="tab-header">
          <el-tabs type="card" v-model="activeTab">
            <el-tab-pane label="基础信息" name="basic"></el-tab-pane>
            <el-tab-pane label="订单记录" name="orders"></el-tab-pane>
          </el-tabs>
        </div>

        <el-descriptions class="info-details" v-if="activeTab === 'basic'" :column="2" border>
          <el-descriptions-item label="角色">{{ userInfo.roleName }} <el-button type="primary" size="small"
              @click="handleModifyRole">修改</el-button></el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ userInfo.userid }}</el-descriptions-item>
          <el-descriptions-item label="企业ID">{{ userInfo.corpid }}</el-descriptions-item>
          <el-descriptions-item label="职务信息">{{ userInfo.position }}</el-descriptions-item>
        </el-descriptions>

        <div class="info-details" v-if="activeTab === 'orders'">
          <el-table v-loading="orderLoading" :data="orderRecords" row-key="orderId" border>
            <el-table-column label="订单ID" prop="orderId" width="120" />
            <el-table-column label="商品名称" prop="goodsNames" width="180" />
            <el-table-column label="订单金额" prop="totalAmount" width="120">
              <template #default="{ row }">{{ row.totalAmount }}元</template>
            </el-table-column>
            <el-table-column label="订单状态" prop="status" width="120">
              <template #default="{ row }">
                <el-tag :type="row.status === 2 ? 'success' : row.status === 5 ? 'danger' : 'info'">
                  {{ { 1: '待付款', 2: '已付款', 3: '已发货', 4: '已完成', 5: '已取消' }[row.status] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="支付时间" prop="payTime" width="180">
              <template #default="{ row }">
                {{ row.payTime ? new Date(row.payTime).toLocaleString() : '-' }}
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
            :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            @size-change="fetchOrders" @current-change="fetchOrders" />
        </div>
      </el-card>
    </div>
    <BalanceEditModal v-model:visible="balanceVisible" :row="userInfo" @refresh="fetchUserDetail" />
    <el-drawer v-model="roleVisible" title="修改角色" direction="rtl" size="30%">
      <el-select v-model="selectedRoleId" placeholder="请选择角色" style="width: 100%; margin: 20px 0">
        <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
      </el-select>
      <div style="padding: 20px; text-align: right">
        <el-button @click="roleVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRoleConfirm">确定</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.detail-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .flex-container {
    display: flex;
    flex: 1;
    gap: 20px;
    min-height: 0;

    .user-info-card {
      width: 20%;
    }

    .info-card {
      width: 80%;
    }
  }

  .user-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;

    .user-name {
      margin-top: 15px;
      font-size: 20px;
      font-weight: bold;
    }
  }

  .tab-header {
    margin-bottom: 0px;
  }
}
</style>