<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <wd-navbar :bordered="false"
      custom-style="background: transparent !important; backdrop-filter: blur(10px) !important; -webkit-backdrop-filter: blur(20px) !important;"
      safeAreaInsetTop fixed placeholder>
      <template #left>
        <view class="li-ml-15 li-mt-10 li-flex li-items-center">
          <text class="ri-arrow-left-s-line li-text-70" @click="goBack"></text>
          <text class="li-text-42">添加员工</text>
        </view>
      </template>
    </wd-navbar>
    <!-- 导航栏背景 -->
    <view class="nav-bg-layer"></view>
    
    <!-- 页面背景 -->
    <view class="page-bg"></view>

    <view class="content">
      <!-- 表单区域 -->
      <wd-form ref="form" :model="formData" :rules="rules" class="form-wrapper">
        <wd-cell-group border class="form-card">
          <wd-input
            v-model="formData.name"
            label="员工姓名"
            placeholder="请输入姓名"
            prop="name"
            label-width="100px"
            clearable
          />
          <wd-input
            v-model="formData.phone"
            label="手机号码"
            type="number"
            placeholder="请输入手机号"
            prop="phone"
            label-width="100px"
            clearable
          />
          <wd-input
            v-model="formData.password"
            label="初始密码"
            placeholder="123456"
            prop="password"
            label-width="100px"
            disabled
          />
          <wd-cell
            title="所属小区"
            :value="villageName"
            @click="showVillagePopup = true"
            is-link
            title-width="100px"
          />
          <wd-cell
            title="权限设置"
            @click="openPermissionPopup"
            is-link
            title-width="100px"
          >
            <view class="permission-summary">
              <text>{{ getPermissionSummary() }}</text>
            </view>
          </wd-cell>
        </wd-cell-group>
        
        <!-- 提交按钮 -->
        <view class="submit-btn-wrapper">
          <wd-button type="primary" block @click="submitForm" custom-style="background: linear-gradient(135deg, #42a5ff, #0070F0);">创建员工</wd-button>
        </view>
      </wd-form>
      
      <!-- 选择小区弹窗 -->
      <wd-popup v-model="showVillagePopup" position="bottom" title="选择小区" round>
        <view class="village-popup">
          <view 
            v-for="(item, index) in villages" 
            :key="index" 
            class="village-item"
            :class="{ active: formData.villageId === item.id }"
            @click="selectVillage(item)"
          >
            <view class="village-name">{{ item.name }}</view>
            <view class="village-check">
              <text class="ri-checkbox-circle-fill" v-if="formData.villageId === item.id"></text>
            </view>
          </view>
        </view>
      </wd-popup>
      
      <!-- 权限设置弹窗 -->
      <wd-popup v-model="showPermissionPopup" position="bottom" custom-style="border-radius: 20rpx 20rpx 0 0;" :safe-area-inset-bottom="true">
        <permission-settings 
          :staff="staffWithPermissions" 
          :permissions="allPermissions"
          @save="savePermissions"
          @cancel="closePermissionPopup"
        />
      </wd-popup>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue';
import { useNavigation } from '@/hooks/useNavigation';
import PermissionSettings from '@/components/PermissionSettings.vue';

// 导航相关
const { toPages } = useNavigation();

// 表单引用
const form = ref(null);

// 表单数据
const formData = reactive({
  name: '',
  phone: '',
  password: '123456',
  villageId: '',
  permissions: []
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入员工姓名' }
  ],
  phone: [
    { required: true, message: '请输入手机号码' },
    { pattern: /^1\d{10}$/, message: '手机号格式不正确' }
  ],
  password: [
    { required: true, message: '默认初始密码' }
  ]
};

// 小区数据
const villages = ref([
  { id: '1', name: '阳光花园小区' },
  { id: '2', name: '幸福家园小区' },
  { id: '3', name: '时代广场小区' }
]);

// 显示小区选择弹窗
const showVillagePopup = ref(false);

// 当前选中的小区名称
const villageName = computed(() => {
  const village = villages.value.find(v => v.id === formData.villageId);
  return village ? village.name : '请选择';
});

// 选择小区
const selectVillage = (village) => {
  formData.villageId = village.id;
  showVillagePopup.value = false;
};

// 权限弹窗
const showPermissionPopup = ref(false);

// 权限数据，用于传递给权限设置组件
const staffWithPermissions = computed(() => {
  return {
    name: formData.name || '新员工',
    permissions: formData.permissions
  };
});

