<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <input class="search-input-field" v-model="queryParams.nickName" placeholder="请输入姓名搜索" @input="handleQuery"
          @confirm="handleQuery" />
      </view>
    </view>

    <!-- 部门选择 -->
    <view class="dept-section" v-if="deptOptions.length > 0">
      <view class="dept-header">
        <text class="dept-title">部门</text>
        <text class="dept-name">{{ currentDeptName || '全部部门' }}</text>
      </view>
      <scroll-view class="dept-scroll" scroll-x>
        <view class="dept-list">
          <view class="dept-item" :class="{ active: !queryParams.deptId }" @click="selectDept(null, '全部部门')">
            全部
          </view>
          <view v-for="dept in deptOptions" :key="dept.id" class="dept-item"
            :class="{ active: queryParams.deptId === dept.id }" @click="selectDept(dept.id, dept.label)">
            {{ dept.label }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 状态选择 -->
    <view class="status-section">
      <view class="status-header">
        <text class="status-title">状态</text>
        <text class="status-name">{{ getStatusLabel(queryParams.status) || '在职' }}</text>
      </view>
      <scroll-view class="status-scroll" scroll-x>
        <view class="status-list">
          <view class="status-item" :class="{ active: queryParams.status === '0' }" @click="selectStatus('0')">
            在职
          </view>
          <view class="status-item" :class="{ active: queryParams.status === '1' }" @click="selectStatus('1')">
            离职
          </view>
          <view class="status-item" :class="{ active: queryParams.status === '2' }" @click="selectStatus('2')">
            退休
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 员工列表 -->
    <mescroll-uni ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption"
      :up="upOption" :fixed="false" :top="10" style="padding: 30rpx;">
      <view class="staff-list">
        <view v-for="(item, index) in staffList" :key="index" class="staff-card" @click="handleView(item)">
          <view class="staff-header">
            <view class="staff-avatar">
              <image class="avatar-image" :src="item.avatar || '/static/images/user.png'" mode="aspectFill" />
            </view>
            <view class="staff-info">
              <view class="staff-name">{{ item.nickName }}</view>
              <view class="staff-dept">{{ (item.dept && item.dept.deptName) || '未分配部门' }}</view>
              <view class="staff-status">
                <text class="status-tag" :class="'status-' + item.status">
                  {{ getStatusText(item.status) }}
                </text>
              </view>
            </view>
            <view class="staff-actions">
              <text class="arrow-icon" @click="goToDetail(item)">详情</text>
            </view>
          </view>

          <view class="staff-details">
            <view class="detail-item">
              <text class="detail-label">年龄：</text>
              <text class="detail-value">{{ String(getAgeByIdCard(item.idCard)).slice(0, 2) }}岁</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">性别：</text>
              <text class="detail-value">{{ item.sex == 0 ? '男' : '女' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">手机：</text>
              <text class="detail-value">{{ item.phonenumber || '无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">职称：</text>
              <text class="detail-value">{{ getTitleText(item.titles) || '无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">职务：</text>
              <text class="detail-value">{{ item.postNames || '无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">岗级：</text>
              <text class="detail-value">{{ formatPostLevel(item.postLevel, item.salaryLevel) || '无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">入职时间：</text>
              <text class="detail-value">{{ formatDate(item.entryDate) || '无' }}</text>
            </view>
          </view>
        </view>
      </view>
    </mescroll-uni>
  </view>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus } from "@/api/system/user";
import { deptTreeSelectNew } from "@/api/system/dept";
import MescrollMixin from '@/uni_modules/mescroll/components/mescroll-uni/mescroll-mixins.js';

export default {
  mixins: [MescrollMixin],
  data() {
    return {
      mescroll: null, // mescroll实例
      downOption: {
        auto: true,
        textOutOffset: '下拉刷新',
        textLoading: '加载中...'
      },
      upOption: {
        auto: false,
        page: { num: 1, size: 10 },
        noMoreSize: 5,
        empty: { tip: '暂无更多员工数据' },
        textNoMore: '~ 没有更多数据了 ~'
      },
      staffList: [],
      deptOptions: [],
      currentDeptName: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: '',
        titles: '',
        certificates: '',
        degree: '',
        status: '0',
        deptId: undefined
      },
      // 筛选选项
      titleOptions: [
        { label: '正高级工程师', value: '0' },
        { label: '高级工程师', value: '1' },
        { label: '工程师', value: '2' },
        { label: '助理工程师', value: '3' },
        { label: '技术员', value: '4' }
      ],
      certificateOptions: [
        { label: '注册测绘师', value: '1' },
        { label: '注册建筑师', value: '2' },
        { label: '注册结构师', value: '3' },
        { label: '注册造价师', value: '4' }
      ],
      degreeOptions: [
        { label: '博士', value: '1' },
        { label: '硕士', value: '2' },
        { label: '本科', value: '3' },
        { label: '专科', value: '4' },
        { label: '高中', value: '5' }
      ],
      statusOptions: [
        { label: '在职', value: '0' },
        { label: '离职', value: '1' },
        { label: '退休', value: '2' },
        { label: '试用', value: '3' },
        { label: '返聘', value: '4' }
      ]
    }
  },
  onLoad: function (options) {
    this.getDeptTree();
    uni.startPullDownRefresh();
  },

  methods: {
    mescrollInit(mescroll) {
      this.mescroll = mescroll;
    },

    // 获取部门树
    async getDeptTree() {
      try {
        const res = await deptTreeSelectNew();
        this.deptOptions = res.data[0].children || [];
      } catch (error) {
        console.error('获取部门树失败:', error);
      }
    },

    // 选择部门
    selectDept(deptId, deptName) {
      this.queryParams.deptId = deptId;
      this.currentDeptName = deptName;
      this.handleQuery();
    },

    // 选择状态
    selectStatus(status) {
      this.queryParams.status = status;
      this.handleQuery();
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.staffList = [];
      this.downCallback();
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: '',
        titles: '',
        certificates: '',
        degree: '',
        status: '0', // 默认选中在职
        deptId: undefined
      };
      this.currentDeptName = '';
      this.handleQuery();
    },

    // 获取职称标签
    getTitleLabel(value) {
      const item = this.titleOptions.find(item => item.value === value);
      return item ? item.label : '';
    },

    // 获取状态标签
    getStatusLabel(value) {
      const item = this.statusOptions.find(item => item.value === value);
      return item ? item.label : '';
    },

    // 加载数据
    async loadData() {
      try {
        const res = await listUser(this.queryParams);
        return { data: res.rows, total: res.total };
      } catch (e) {
        console.error('加载员工数据失败:', e);
        return { data: [], error: true };
      }
    },

    // mescroll下拉刷新回调
    async downCallback() {
      this.staffList = []; // 清空列表
      this.queryParams.pageNum = 1;
      const res = await this.loadData();
      if (res.error) {
        this.mescroll.endErr();
      } else {
        this.staffList = res.data;
        this.mescroll.endSuccess(res.data.length, res.total);
      }
      uni.stopPullDownRefresh();
    },

    // mescroll上拉加载回调
    async upCallback(page) {
      this.queryParams.pageNum = page.num;
      const res = await this.loadData();
      if (res.error) {
        this.mescroll.endErr();
      } else {
        this.staffList = this.staffList.concat(res.data);
        this.mescroll.endSuccess(res.data.length, res.total);
      }
    },

    // 查看员工详情
    handleView(item) {
      uni.navigateTo({
        url: `/pages/oa/staff/staffDetail?userId=${item.userId}&nickName=${item.nickName}`
      });
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '0': '在职',
        '1': '离职',
        '2': '退休',
        '3': '试用',
        '4': '返聘'
      };
      return statusMap[status] || '未知';
    },

    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        '0': 'success',
        '1': 'error',
        '2': 'warning',
        '3': 'primary',
        '4': 'info'
      };
      return typeMap[status] || 'default';
    },

    // 获取职称文本
    getTitleText(titles) {
      const titleMap = {
        '0': '正高级工程师',
        '1': '高级工程师',
        '2': '工程师',
        '3': '助理工程师',
        '4': '技术员'
      };
      return titleMap[titles] || '';
    },

    // 根据身份证计算年龄
    getAgeByIdCard(idCard) {
      if (!idCard) return 0;
      const birthStr = idCard.substring(6, 14);
      const birthYear = parseInt(birthStr.substring(0, 4), 10);
      const birthMonth = parseInt(birthStr.substring(4, 6), 10) - 1;
      const birthDay = parseInt(birthStr.substring(6, 8), 10);
      const birthDate = new Date(birthYear, birthMonth, birthDay);
      const now = new Date();
      let age = now.getFullYear() - birthDate.getFullYear();
      const monthDiff = now.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && now.getDate() < birthDate.getDate())) {
        age--;
      }
      return age;
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },

    // 格式化岗级
    formatPostLevel(postLevel, salaryLevel) {
      const postLevelMap = {
        '0': '一岗',
        '1': '二岗',
        '2': '三岗',
        '3': '四岗',
        '4': '五岗',
        '5': '六岗',
        '6': '七岗',
        '7': '八岗',
      };
      const salaryLevelMap = {
        '0': '一级',
        '1': '二级',
        '2': '三级',
        '3': '四级',
      };
      return postLevelMap[postLevel] + salaryLevelMap[salaryLevel] || '';
    },
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/oa/staff/staffDetail?userId=${item.userId}&nickName=${item.nickName}`
      });
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  padding: 10rpx;
  background-color: #f5f5f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;

  .search-input {
    flex: 1;

    .search-input-field {
      width: 100%;
      height: 60rpx;
      padding: 0 20rpx;
      border: 1rpx solid #ddd;
      border-radius: 30rpx;
      font-size: 28rpx;
    }
  }
}

.dept-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;

  .dept-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .dept-title {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }

    .dept-name {
      font-size: 24rpx;
      color: #666;
    }
  }

  .dept-scroll {
    white-space: nowrap;

    .dept-list {
      display: flex;

      .dept-item {
        display: inline-block;
        padding: 10rpx 20rpx;
        margin-right: 20rpx;
        background-color: #f5f5f5;
        border-radius: 20rpx;
        font-size: 24rpx;
        color: #666;
        white-space: nowrap;

        &.active {
          background-color: #007aff;
          color: #fff;
        }
      }
    }
  }
}

.status-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;

  .status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .status-title {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }

    .status-name {
      font-size: 24rpx;
      color: #666;
    }
  }

  .status-scroll {
    white-space: nowrap;

    .status-list {
      display: flex;

      .status-item {
        display: inline-block;
        padding: 10rpx 20rpx;
        margin-right: 20rpx;
        background-color: #f5f5f5;
        border-radius: 20rpx;
        font-size: 24rpx;
        color: #666;
        white-space: nowrap;

        &.active {
          background-color: #007aff;
          color: #fff;
        }
      }
    }
  }
}

.staff-list {
  .staff-card {
    background-color: #fff;
    border-radius: 20rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

    .staff-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .staff-avatar {
        margin-right: 20rpx;

        .avatar-image {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
        }
      }

      .staff-info {
        flex: 1;

        .staff-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }

        .staff-dept {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 10rpx;
        }

        .staff-status {
          display: inline-block;

          .status-tag {
            padding: 4rpx 12rpx;
            border-radius: 10rpx;
            font-size: 20rpx;

            &.status-0 {
              background-color: #e6f7ff;
              color: #52c41a;
            }

            &.status-1 {
              background-color: #fff2e8;
              color: #fa8c16;
            }

            &.status-2 {
              background-color: #f6ffed;
              color: #1890ff;
            }

            &.status-3 {
              background-color: #f9f0ff;
              color: #722ed1;
            }

            &.status-4 {
              background-color: #f0f0f0;
              color: #8c8c8c;
            }
          }
        }
      }

      .staff-actions {
        padding: 10rpx;

        .arrow-icon {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .staff-details {
      .detail-item {
        display: flex;
        margin-bottom: 15rpx;

        .detail-label {
          width: 140rpx;
          font-size: 26rpx;
          color: #999;
        }

        .detail-value {
          flex: 1;
          font-size: 26rpx;
          color: #333;
        }
      }
    }
  }
}
</style>