<template>
  <div class="home">
    <van-nav-bar title="人员管理" fixed left-arrow @click-left="onClickLeft">
    </van-nav-bar>
    <van-search
      shape="round"
      v-model="searchValue"
      :show-action="false"
      placeholder="请输入人员姓名"
    />
    <van-cell-group>
      <van-cell title="当前站点" :value="yhzDetail.mc" />
    </van-cell-group>

    <div class="content">
      <van-cell-group>
        <van-cell
          v-for="(item, index) in staffList"
          :key="index"
          :title="item.xm"
          is-link
          :value="
            item.ryjs === 1
              ? '负责人'
              : item.ryjs === 2
              ? '一般工作人员'
              : '其他'
          "
          :to="{
            name: 'StaffDetail',
            params: {
              data: encodeURIComponent(
                JSON.stringify({
                  yhzDetail: yhzDetail,
                  staffData: item,
                })
              ),
            },
          }"
        ></van-cell>
      </van-cell-group>
    </div>

    <van-button type="primary" class="add-btn" icon="plus" @click="handleAdd">
      添加人员
    </van-button>

    <!-- 弹出层 -->
    <van-popup
      :show="showPopup"
      position="bottom"
      closeable
      close-on-click-overlay
      :style="{ height: '80%' }"
      @close="onPopupClose"
    >
      <div class="popup-content">
        <h3>添加人员</h3>
        <van-search
          shape="round"
          v-model="addSearchValue"
          :show-action="false"
          placeholder="请输入电话号码或姓名"
        />
        <van-cell-group class="add-cell-group">
          <van-cell
            v-for="item in personList"
            :key="item.userId"
            :title="item.realName"
            :label="`电话：${item.phone}`"
            clickable
            @click="handleRadioClick(item)"
          >
            <template #right-icon>
              <van-radio
                :name="item.userId"
                v-model="selectedUserId"
                @click.stop="handleRadioClick(item)"
              />
            </template>
          </van-cell>
        </van-cell-group>
        <div
          style="
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 16px;
            background: white;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 100;
          "
        >
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            @click="handleConfirmAdd"
          >
            确认添加
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
    
    <script setup>
import { ref, onMounted, reactive, toRaw, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
import { request } from "../../../../shared/utils/request";
const route = useRoute();
const router = useRouter();
const searchValue = ref(""); // 搜索框输入值
const showPopup = ref(false); // 控制弹出层显示隐藏
const yhzDetail = ref({}); // 养护站详情数据
const staffList = ref([]); // 养护站人员列表数据
const addSearchValue = ref(""); // 添加人员搜索框输入值
const personList = ref([]); // 人员列表数据
const selectedUserId = ref(null); // 选择的用户id
const selectedUser = ref(null); // 选择的用户对象

// 获取养护站人员列表
const getStaffList = async (xm) => {
  try {
    const yhzid = yhzDetail.value.id;
    if (!yhzid) {
      return;
    }
    const data = {
      pageNum: 1,
      pageSize: 9999,
      yhzid,
      xm,
    };
    const res = await request({
      url: "/snow-ops-platform/yhzry/list",
      method: "get",
      params: data,
    });
    if (res.code === "00000") {
      staffList.value = res.data.records;
    }
  } catch (error) {}
};

// 组件挂载时获取数据
onMounted(() => {
  yhzDetail.value = JSON.parse(decodeURIComponent(route.params.data));
  getStaffList();
});

watch(
  () => searchValue.value,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      getStaffList(newVal);
    }
  }
);

const onClickLeft = () => {
  router.push("/");
};

// 获取人员列表
const getPersonList = async (key) => {
  try {
    const keyword = key;
    let url = "";
    if (keyword) {
      url = `/snow-ops-platform/yhzry/getUserByKey?key=${keyword}`;
    } else {
      url = `/snow-ops-platform/yhzry/getUserByKey?key=`;
    }
    const res = await request({
      url: url,
      method: "GET",
    });
    if (res.code === "00000") {
      personList.value = res.data;
    } else {
      throw new Error(res.message);
    }
  } catch (error) {
    showToast({
      type: "error",
      message: error.message || "获取人员列表失败",
    });
  }
};
// 打开添加人员弹窗
const handleAdd = async () => {
  await getPersonList();
  showPopup.value = true;
};

// 选择要添加的人员
const handleRadioClick = (item) => {
  selectedUserId.value = item.userId;
  selectedUser.value = {
    xm: item.realName,
    sjhm: item.phone,
    yhzid: yhzDetail.value.id,
    ryjs: 2,
    userId: item.userId,
  };
};

watch(
  () => addSearchValue.value,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      getPersonList(newVal);
    }
  }
);

const onPopupClose = () => {
  selectedUserId.value = null;
  selectedUser.value = null;
  addSearchValue.value = "";
  personList.value = [];
  showPopup.value = false;
};

// 确认添加人员
const handleConfirmAdd = async () => {
  try {
    // console.log('toRaw(selectedUser.value)',toRaw(selectedUser.value));

    const res = await request({
      url: "/snow-ops-platform/yhzry/add",
      method: "POST",
      data: toRaw(selectedUser.value),
    });
    if (res.code === "00000") {
      showToast({
        type: "success",
        message: "添加人员成功",
      });
      onPopupClose();
      getStaffList(searchValue.value);
    } else {
      throw new Error(res.message);
    }
  } catch (error) {
    showToast({
      type: "fail",
      message: error.message || "添加人员失败",
    });
  }
};
</script> 
    
    <style scoped>
.home {
  padding-top: var(--van-nav-bar-height); /* 自动匹配导航栏高度 */
}

.content {
  padding: 16px;
}

.content .van-cell-group .van-cell {
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.add-btn {
  position: fixed;
  bottom: 20px;
  left: 16px;
  right: 16px;
  width: calc(100% - 32px);
  margin: 0 auto;
  border-radius: 24px;
  font-size: 16px;
  height: 44px;
  z-index: 999;
}

.grid {
  margin-top: 16px;
}

.btn {
  margin-top: 24px;
}

.status-tag {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
}
.status-good {
  background-color: #07c160;
}
.status-warning {
  background-color: #ff976a;
}
.status-danger {
  background-color: #ee0a24;
}
.popup-content {
  padding: 16px 16px 80px 16px;
}
.add-cell-group {
  height: calc(100vh * 0.8 - 200px);
  overflow-y: auto;
}
</style>
    