<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-box">
      <view class="search-header" @tap="toggleSearch">
        <text class="search-title">搜索条件</text>
        <text class="search-icon">{{ isSearchExpanded ? '收起' : '展开' }}</text>
      </view>
      
      <view class="search-content" v-if="isSearchExpanded">
        <view class="search-item">
          <text>项目编号</text>
          <input v-model="queryParams.projectNumber" placeholder="请输入项目编号" @confirm="handleQuery" />
        </view>
        <view class="search-item">
          <text>项目名称</text>
          <input v-model="queryParams.projectName" placeholder="请输入项目名称" @confirm="handleQuery" />
        </view>
        <view class="search-item">
          <text>项目负责人</text>
          <picker mode="selector" :range="userList" range-key="text" @change="handleLeaderChange">
            <view class="picker">
              <text>{{ selectedLeader || '请选择项目负责人' }}</text>
            </view>
          </picker>
        </view>
        <view class="search-item">
          <text>承担部门</text>
          <picker mode="selector" :range="deptList" range-key="text" @change="handleDeptChange">
            <view class="picker">
              <text>{{ selectedDept || '请选择承担部门' }}</text>
            </view>
          </picker>
        </view>
        <view class="search-item">
          <text>其他关键字</text>
          <input v-model="queryParams.queryString" placeholder="请输入关键字" @confirm="handleQuery" />
        </view>
        <view class="search-buttons">
          <button type="primary" size="mini" @tap="handleQuery">搜索</button>
          <button type="default" size="mini" @tap="resetQuery">重置</button>
        </view>
      </view>
    </view>

    <!-- 项目列表 -->
    <view class="list-box">
      <view class="list-header">
        <text class="title">测绘项目列表</text>
        <view class="header-btns">
          <button type="primary" size="mini" @tap="handleRegister">登记项目</button>
          <button type="default" size="mini" @tap="handleExport">导出项目</button>
        </view>
      </view>

      <scroll-view 
        scroll-y 
        class="list-scroll"
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
      >
        <view class="list-content">
          <view class="project-card" v-for="(item, index) in projectList" :key="index">
            <!-- 卡片头部 -->
            <view class="card-header">
              <view class="header-left">
                <text class="project-name">{{ item.projectName }}</text>
                <text class="status-tag" :class="item.isFinished === '0' ? 'success' : 'warning'">
                  {{ item.isFinished === '0' ? '进行中' : '已结束' }}
                </text>
              </view>
              <text class="level-tag" :class="item.projectLevel === '0' ? 'info' : 'error'">
                {{ item.projectLevel === '0' ? '一般项目' : '重大项目' }}
              </text>
            </view>

            <!-- 卡片内容 -->
            <view class="card-content">
              <view class="info-row">
                <text class="label">项目编号：</text>
                <text class="value">{{ item.projectNumber }}</text>
              </view>
              <view class="info-row">
                <text class="label">合同编码：</text>
                <text class="value">{{ item.contract ? item.contract.contractCode : '未关联' }}</text>
              </view>
              <view class="info-row">
                <text class="label">承担部门：</text>
                <text class="value">{{ item.undertakingDeptName }}</text>
              </view>
              <view class="info-row">
                <text class="label">项目负责人：</text>
                <text class="value">{{ item.projectLeaderUser ? item.projectLeaderUser.nickName : '' }}</text>
              </view>
              <view class="info-row">
                <text class="label">项目类型：</text>
                <text class="value">{{ item.projectType }}</text>
              </view>
              <view class="info-row">
                <text class="label">项目进度：</text>
                <view class="progress-box">
                  <progress :percent="item.percentage" :activeColor="getProgressColor(item.percentage)" />
                  <text class="progress-text">{{ item.percentage }}%</text>
                </view>
              </view>
            </view>

            <!-- 卡片底部 -->
            <view class="card-footer">
              <button type="primary" size="mini" @tap="handleView(item)">查看</button>
              <button type="warn" size="mini" @tap="handleDelete(item)">删除</button>
              <button type="default" size="mini" @tap="handleRelate(item)">关联合同</button>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="projectList.length > 0">
        <text v-if="hasMore">上拉加载更多</text>
        <text v-else>没有更多数据了</text>
      </view>
    </view>
  </view>
</template>

<script>
import { listProject, listProjectFuzzy, delProject } from "@/api/oa/project/project";
import { getProjectProgress } from "@/api/oa/project/projectProgress";
import { listDept } from '@/api/system/dept';
import { listUser } from '@/api/system/user';

