<template>
  <div class="agent-info-container">
    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 顶部提示信息 -->
      <div class="info-banner">
        <el-icon><InfoFilled /></el-icon>
        <span>代理的个人信息，可修改保存。如果代理需要续费充值，请联系右侧平台客服，为避免续费延期。</span>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧表单 -->
        <div class="form-section">
          <el-form ref="agentFormRef" :model="agentForm" :rules="rules" label-width="120px">
            <el-form-item label="代理人账号：" prop="userName">
              <el-input v-model="agentForm.userName" :disabled="true" />
            </el-form-item>

            <el-form-item label="登录密码：" prop="password">
              <el-input
                v-model="agentForm.password"
                type="password"
                placeholder="不输入则不修改(6-18位数字字母组合)"
                show-password
                :disabled="editBtn"
              />
            </el-form-item>

            <el-form-item label="代理类型：" prop="agentType">
              <el-select v-model="agentForm.agentType" placeholder="请选择代理类型" :disabled="true">
                <el-option label="一级代理人" value="1" />
                <el-option label="二级代理人" value="2" />
              </el-select>
            </el-form-item>

            <el-form-item label="发展门店数：" prop="storeCount">
              <el-input v-model="agentForm.storeCount" :disabled="true" />
            </el-form-item>

            <el-form-item label="到期时间：" prop="expireDate">
              <el-input v-model="agentForm.expireDate" :disabled="true" />
            </el-form-item>

            <el-form-item label="代理人姓名：" prop="nickName">
              <el-input v-model="agentForm.nickName" placeholder="请输入代理人姓名" :disabled="editBtn" />
            </el-form-item>

            <el-form-item label="代理人手机：" prop="phonenumber">
              <el-input v-model="agentForm.phonenumber" placeholder="请输入手机号" :disabled="editBtn" />
            </el-form-item>

            <el-form-item label="门店后台名称：" prop="storeName">
              <el-input v-model="agentForm.storeName" placeholder="请输入门店后台名称" :disabled="editBtn" />
            </el-form-item>

            <el-form-item label="门店后台网址：" prop="storeUrl">
              <el-input v-model="agentForm.storeUrl" placeholder="请输入门店后台网址" :disabled="editBtn" />
            </el-form-item>

            <!-- 保存按钮 -->
            <el-form-item>
              <el-button type="primary" :loading="loading" @click="handleSave" v-if="!editBtn"> &nbsp;&nbsp;&nbsp;保存&nbsp;&nbsp;&nbsp; </el-button>
              <el-button type="primary" @click="editBtn = false" v-if="editBtn"> &nbsp;&nbsp;&nbsp;编辑&nbsp;&nbsp;&nbsp; </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧客服信息 -->
        <div class="service-section">
          <div class="service-card">
            <h3>平台客服</h3>
            <div class="service-tip">如果需要续费充值，请联系右侧平台客服进行线下充值续期。</div>

            <div class="qr-code-container">
              <img :src="serviceInfo.qrCodeUrl" alt="客服二维码" class="qr-code" />
            </div>

            <div class="service-contact">
              <p>客服：{{ serviceInfo.serviceName }}</p>
              <p>电话：{{ serviceInfo.servicePhone }}</p>
            </div>
          </div>

          <!-- 门店后台登录 -->
          <div class="store-login-section">
            <h4>门店后台登录 <span class="required">*</span></h4>
            <div class="login-card">
              <div class="add-button" @click="handleAddStore">
                <el-icon><Plus /></el-icon>
                <p>使用白色透明背景</p>
              </div>
            </div>
          </div>

          <div class="store-login-section">
            <h4>门店后台应用 <span class="required">*</span></h4>
            <div class="login-card">
              <div class="add-button" @click="handleAddApp">
                <el-icon><Plus /></el-icon>
                <p>使用白色透明背景</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="AgentInfo" lang="ts">
import { getSysAgent, updateSysAgent } from '@/api/system/sysAgent';
import { getInfo } from '@/api/login';
import { InfoFilled, Plus } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(false);
const agentFormRef = ref<ElFormInstance>();
const editBtn = ref<boolean>(true);

// 代理信息表单
const agentForm = ref({
  userId: '',
  userName: '',
  password: '',
  agentType: '1',
  storeCount: '800',
  expireDate: '2024-05-18',
  nickName: '',
  phonenumber: '',
  storeName: '',
  storeUrl: ''
});

// 客服信息
const serviceInfo = ref({
  serviceName: '肖先生',
  servicePhone: '027-88886666',
  qrCodeUrl:
    'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0iI2Y1ZjVmNSIvPgogIDx0ZXh0IHg9IjYwIiB5PSI2MCIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjE0IiBmaWxsPSIjOTk5IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+5LqM57u055qEPC90ZXh0Pgo8L3N2Zz4K' // 默认占位图片
});