// 所有权限列表
const allPermissions = [
  { value: 'delivery', label: '配送权限', icon: 'ri-truck-line', description: '允许配送相关的订单处理', colorClass: 'delivery-color', isCommon: true },
  { value: 'maintenance', label: '维修权限', icon: 'ri-tools-line', description: '允许接受维修工单和处理', colorClass: 'maintenance-color', isCommon: true },
  { value: 'finance', label: '财务管理', icon: 'ri-money-cny-circle-line', description: '允许处理财务相关事务', colorClass: 'finance-color', isCommon: true },
  { value: 'resident', label: '住户管理', icon: 'ri-user-line', description: '允许管理小区住户信息', colorClass: 'general-color', isCommon: false },
  { value: 'security', label: '安防权限', icon: 'ri-shield-line', description: '允许管理小区安防系统', colorClass: 'general-color', isCommon: false },
  { value: 'admin', label: '管理员权限', icon: 'ri-admin-line', description: '系统管理员权限', colorClass: 'admin-color', isCommon: false },
  { value: 'parking', label: '车位管理', icon: 'ri-parking-line', description: '允许管理小区车位', colorClass: 'general-color', isCommon: false },
  { value: 'visitor', label: '访客管理', icon: 'ri-user-location-line', description: '允许管理小区访客', colorClass: 'general-color', isCommon: false },
  { value: 'complaint', label: '投诉处理', icon: 'ri-customer-service-line', description: '允许处理业主投诉', colorClass: 'general-color', isCommon: true },
  { value: 'facility', label: '设施管理', icon: 'ri-building-4-line', description: '允许管理小区公共设施', colorClass: 'general-color', isCommon: false },
  { value: 'notice', label: '通知发布', icon: 'ri-notification-line', description: '允许发布小区通知', colorClass: 'general-color', isCommon: false },
  { value: 'inspection', label: '巡检权限', icon: 'ri-survey-line', description: '允许进行小区巡检记录', colorClass: 'maintenance-color', isCommon: true },
];

// 打开权限设置弹窗
const openPermissionPopup = () => {
  showPermissionPopup.value = true;
};

// 关闭权限设置弹窗
const closePermissionPopup = () => {
  showPermissionPopup.value = false;
};

// 保存权限设置
const savePermissions = (staffData) => {
  formData.permissions = [...staffData.permissions];
  closePermissionPopup();
};

// 获取权限摘要文本
const getPermissionSummary = () => {
  if (formData.permissions.length === 0) {
    return '未设置权限';
  }
  
  // 获取已选权限的名称
  const permNames = formData.permissions.map(code => {
    const perm = allPermissions.find(p => p.value === code);
    return perm ? perm.label : '';
  }).filter(name => name);
  
  if (permNames.length <= 2) {
    return permNames.join('、');
  } else {
    return `${permNames[0]}、${permNames[1]} 等${permNames.length}项`;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 提交表单
const submitForm = () => {
  form.value.validate()
    .then(({ valid, errors }) => {
      if (valid) {
        if (!formData.villageId) {
          uni.showToast({ title: '请选择所属小区', icon: 'none' });
          return;
        }
        
        // 显示加载
        uni.showLoading({ title: '提交中...' });
        
        // 模拟提交
        setTimeout(() => {
          uni.hideLoading();
          uni.showToast({ title: '添加成功', icon: 'success' });
          
          // 延迟返回
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }, 1000);
      } else {
        console.log('表单校验失败', errors);
      }
    })
    .catch(error => {
      console.error('表单校验异常', error);
    });
};
</script>

<style lang="scss" scoped>
/* 主容器 */
.container {
  min-height: 100vh;
  background-color: transparent;
  position: relative;
  font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, Helvetica, Segoe UI, Arial, Roboto, PingFang SC, sans-serif;
  padding-bottom: env(safe-area-inset-bottom);
}

/* 导航栏背景 */
.nav-bg-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: calc(var(--status-bar-height) + 88rpx);
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.9) 100%);
  z-index: -1;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

/* 页面背景 */
.page-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f8fafd 0%, #eef2f9 100%);
  z-index: -2;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 100%;
    height: 30%;
    background: linear-gradient(135deg, rgba(66, 165, 255, 0.03), rgba(0, 112, 240, 0));
    z-index: -1;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 40%;
    background: linear-gradient(315deg, rgba(66, 165, 255, 0.02), rgba(0, 112, 240, 0));
    z-index: -1;
  }
}

/* 内容区域 */
.content {
  position: relative;
  z-index: 2;
  padding: 30rpx;
  padding-bottom: 50rpx;
  /* #ifdef MP-WEIXIN  */
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  /* #endif */
}

/* 表单包装器 */
.form-wrapper {
  width: 100%;
}

/* 表单卡片 */
.form-card {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 40rpx;
  box-shadow: 0 8rpx 16rpx rgba(0, 112, 240, 0.06);
}

/* 提交按钮 */
.submit-btn-wrapper {
  margin-top: 60rpx;
  padding: 0 20rpx;
}

/* 小区选择弹窗 */
.village-popup {
  padding: 30rpx;
  max-height: 60vh;
}

.village-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 16rpx;
  border-bottom: 1px solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
  
  &.active {
    background-color: rgba(66, 165, 255, 0.05);
  }
  
  .village-name {
    font-size: 28rpx;
    color: #333;
  }
  
  .village-check {
    color: #42a5ff;
    font-size: 40rpx;
  }
}

/* 权限摘要 */
.permission-summary {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 28rpx;
  color: #666;
}

:deep(.wd-input__label) {
  font-size: 28rpx !important;
  color: #333 !important;
}

:deep(.wd-cell__title) {
  font-size: 28rpx !important;
  color: #333 !important;
}

:deep(.wd-cell__value) {
  color: #666 !important;
}

:deep(.wd-button--primary) {
  background: linear-gradient(135deg, #42a5ff, #0070F0) !important;
  border: none !important;
}
</style> 