<template>
  <view class="choose-people">
    <view class="search-form">
      <view class="search-item">
        <text class="label">姓名：</text>
        <uv-input v-model="queryParams.nickName" placeholder="请输入姓名" />
      </view>
      <view class="search-item">
        <text class="label">部门：</text>
        <uni-data-select style="width:270rpx;margin-right:30rpx;" v-model="queryParams.deptId" :localdata="deptList"
          @change="getList" clearable />
      </view>
      <view class="search-item">
        <u-button type="primary" @click="getList">搜索</u-button>
      </view>
    </view>

    <!-- 选择人员 -->
    <scroll-view scroll-y class="user-list" :style="{ height: '35vh' }">
      <uv-checkbox-group v-model="selectedIds" iconPlacement="right" placement="column"
        @change="(value) => handleCheckboxChange(value)">
        <uv-checkbox v-for="item in userList" :label="item.nickName" :name="item.userId" :disabled="item.status == 1" />
      </uv-checkbox-group>
    </scroll-view>
    
    <view class="selected-users" v-if="multiple">
      <text class="label">已选人员：</text>
      <view class="tags">
        <u-tag v-for="item in chooseUser" :key="item.userId" :text="item.nickName" style="margin: 5px;" />
      </view>
    </view>

    <view class="selected-users" v-else>
      <text class="label">已选人员：</text>
      <u-tag v-if="chooseUser.nickName" :text="chooseUser.nickName" style="margin: 5px;" />
    </view>

    <view class="action-buttons">
      <u-button type="primary" @click="confirmChoose">确认选择</u-button>
      <u-button @click="clearChoose">清空选择</u-button>
    </view>
  </view>
</template>

<script>
import { listUser } from "@/api/system/user";
import { listDept } from "@/api/system/dept";

export default {
  name: 'ChoosePeople',
  props: {
    deptId: {
      type: Number
    },
    multiple: {
      type: Boolean,
      default: true
    },
    selected: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        nickName: '',
        deptId: undefined
      },
      userList: [],
      deptList: [],
      chooseUser: this.selected,
      total: 0,
      selectedIds: [],
      allSelectedUsers: []
    }
  },
  created() {
    this.queryParams.deptId = this.deptId;
    this.getList();
    this.getDeptList();
    this.selectedIds = this.selected.map(user => user.userId);
    this.allSelectedUsers = [...this.selected];
  },
  methods: {
    getList() {
      listUser(this.queryParams).then(response => {
        this.userList = response.rows.filter(item => item.status != '1' && item.status != '2');
        this.total = response.total;
        // 更新当前页面的选中状态，保持所有已选用户
        this.selectedIds = this.userList
          .filter(item => this.allSelectedUsers.some(selected => selected.userId === item.userId))
          .map(item => item.userId);
        this.updateSelectedUsers();
      });
    },
    getDeptList() {
      listDept().then(res => {
        this.deptList = res.data
          .filter(item => item.deptName != '四川中水成勘院测绘工程有限责任公司')
          .map(item => ({
            text: item.deptName,
            value: item.deptId
          }));
      });
    },
    updateSelectedUsers() {
      // 合并当前页面选中的用户和其他页面的已选用户
      const currentPageUsers = this.userList.filter(item => this.selectedIds.includes(item.userId));
      const otherPageUsers = this.allSelectedUsers.filter(user =>
        !this.userList.some(item => item.userId === user.userId)
      );
      this.chooseUser = [...currentPageUsers, ...otherPageUsers];
    },
    isSelected(user) {
      return this.selectedIds.includes(user.userId);
    },
    confirmChoose() {
      this.$emit('chooseUser', this.chooseUser);
    },
    clearChoose() {
      this.selectedIds = [];
      this.allSelectedUsers = [];
      this.chooseUser = this.multiple ? [] : {};
      this.$emit('clear');
    },
    getAgeByIdCard(idCard) {
      if (!idCard) return '';
      const yearBirth = idCard.substring(6, 10);
      const monthBirth = idCard.substring(10, 12);
      const dayBirth = idCard.substring(12, 14);
      const now = new Date();
      const monthNow = now.getMonth() + 1;
      const dayNow = now.getDate();
      let age = now.getFullYear() - yearBirth;
      if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
        age--;
      }
      return age;
    },
    handleCheckboxChange(selectedNames) {
      if (this.multiple) {
        this.selectedIds = selectedNames;
        // 更新当前页面的选中用户
        const currentPageSelectedUsers = this.userList.filter(user => selectedNames.includes(user.userId));
        // 获取其他页面的已选用户
        const otherPageUsers = this.allSelectedUsers.filter(user =>
          !this.userList.some(item => item.userId === user.userId)
        );
        // 更新所有已选用户列表
        this.allSelectedUsers = [...currentPageSelectedUsers, ...otherPageUsers];
        this.updateSelectedUsers();
      } else {
        const lastSelectedId = selectedNames[selectedNames.length - 1];
        this.selectedIds = lastSelectedId ? [lastSelectedId] : [];
        this.allSelectedUsers = lastSelectedId ? [this.userList.find(user => user.userId === lastSelectedId)] : [];
        this.updateSelectedUsers();
        if (lastSelectedId) {
          this.confirmChoose();
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.choose-people {
  padding: 20rpx;

  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;

    .search-item {
      display: flex;
      align-items: center;
      gap: 10rpx;

      .label {
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .user-list {
    margin-bottom: 30rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;

    ::v-deep .uv-checkbox {
      margin: 20rpx 0;
      padding: 20rpx;
      border-radius: 8rpx;
      background-color: #f8f8f8;
      transition: all 0.3s;

      &:active {
        background-color: #f0f0f0;
      }

      &.uv-checkbox--checked {
        background-color: #e6f7ff;
        border-color: #1890ff;
        box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.15);
      }

      .uv-checkbox__label {
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    margin: 20rpx 0;
  }

  .selected-users {
    margin: 20rpx 0;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10rpx;

    .label {
      font-size: 28rpx;
      color: #333;
    }

    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10rpx;
    }
  }

  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 20rpx;
    margin-top: 30rpx;
  }
}
</style>