// 表单验证规则
const rules = ref({
  nickName: [{ required: true, message: '代理人姓名不能为空', trigger: 'blur' }],
  phonenumber: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,18}$/,
      message: '密码必须是6-18位数字字母组合',
      trigger: 'blur'
    }
  ]
} as any);

/** 获取当前用户代理信息 */
const getCurrentAgentInfo = async () => {
  try {
    loading.value = true;

    // 先获取当前用户信息
    const userInfo = await getInfo();
    const currentUserId = userInfo.data?.user?.userId;

    if (!currentUserId) {
      proxy?.$modal.msgError('无法获取当前用户信息');
      return;
    }

    // 获取代理详细信息
    const response = await getSysAgent(currentUserId);

    if (response.data) {
      const responseData = response.data as any;
      const userInfo = responseData.userInfo; // 用户信息在userInfo中
      const agentInfo = responseData; // 代理信息在顶层

      // 填充表单数据
      agentForm.value = {
        userId: userInfo?.userId || currentUserId,
        userName: userInfo?.userName || '',
        password: '',
        agentType: '1', // 根据实际数据设置
        storeCount: '800', // 根据实际数据设置
        expireDate: agentInfo?.expireDate || '2024-05-18',
        nickName: userInfo?.nickName || '',
        phonenumber: userInfo?.phonenumber || '',
        storeName: '维克美业管理', // 根据实际数据设置
        storeUrl: 'https://www.mzm.com?d=23/login.html' // 根据实际数据设置
      };
    }
  } catch (error) {
    console.error('获取代理信息失败:', error);
    proxy?.$modal.msgError('获取代理信息失败');
  } finally {
    loading.value = false;
  }
};

/** 保存代理信息 */
const handleSave = async () => {
  try {
    await agentFormRef.value?.validate();
    loading.value = true;

    // 构造保存数据
    const saveData = {
      user: {
        userId: agentForm.value.userId,
        userName: agentForm.value.userName,
        nickName: agentForm.value.nickName,
        phonenumber: agentForm.value.phonenumber,
        password: agentForm.value.password || undefined // 如果密码为空则不传递
      },
      agent: {
        userId: agentForm.value.userId
        // 其他代理相关字段
      }
    };

    await updateSysAgent(saveData);
    proxy?.$modal.msgSuccess('保存成功');
    editBtn.value = true; // 保存后回到查看模式

    // 重新获取最新数据
    await getCurrentAgentInfo();
  } catch (error) {
    console.error('保存失败:', error);
    proxy?.$modal.msgError('保存失败');
  } finally {
    loading.value = false;
  }
};

/** 添加门店后台登录 */
const handleAddStore = () => {
  proxy?.$modal.msg('添加门店后台登录功能开发中...');
};

/** 添加门店后台应用 */
const handleAddApp = () => {
  proxy?.$modal.msg('添加门店后台应用功能开发中...');
};

onMounted(() => {
  getCurrentAgentInfo();
});
</script>

<style scoped lang="scss">
.agent-info-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content-area {
  padding: 20px;
}

.info-banner {
  display: flex;
  align-items: center;
  background-color: #e1f3ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
  color: #0066cc;

  .el-icon {
    margin-right: 8px;
    font-size: 16px;
  }

  span {
    font-size: 14px;
  }
}

.main-content {
  display: flex;
  gap: 30px;
  background-color: #ffffff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-section {
  flex: 1;
  max-width: 600px;

  .el-form-item {
    margin-bottom: 24px;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #303133;
    }

    :deep(.el-input) {
      width: 100%;
    }

    :deep(.el-select) {
      width: 100%;
    }
  }
}

.service-section {
  width: 300px;

  .service-card {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    margin-bottom: 20px;

    h3 {
      margin: 0 0 10px 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }

    .service-tip {
      font-size: 12px;
      color: #909399;
      margin-bottom: 20px;
      line-height: 1.4;
    }

    .qr-code-container {
      margin: 20px 0;

      .qr-code {
        width: 120px;
        height: 120px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
      }
    }

    .service-contact {
      p {
        margin: 5px 0;
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .store-login-section {
    margin-bottom: 20px;

    h4 {
      margin: 0 0 10px 0;
      font-size: 14px;
      color: #303133;

      .required {
        color: #f56c6c;
      }
    }

    .login-card {
      border: 2px dashed #d3d3d3;
      border-radius: 8px;
      padding: 20px;
      text-align: center;
      background-color: #fafafa;

      .add-button {
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          color: #409eff;
          border-color: #409eff;
        }

        .el-icon {
          font-size: 24px;
          color: #c0c4cc;
          margin-bottom: 8px;
        }

        p {
          margin: 0;
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    gap: 20px;
  }

  .service-section {
    width: 100%;
  }
}
</style>
