<template>
  <div class="page-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">用户管理</span>
          <div class="header-actions">
            <el-select v-model="searchForm.areaId" placeholder="所属区域" style="width: 150px; margin-right: 10px" clearable @change="onSearchAreaChange">
              <el-option v-for="area in areaList" :key="area.id" :label="area.name" :value="area.id" />
            </el-select>
            <el-select v-model="searchForm.stationId" placeholder="所属站点" style="width: 150px; margin-right: 10px" clearable @change="handleSearch">
              <el-option v-for="station in filteredStationList" :key="station.id" :label="station.name" :value="station.id" />
            </el-select>
            <el-input v-model="searchForm.keyword" placeholder="搜索姓名/手机号" style="width: 200px; margin-right: 10px;" clearable @keyup.enter="handleSearch" @clear="handleSearch" />
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['archieves:customer:add']">新增用户</el-button>
          </div>
        </div>
      </template>

      <el-table :data="tableData" v-loading="loading" style="width: 100%" :header-cell-style="{ background: '#f5f7fa' }">
        <el-table-column label="用户基本信息" width="250">
          <template #default="scope">
            <div style="display: flex; align-items: center;">
              <el-avatar :size="40" :src="scope.row.avatarUrl" style="margin-right: 10px;" />
              <div>
                <div style="font-weight: bold;">{{ scope.row.name }}
                  <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
                </div>
                <div style="font-size: 12px; color: #999;">{{ scope.row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="住址" show-overflow-tooltip min-width="150">
          <template #default="scope">
            {{ [scope.row.regionCode ? scope.row.regionCode.split('/').map(c => codeToText[c] || '').filter(Boolean).join(' ') : '', scope.row.address].filter(Boolean).join(' ') || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="用户标签" width="200">
          <template #default="scope">
            <el-tag v-for="tag in scope.row.tags" :key="tag.id" :type="tag.colorType || 'info'" effect="light" size="small" style="margin-right: 5px;">{{ tag.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="录入信息" width="200">
          <template #default="scope">
            <div><el-tag size="small" effect="plain" :type="scope.row.source && scope.row.source.includes('平台') ? '' : 'warning'">{{ scope.row.source || '-' }}</el-tag></div>
            <div style="font-size: 12px; color: #999; margin-top: 4px;">{{ scope.row.createTime }}</div>
          </template>
        </el-table-column>
        <el-table-column label="订单数量" width="120" align="center" sortable prop="orderCount">
          <template #default="scope">
            <div>{{ scope.row.orderCount }}单</div>
          </template>
        </el-table-column>
        <el-table-column prop="petCount" label="关联宠物" width="100" align="center">
          <template #default="scope">
            <el-tag size="small" round>{{ scope.row.petCount }}只</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="0"
              :inactive-value="1"
              inline-prompt
              active-text="正常"
              inactive-text="停用"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleDetail(scope.row)" v-hasPermi="['archieves:customer:query']">详情</el-button>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)" v-hasPermi="['archieves:customer:edit']">编辑</el-button>
            <el-dropdown trigger="click" @command="(cmd) => handleCommand(cmd, scope.row)" style="margin-left: 10px; vertical-align: middle">
              <el-button link type="primary" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="remark" v-hasPermi="['archieves:customer:edit']">添加备注</el-dropdown-item>
                  <el-dropdown-item command="delete" style="color: #F56C6C" v-hasPermi="['archieves:customer:remove']">删除用户</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="getList"
          @current-change="getList"
        />
      </div>
    </el-card>

    <!-- User Detail Drawer -->
    <el-drawer v-model="drawerVisible" title="用户档案详情" size="60%" destroy-on-close>
      <div class="profile-header">
        <el-avatar :size="80" :src="currentUser.avatarUrl" />
        <div class="profile-basic">
          <div class="name-row">
            <span class="name">{{ currentUser.name }}</span>
            <dict-tag :options="sys_user_sex" :value="currentUser.gender" />
            <span class="phone">{{ currentUser.phone }}</span>
          </div>
          <div class="tags-row" style="margin-top: 8px">
            <el-tag v-for="tag in currentUser.tags" :key="tag.id" :type="tag.colorType || 'info'" effect="light" size="small" style="margin-right: 5px">
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
      </div>

      <el-tabs v-model="detailActiveTab" class="profile-tabs">
        <el-tab-pane label="档案信息" name="info">
          <div class="section-title">基本信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">{{ currentUser.name }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ currentUser.phone }}</el-descriptions-item>
            <el-descriptions-item label="所属区域">{{ currentUser.areaName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="所属站点">{{ currentUser.stationName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="录入来源">{{ currentUser.source || '-' }}</el-descriptions-item>
            <el-descriptions-item label="录入时间">{{ currentUser.createTime || '-' }}</el-descriptions-item>
          </el-descriptions>

          <div class="section-title" style="margin-top: 20px">居住信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="详细住址" :span="2">{{ currentUser.address }}</el-descriptions-item>
            <el-descriptions-item label="房屋类型">
              <dict-tag :options="sys_house_type" :value="currentUser.houseType" />
            </el-descriptions-item>
            <el-descriptions-item label="入门方式">
              <dict-tag :options="sys_entry_method" :value="currentUser.entryMethod" />
            </el-descriptions-item>
            <el-descriptions-item label="开门详情" :span="2">
              {{ currentUser.entryMethod === 'password' ? currentUser.entryPassword : currentUser.keyLocation }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="宠物列表" name="pets">
          <div style="margin-bottom: 15px;">
            <el-button type="primary" size="small" icon="Plus" @click="openAddPet">新增宠物</el-button>
          </div>
          <el-table :data="currentPets" border style="width: 100%">
            <el-table-column label="宠物信息" width="200">
              <template #default="scope">
                <div style="display: flex; align-items: center;">
                  <el-avatar :size="30" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" style="margin-right: 8px;" />
                  {{ scope.row.name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="breed" label="品种" />
            <el-table-column prop="gender" label="性别" width="60" />
            <el-table-column prop="age" label="年龄" width="60" />
            <el-table-column prop="status" label="健康状态">
              <template #default="scope">
                <el-tag :type="scope.row.status === '健康' ? 'success' : 'warning'" size="small">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="疫苗接种" width="120" align="center">
              <template #default="scope">
                {{ scope.row.vaccine || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template #default="scope">
                <el-button link type="primary" @click="handlePetDetail(scope.row)">详情</el-button>
                <el-button link type="primary" @click="handlePetEdit(scope.row)">编辑</el-button>
                <el-button link type="primary" @click="handlePetRemark(scope.row)">备注</el-button>
                <el-button link type="danger" @click="handlePetDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="历史订单" name="orders">
          <el-table :data="mockOrders" border style="width: 100%">
            <el-table-column prop="orderNo" label="订单编号" width="180" />
            <el-table-column prop="service" label="服务项目" />
            <el-table-column prop="pets" label="服务宠物" />
            <el-table-column prop="time" label="服务时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag type="success" size="small">完成</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="档案日志" name="logs">
          <el-timeline style="margin-top: 10px; padding-left: 5px;">
            <el-timeline-item
              v-for="(log, index) in changeLogs"
              :key="index"
              :timestamp="log.createTime"
              type="primary"
            >
              [{{ log.changeType }}] {{ log.content }}
              <div style="font-size: 12px; color: #999; margin-top: 4px">操作人: {{ log.operatorName }}</div>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

    <!-- Add/Edit User Dialog -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="700px" destroy-on-close>
      <el-form :model="form" label-width="90px" class="user-form">
        <el-row :gutter="20">
          <el-col :span="24" style="text-align: center; margin-bottom: 25px;">
            <el-upload action="#" :show-file-list="false" :auto-upload="false" :on-change="handleUserUploadFile">
              <el-avatar :size="80" :src="userAvatarDisplayUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" class="upload-avatar" />
              <div style="margin-top: 8px; font-size: 12px; color: #409EFF;">点击修改头像</div>
            </el-upload>
          </el-col>

          <el-col :span="24"><div class="form-section-header">基本资料</div></el-col>
          <el-col :span="12">
            <el-form-item label="录入来源">
              <PageSelect v-model="form.source"
                :options="brandList.map(item => ({ value: item.name, label: item.name }))"
                :total="brandTotal" :pageSize="10" placeholder="请选择所属品牌"
                @page-change="handleBrandPageChange"
                @visible-change="handleBrandVisibleChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域">
              <el-cascader v-model="formAreaValue" :options="areaTreeOptions" placeholder="请选择区域"
                style="width: 100%" clearable @change="handleFormAreaChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属站点">
              <el-select v-model="form.stationId" style="width: 100%" filterable placeholder="请选择站点" clearable :disabled="!form.areaId">
                <el-option v-for="station in formStationList" :key="station.id" :label="station.name" :value="station.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" required><el-input v-model="form.name" placeholder="请输入姓名" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" required><el-input v-model="form.phone" placeholder="请输入电话" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24"><div class="form-section-header">居住信息</div></el-col>
          <el-col :span="24">
            <el-form-item label="所在地区">
              <el-cascader
                v-model="regionCascaderValue"
                :options="regionData"
                placeholder="请选择省/市/区"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细住址"><el-input v-model="form.address" placeholder="请输入街道/门牌号" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房屋类型">
              <el-radio-group v-model="form.houseType">
                <el-radio v-for="dict in sys_house_type" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入门方式">
              <el-radio-group v-model="form.entryMethod">
                <el-radio v-for="dict in sys_entry_method" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.entryMethod === 'password'">
            <el-form-item label="开门密码">
              <el-input v-model="form.entryPassword" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.entryMethod === 'key'">
            <el-form-item label="钥匙位置">
              <el-input v-model="form.keyLocation" placeholder="如：地毯下" />
            </el-form-item>
          </el-col>

          <el-col :span="24"><div class="form-section-header">其他</div></el-col>
          <el-col :span="24">
            <el-form-item label="用户标签">
              <el-select v-model="selectedTagIds" multiple placeholder="选择标签" style="width: 100%">
                <el-option v-for="tag in allUserTags" :key="tag.id" :label="tag.name" :value="tag.id">
                  <el-tag :type="tag.colorType || 'info'" effect="light" size="small">{{ tag.name }}</el-tag>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注说明"><el-input type="textarea" v-model="form.remark" rows="3" /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: center; margin-top: 20px;">
        <el-button @click="dialogVisible = false" size="large" style="width: 120px;">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="saveUser" size="large" style="width: 120px;">保存</el-button>
      </div>
    </el-dialog>

    <!-- Remark Dialog -->
    <el-dialog v-model="remarkDialogVisible" title="添加备注" width="400px">
      <el-input v-model="remarkForm.content" type="textarea" :rows="3" placeholder="请输入备注内容..." />
      <template #footer>
            <span class="dialog-footer">
                <el-button @click="remarkDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveRemark">保存</el-button>
            </span>
      </template>
    </el-dialog>

    <!-- Full Add/Edit Pet Dialog -->
    <el-dialog v-model="petDialogVisible" :title="petForm.id ? '编辑宠物' : '新增宠物'" width="800px">
      <el-tabs v-model="petDialogActiveTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-form :model="petForm" label-width="100px">
            <el-row>
              <el-col :span="24" style="display: flex; justify-content: center; margin-bottom: 20px;">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handlePetUploadFile"
                >
                  <el-avatar v-if="petAvatarDisplayUrl" :src="petAvatarDisplayUrl" :size="80" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-col>
              <el-col :span="12">
                <el-form-item label="宠物姓名" required><el-input v-model="petForm.name" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别">
                  <el-select v-model="petForm.gender" placeholder="请选择">
                    <el-option v-for="dict in sys_pet_gender" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品种">
                  <el-select v-model="petForm.breed" placeholder="请选择品种" style="width: 100%" filterable allow-create default-first-option>
                    <el-option v-for="dict in sys_pet_breed" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="体型">
                  <el-select v-model="petForm.size" style="width: 100%">
                    <el-option label="小型" value="small" />
                    <el-option label="中型" value="medium" />
                    <el-option label="大型" value="large" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="体重(kg)"><el-input-number v-model="petForm.weight" :min="0" :precision="1" style="width: 100%" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄(岁)"><el-input-number v-model="petForm.age" :min="0" style="width: 100%" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="性格关键词"><el-input v-model="petForm.personality" placeholder="如：活泼、粘人" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="萌宠性格"><el-input v-model="petForm.cutePersonality" type="textarea" placeholder="详细描述" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="宠物标签">
                  <el-select v-model="petForm.tagIds" multiple placeholder="选择标签" style="width: 100%">
                    <el-option v-for="tag in allPetTags" :key="tag.id" :label="tag.name" :value="tag.id">
                      <el-tag :type="tag.colorType || 'info'" effect="light" size="small">{{ tag.name }}</el-tag>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="家庭信息" name="family">
          <el-form :model="petForm" label-width="120px">
            <el-form-item label="新来家庭时间">
              <el-date-picker v-model="petForm.arrivalTime" type="date" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
            <el-form-item label="家庭房屋类型">
              <el-radio-group v-model="petForm.houseType">
                <el-radio label="stairs">楼梯</el-radio>
                <el-radio label="elevator">电梯</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="入门方式">
              <el-radio-group v-model="petForm.entryMethod">
                <el-radio label="password">密码开门</el-radio>
                <el-radio label="key">钥匙开门</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="密码" v-if="petForm.entryMethod === 'password'">
              <el-input v-model="petForm.entryPassword" placeholder="请输入门锁密码" />
            </el-form-item>
            <el-form-item label="钥匙位置" v-if="petForm.entryMethod === 'key'">
              <el-input v-model="petForm.keyLocation" placeholder="请输入钥匙存放位置" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="健康状况" name="health">
          <el-form :model="petForm" label-width="120px">
            <el-form-item label="健康状态">
              <el-radio-group v-model="petForm.healthStatus">
                <el-radio label="健康">健康</el-radio>
                <el-radio label="亚健康">亚健康</el-radio>
                <el-radio label="疾病">疾病</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否有攻击倾向">
              <el-switch v-model="petForm.aggression" active-text="是" inactive-text="否" :active-value="1" :inactive-value="0" />
            </el-form-item>
            <el-form-item label="疫苗情况">
              <el-radio-group v-model="petForm.vaccine">
                <el-radio label="无">无</el-radio>
                <el-radio label="已打1次">已打1次</el-radio>
                <el-radio label="已打2次">已打2次</el-radio>
                <el-radio label="已打3次">已打3次</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="疫苗凭证">
              <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false" :on-change="handlePetUploadVaccineCert">
                <img v-if="petVaccineCertDisplayUrl" :src="petVaccineCertDisplayUrl" class="avatar" style="width: 100px; height: 100px; object-fit: cover;" />
                <el-icon v-else class="avatar-uploader-icon" style="width: 100px; height: 100px; line-height: 100px;"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="既往病史">
              <el-input v-model="petForm.medicalHistory" type="textarea" placeholder="如有病史请记录" />
            </el-form-item>
            <el-form-item label="过敏史">
              <el-input v-model="petForm.allergies" type="textarea" placeholder="如有过敏源请记录" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
            <span class="dialog-footer">
                <el-button @click="petDialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="submitLoading" @click="savePet">保存</el-button>
            </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance, toRefs } from 'vue'
import { globalHeaders } from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listCustomer, getCustomer, addCustomer, updateCustomer, delCustomer, changeCustomerStatus } from '@/api/archieves/customer'
import { listAllTag } from '@/api/archieves/tag'
import { listPetByUser, addPet, updatePet, delPet } from '@/api/archieves/pet'
import { listAllChangeLog } from '@/api/archieves/changeLog'
import { listOnStore } from '@/api/system/areaStation'
import { listOnStore as listBrandOnStore } from '@/api/system/tenant'
import { regionData, codeToText } from 'element-china-area-data'
import PageSelect from '@/components/PageSelect/index.vue'

const { proxy } = getCurrentInstance()
const { sys_user_sex, sys_customer_status, sys_house_type, sys_entry_method, sys_pet_gender, sys_pet_size, sys_pet_type, sys_pet_breed } = toRefs(
  proxy?.useDict('sys_user_sex', 'sys_customer_status', 'sys_house_type', 'sys_entry_method', 'sys_pet_gender', 'sys_pet_size', 'sys_pet_type', 'sys_pet_breed')
)

const loading = ref(false)
const submitLoading = ref(false)
const total = ref(0)

const allNodes = ref([])
const areaList = computed(() => allNodes.value.filter(n => n.type === 1))
const filteredStationList = computed(() => {
  const areaId = searchForm.areaId
  const stations = allNodes.value.filter(n => n.type === 2)
  if (areaId) {
    return stations.filter(s => s.parentId === areaId)
  }
  return stations
})
const formStationList = computed(() => {
  const areaId = form.areaId
  const stations = allNodes.value.filter(n => n.type === 2)
  if (areaId) {
    return stations.filter(s => s.parentId === areaId)
  }
  return stations
})

const loadAreaStation = () => {
  listOnStore().then((res) => {
    allNodes.value = res.data || []
  })
}

const onSearchAreaChange = () => {
  searchForm.stationId = undefined
  handleSearch()
}

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  areaId: undefined,
  stationId: undefined,
  status: undefined
})

const searchForm = reactive({
  keyword: '',
  areaId: undefined,
  stationId: undefined
})

const dialogVisible = ref(false)
const drawerVisible = ref(false)
const remarkDialogVisible = ref(false)
const petDialogVisible = ref(false)
const isEdit = ref(false)
const detailActiveTab = ref('info')
const petDialogActiveTab = ref('basic')

const selectedTagIds = ref([])
const currentUser = ref({})
const currentPets = ref([])
const tableData = ref([])

const allUserTags = ref([])
const allPetTags = ref([])
const changeLogs = ref([])
const userAvatarDisplayUrl = ref('')
const petAvatarDisplayUrl = ref('')
const petVaccineCertDisplayUrl = ref('')

const brandList = ref([])
const brandTotal = ref(0)
const formAreaValue = ref([])
const regionCascaderValue = ref([])


const mockOrders = ref([
  { orderNo: 'DD20231001001', service: '上门喂养 (标准版)', pets: '旺财', time: '2023-10-01 10:00', amount: '88.00', status: 'completed' },
  { orderNo: 'DD20230915002', service: '深度洗护套餐', pets: '旺财, 咪咪', time: '2023-09-15 14:00', amount: '158.00', status: 'completed' }
])

const form = reactive({
  id: undefined,
  name: '',
  phone: '',
  avatar: undefined,
  gender: undefined,
  birthday: '',
  idCard: '',
  areaId: undefined,
  stationId: undefined,
  regionCode: '',
  region: [],
  address: '',
  houseType: '',
  entryMethod: '',
  entryPassword: '',
  keyLocation: '',
  source: '',
  emergencyContact: '',
  emergencyPhone: '',
  memberLevel: 0,
  status: 0,
  remark: '',
  tagIds: []
})

const petForm = reactive({
  id: undefined,
  userId: undefined,
  avatar: undefined,
  name: '',
  type: 0,
  gender: undefined,
  breed: '',
  birthday: '',
  age: 1,
  weight: 5,
  size: 'small',
  isSterilized: 0,
  arrivalTime: '',
  houseType: '',
  entryMethod: '',
  entryPassword: '',
  keyLocation: '',
  personality: '',
  cutePersonality: '',
  healthStatus: '',
  aggression: 0,
  vaccineStatus: '',
  vaccineCert: undefined,
  medicalHistory: '',
  allergies: '',
  remark: '',
  tagIds: []
})

const remarkForm = reactive({ content: '' })

const areaTreeOptions = computed(() => {
  const buildTree = (data, parentId) => {
    return data
      .filter(item => String(item.parentId) === String(parentId))
      .map(item => {
        const children = buildTree(data, item.id)
        const node = { value: item.id, label: item.name }
        if (children.length > 0) node.children = children
        return node
      })
  }
  const areaData = allNodes.value.filter(n => n.type === 0 || n.type === 1)
  return buildTree(areaData, 0)
})

const handleFormAreaChange = (value) => {
  form.stationId = undefined
  if (value && value.length > 0) {
    form.areaId = value[value.length - 1]
  } else {
    form.areaId = undefined
  }
}

const getBrandList = async (pageNum = 1) => {
  const res = await listBrandOnStore({ pageNum, pageSize: 10 })
  if (res.code === 200) {
    brandList.value = res.rows || []
    brandTotal.value = res.total || 0
  }
}

const handleBrandPageChange = (page) => {
  getBrandList(Number(page))
}

const handleBrandVisibleChange = (visible) => {
  if (visible) {
    getBrandList(1)
  }
}

const getList = () => {
  loading.value = true
  queryParams.keyword = searchForm.keyword
  queryParams.areaId = searchForm.areaId || undefined
  queryParams.stationId = searchForm.stationId || undefined
  listCustomer(queryParams).then((res) => {
    tableData.value = res.rows
    total.value = res.total
  }).finally(() => {
    loading.value = false
  })
}

const handleSearch = () => {
  queryParams.pageNum = 1
  getList()
}

const loadTags = () => {
  listAllTag({ category: 'user', status: 0 }).then((res) => {
    allUserTags.value = res.data || []
  }).catch((err) => {
    console.error('加载用户标签失败', err)
  })
  listAllTag({ category: 'pet', status: 0 }).then((res) => {
    allPetTags.value = res.data || []
  }).catch((err) => {
    console.error('加载宠物标签失败', err)
  })
}

const handleAdd = () => {
  isEdit.value = false
  selectedTagIds.value = []
  Object.assign(form, {
    id: undefined, name: '', phone: '', avatar: undefined, gender: undefined, birthday: '', idCard: '',
    areaId: undefined, stationId: undefined, regionCode: '', region: [], address: '',
    houseType: '', entryMethod: '', entryPassword: '', keyLocation: '', source: '',
    emergencyContact: '', emergencyPhone: '', memberLevel: 0, status: 0, remark: '', tagIds: []
  })
  userAvatarDisplayUrl.value = ''
  formAreaValue.value = []
  regionCascaderValue.value = []
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  getCustomer(row.id).then((res) => {
    const data = res.data
    Object.assign(form, {
      id: data.id, name: data.name, phone: data.phone, avatar: data.avatar, gender: data.gender,
      birthday: data.birthday, idCard: data.idCard, areaId: data.areaId, stationId: data.stationId,
      regionCode: data.regionCode, region: data.regionCode ? data.regionCode.split('/') : [],
      address: data.address, houseType: data.houseType, entryMethod: data.entryMethod,
      entryPassword: data.entryPassword, keyLocation: data.keyLocation, source: data.source,
      emergencyContact: data.emergencyContact, emergencyPhone: data.emergencyPhone,
      memberLevel: data.memberLevel, status: data.status, remark: data.remark, tagIds: []
    })
    userAvatarDisplayUrl.value = data.avatarUrl || ''
    // Restore area cascader value path
    if (data.areaId) {
      const findPath = (nodes, targetId, path = []) => {
        for (const node of nodes) {
          const currentPath = [...path, node.id]
          if (node.id === targetId) return currentPath
          const children = allNodes.value.filter(n => (n.type === 0 || n.type === 1) && String(n.parentId) === String(node.id))
          if (children.length > 0) {
            const result = findPath(children, targetId, currentPath)
            if (result) return result
          }
        }
        return null
      }
      const roots = allNodes.value.filter(n => (n.type === 0 || n.type === 1) && String(n.parentId) === '0')
      formAreaValue.value = findPath(roots, data.areaId) || []
    } else {
      formAreaValue.value = []
    }
    // Restore region cascader value
    regionCascaderValue.value = data.regionCode ? data.regionCode.split('/') : []
    selectedTagIds.value = data.tags ? data.tags.map(t => t.id) : []
    dialogVisible.value = true
  })
}

const handleDetail = (row) => {
  getCustomer(row.id).then((res) => {
    const data = res.data
    // Convert areaId to area name
    if (data.areaId) {
      const area = allNodes.value.find(n => n.id === data.areaId)
      data.areaName = area ? area.name : '-'
    } else {
      data.areaName = '-'
    }
    // Convert stationId to station name
    if (data.stationId) {
      const station = allNodes.value.find(n => n.id === data.stationId)
      data.stationName = station ? station.name : '-'
    } else {
      data.stationName = '-'
    }
    currentUser.value = data
    detailActiveTab.value = 'info'
    loadDetailPets(row.id)
    loadDetailLogs(row.id, 'customer')
    drawerVisible.value = true
  })
}

const loadDetailPets = (userId) => {
  listPetByUser(userId).then((res) => {
    currentPets.value = res.data || []
  })
}

const loadDetailLogs = (targetId, targetType) => {
  listAllChangeLog(targetId, targetType).then((res) => {
    changeLogs.value = res.data || []
  })
}

const handleRemark = (row) => {
  currentUser.value = row
  remarkForm.content = ''
  remarkDialogVisible.value = true
}

const saveRemark = () => {
  if (!remarkForm.content) return ElMessage.warning('请输入内容')
  // For now, update customer remark via API
  const data = { 
    id: currentUser.value.id, 
    name: currentUser.value.name,
    phone: currentUser.value.phone,
    remark: remarkForm.content 
  }
  updateCustomer(data).then(() => {
    ElMessage.success('备注添加成功')
    remarkDialogVisible.value = false
    getList()
  })
}

const saveUser = () => {
  if (!form.name) return ElMessage.warning('请输入姓名')
  if (!form.phone) return ElMessage.warning('请输入电话')
  submitLoading.value = true
  form.tagIds = selectedTagIds.value
  if (regionCascaderValue.value && regionCascaderValue.value.length > 0) {
    form.regionCode = regionCascaderValue.value.join('/')
  } else {
    form.regionCode = ''
  }
  const api = isEdit.value ? updateCustomer(form) : addCustomer(form)
  api.then(() => {
    ElMessage.success('保存成功')
    dialogVisible.value = false
    getList()
  }).finally(() => {
    submitLoading.value = false
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户档案吗?', '提示', { type: 'warning' }).then(() => {
    delCustomer(row.id).then(() => {
      ElMessage.success('删除成功')
      getList()
    })
  })
}

const handleStatusChange = (row) => {
  const statusText = row.status === 0 ? '启用' : '停用'
  ElMessageBox.confirm(`确认${statusText}用户 "${row.name}" 吗?`, '提示', { type: 'warning' }).then(() => {
    changeCustomerStatus(row.id, row.status).then(() => {
      ElMessage.success(`${statusText}成功`)
    })
  }).catch(() => {
    row.status = row.status === 0 ? 1 : 0
  })
}

const handleCommand = (command, row) => {
  if (command === 'remark') {
    handleRemark(row)
  } else if (command === 'delete') {
    handleDelete(row)
  }
}

const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadUrl = baseUrl + '/resource/oss/upload'

const handleUserUploadFile = async (file) => {
  const formData = new FormData()
  formData.append('file', file.raw)
  try {
    const headers = globalHeaders()
    const res = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Authorization': headers.Authorization,
        'clientid': headers.clientid
      },
      body: formData
    })
    const result = await res.json()
    if (result.code === 200) {
      form.avatar = result.data.ossId
      userAvatarDisplayUrl.value = result.data.url
    } else {
      ElMessage.error(result.msg || '头像上传失败')
    }
  } catch (e) {
    ElMessage.error('头像上传失败')
  }
}

const handlePetUploadFile = async (file) => {
  const formData = new FormData()
  formData.append('file', file.raw)
  try {
    const headers = globalHeaders()
    const res = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Authorization': headers.Authorization,
        'clientid': headers.clientid
      },
      body: formData
    })
    const result = await res.json()
    if (result.code === 200) {
      petForm.avatar = result.data.ossId
      petAvatarDisplayUrl.value = result.data.url
    } else {
      ElMessage.error(result.msg || '头像上传失败')
    }
  } catch (e) {
    ElMessage.error('头像上传失败')
  }
}
const handlePetUploadVaccineCert = async (file) => {
  const formData = new FormData()
  formData.append('file', file.raw)
  try {
    const headers = globalHeaders()
    const res = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Authorization': headers.Authorization,
        'clientid': headers.clientid
      },
      body: formData
    })
    const result = await res.json()
    if (result.code === 200) {
      petForm.vaccineCert = result.data.ossId
      petVaccineCertDisplayUrl.value = result.data.url
    } else {
      ElMessage.error(result.msg || '疫苗凭证上传失败')
    }
  } catch (e) {
    ElMessage.error('疫苗凭证上传失败')
  }
}

const openAddPet = () => {
  petDialogActiveTab.value = 'basic'
  Object.assign(petForm, {
    id: undefined, userId: currentUser.value.id, avatar: undefined, name: '', type: 0, gender: undefined,
    breed: '', birthday: '', age: 1, weight: 5, size: 'small', isSterilized: 0,
    arrivalTime: '', houseType: '', entryMethod: '', entryPassword: '', keyLocation: '',
    personality: '', cutePersonality: '', healthStatus: '健康', aggression: 0,
    vaccineStatus: '无', vaccineCert: undefined, medicalHistory: '', allergies: '', remark: '', tagIds: []
  })
  petAvatarDisplayUrl.value = ''
  petVaccineCertDisplayUrl.value = ''
  petDialogVisible.value = true
}

const handlePetDetail = (row) => {
  ElMessage.info(`查看宠物 [${row.name}] 详情`)
}

const handlePetEdit = (row) => {
  petDialogActiveTab.value = 'basic'
  Object.assign(petForm, {
    id: row.id, userId: row.userId, avatar: row.avatar, name: row.name, type: row.type,
    gender: row.gender, breed: row.breed, birthday: row.birthday, age: row.age,
    weight: row.weight, size: row.size, isSterilized: row.isSterilized,
    arrivalTime: row.arrivalTime, houseType: row.houseType, entryMethod: row.entryMethod,
    entryPassword: row.entryPassword, keyLocation: row.keyLocation,
    personality: row.personality, cutePersonality: row.cutePersonality,
    healthStatus: row.healthStatus, aggression: row.aggression,
    vaccineStatus: row.vaccineStatus, vaccineCert: row.vaccineCert,
    medicalHistory: row.medicalHistory, allergies: row.allergies, remark: row.remark,
    tagIds: row.tags ? row.tags.map(t => t.id) : []
  })
  petAvatarDisplayUrl.value = row.avatarUrl || ''
  petVaccineCertDisplayUrl.value = row.vaccineCertUrl || ''
  petDialogVisible.value = true
}

const handlePetRemark = (row) => {
  remarkForm.content = `[宠物:${row.name}] `
  remarkDialogVisible.value = true
}

const handlePetDelete = (row) => {
  ElMessageBox.confirm(`确认删除宠物 [${row.name}] 吗?`, '提示', { type: 'warning' }).then(() => {
    delPet(row.id).then(() => {
      ElMessage.success('宠物删除成功')
      loadDetailPets(currentUser.value.id)
      getList()
    })
  })
}

const savePet = () => {
  if (!petForm.name) return ElMessage.warning('请输入宠物昵称')
  submitLoading.value = true
  const data = { ...petForm, aggression: Number(petForm.aggression) || 0 }
  const api = data.id ? updatePet(data) : addPet(data)
  api.then(() => {
    ElMessage.success('宠物档案保存成功')
    petDialogVisible.value = false
    loadDetailPets(currentUser.value.id)
    getList()
  }).finally(() => {
    submitLoading.value = false
  })
}

onMounted(() => {
  getList()
  loadTags()
  loadAreaStation()
  getBrandList()
})
</script>

<style scoped>
.page-container { padding: 20px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.title { font-weight: bold; }

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}
.profile-basic {
  margin-left: 20px;
}
.name-row {
  display: flex;
  align-items: center;
}
.name {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}
.phone {
  margin-left: 10px;
  color: #666;
}
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
  line-height: 1.2;
}

.form-section-header {
  font-weight: bold;
  margin-bottom: 15px;
  margin-top: 10px;
  padding-bottom: 5px;
  border-bottom: 1px dashed #eee;
  color: #303133;
}
.upload-avatar:hover {
  cursor: pointer;
  opacity: 0.8;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* Add Upload Styles */
.avatar-uploader .el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: .2s;
}
.avatar-uploader-icon:hover {
  border-color: #409EFF;
  color: #409EFF;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 4px;
}
</style>