export default {
  data() {
    return {
      isSearchExpanded: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNumber: '',
        projectLeader: '',
        projectName: '',
        queryString: '',
        undertakingDept: ''
      },
      projectList: [],
      total: 0,
      loading: false,
      userList: [],
      deptList: [],
      selectedLeader: '',
      selectedDept: '',
      hasMore: true,
      isRefreshing: false
    }
  },
  onLoad() {
    this.getList();
    this.getDeptList();
    this.getUserList();
  },
  methods: {
    toggleSearch() {
      this.isSearchExpanded = !this.isSearchExpanded;
    },
    
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        projectNumber: '',
        projectLeader: '',
        projectName: '',
        queryString: '',
        undertakingDept: ''
      };
      this.selectedLeader = '';
      this.selectedDept = '';
      this.handleQuery();
    },
    
    async getList() {
      this.loading = true;
      try {
        const response = this.queryParams.queryString ? 
          await listProjectFuzzy(this.queryParams) : 
          await listProject(this.queryParams);
        
        if (this.queryParams.pageNum === 1) {
          this.projectList = response.rows;
        } else {
          this.projectList = [...this.projectList, ...response.rows];
        }
        
        this.total = response.total;
        this.hasMore = this.projectList.length < this.total;
        
        for (let project of this.projectList) {
          const res = await getProjectProgress(project.projectId);
          if (res.data && res.data.length > 0) {
            project.percentage = Number(res.data[res.data.length - 1].percentage);
          } else {
            project.percentage = 0;
          }
          if (project.isFinished === '1') {
            project.percentage = 100;
          }
        }
      } catch (error) {
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        this.isRefreshing = false;
      }
    },
    
    async getDeptList() {
      try {
        const res = await listDept({});
        this.deptList = res.data.map(item => ({
          value: item.deptId,
          text: item.deptName
        }));
      } catch (error) {
        uni.showToast({
          title: '获取部门列表失败',
          icon: 'none'
        });
      }
    },
    
    async getUserList() {
      try {
        const res = await listUser({ pageNum: 1, pageSize: 9999 });
        this.userList = res.rows.map(item => ({
          value: item.userId,
          text: item.nickName
        }));
      } catch (error) {
        uni.showToast({
          title: '获取用户列表失败',
          icon: 'none'
        });
      }
    },
    
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    handleLeaderChange(e) {
      const index = e.detail.value;
      this.queryParams.projectLeader = this.userList[index].value;
      this.selectedLeader = this.userList[index].text;
      this.handleQuery();
    },
    
    handleDeptChange(e) {
      const index = e.detail.value;
      this.queryParams.undertakingDept = this.deptList[index].value;
      this.selectedDept = this.deptList[index].text;
      this.handleQuery();
    },
    
    handleView(row) {
      uni.navigateTo({
        url: `/pages/project/info?id=${row.projectId}&projectName=${encodeURIComponent(row.projectName)}`
      });
    },
    
    handleDelete(row) {
      uni.showModal({
        title: '提示',
        content: `是否确认删除项目编号为"${row.projectNumber}"的数据项？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await delProject(row.projectId);
              this.getList();
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
            } catch (error) {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    handleRegister() {
      uni.navigateTo({
        url: '/pages/project/register'
      });
    },
    
    handleExport() {
      uni.showToast({
        title: '导出功能开发中',
        icon: 'none'
      });
    },
    
    handleRelate(row) {
      uni.showToast({
        title: '关联合同功能开发中',
        icon: 'none'
      });
    },
    
    loadMore() {
      if (this.hasMore) {
        this.queryParams.pageNum++;
        this.getList();
      }
    },
    
    onRefresh() {
      this.isRefreshing = true;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    getProgressColor(percentage) {
      if (!percentage) return '#ff4d4f';
      if (percentage <= 20) return '#ff4d4f';
      if (percentage <= 50) return '#faad14';
      if (percentage <= 80) return '#1890ff';
      return '#52c41a';
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.search-box {
  background-color: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.search-header {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

.search-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.search-icon {
  font-size: 28rpx;
  color: #909399;
}

.search-content {
  padding: 20rpx;
}

.search-item {
  margin-bottom: 20rpx;
}

.search-item text {
  display: block;
  margin-bottom: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.search-item input,
.search-item .picker {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1px solid #dcdfe6;
  border-radius: 4rpx;
  box-sizing: border-box;
}

.search-item .picker {
  line-height: 80rpx;
  color: #606266;
}

.search-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.search-buttons button {
  flex: 1;
}

.list-box {
  flex: 1;
  background-color: #fff;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.list-header {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.header-btns {
  display: flex;
  gap: 20rpx;
}

.list-scroll {
  flex: 1;
  height: 0;
}

.list-content {
  padding: 20rpx;
}

.project-card {
  background-color: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.project-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-tag,
.level-tag {
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  font-size: 24rpx;
}

.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.info {
  background-color: #f4f4f5;
  color: #909399;
}

.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.card-content {
  padding: 20rpx;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row .label {
  width: 160rpx;
  color: #909399;
  font-size: 28rpx;
}

.info-row .value {
  flex: 1;
  color: #333;
  font-size: 28rpx;
}

.progress-box {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.progress-box progress {
  flex: 1;
}

.progress-text {
  width: 80rpx;
  text-align: right;
  color: #333;
  font-size: 28rpx;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 20rpx;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
}

.card-footer button {
  margin: 0;
  padding: 0 30rpx;
}

.load-more {
  text-align: center;
  padding: 20rpx;
  color: #909399;
  font-size: 28rpx;
}
</style>
