
<template>
  <ciy-header title="在研课题备案管理" ref="header"></ciy-header>

  <view class="ciy-page">
    <view v-if="init.code != 1">
      <view class="px4 py4">
        <view style="height:2em;width:60%;" class="ciy-skeleton"></view>
        <view style="height:1em;width:40%;margin-left:1em;" class="ciy-skeleton"></view>
        <view style="height:1em;width:50%;" class="ciy-skeleton"></view>
        <view style="height:6em;width:100%;" class="ciy-skeleton"></view>
      </view>
    </view>
    <view v-else>
      <view class="sti" :style="{top: headerTotalHeight + 'px'}">
        <ciy-segment :lis="init.lis" all="全部类目" @change="segment_change"></ciy-segment>
        <ciy-query ref="query" :gdict="g" :qry="init.searchinput" @confirm="query_confirm">
          <template v-slot="{itm}">
            <ciy-input :name="itm.item.form" v-model="itm.data[itm.item.form]"></ciy-input>
          </template>
        </ciy-query>
      </view>
      <view class="ciy-list" :class="{del:item._del}" v-for="(item,index) in init.list" :key="item.id" @tap="showmenu(index)">
        <view class="project-item">
          <view class="project-header">
            <text class="title">{{ item.name }}</text>
            <text class="record-no">备案编号: {{ item.recordno }}</text>
          </view>
          <view class="project-details">
            <text class="summary">{{ item.descs }}</text>
            <text class="org-name">所属机构: {{ item.orgname }}</text>
            <text class="status">状态: <text :class="ccode(g.rprojectstatus, item.rprojectstatus,'clas')">{{ ccode(g.rprojectstatus, item.rprojectstatus) }}</text></text>
            <text class="progress">进度: {{ item.progress }}%</text>
            <text class="progress">负责人: {{ item.principal_name}}</text>
            <text class="members">成员: {{ item.member_names || '暂无成员' }}</text>
          </view>
        </view>
      </view>

      <ciy-listend :page="pageno" :listlen="init.list.length" :nodataimg="file_stor('/img/mbnone.png')"></ciy-listend>
      <view class="ciy-add" @tap="goAdd()"></view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {};
  },
  computed: {
    headerTotalHeight() {
      return this.header_statusbar_height + this.header_title_height;
    }
  },
  onLoad() {
    this.$nextTick(() => {
      this.getrefs('header').then(ref => {
        this.header_statusbar_height = ref.statusbar_height;
        this.header_title_height = ref.title_height;
      });
    });

    this.getlist();
    uni.$off('project-updated'); // 防止重复监听
    uni.$off('project-added');
    uni.$on('project-updated', (params) => {
      console.log('收到课题更新通知，正在刷新列表...', params);
      // 刷新整个列表
      this.pageno = 0;
      this.getlist();
    });
    uni.$on('project-added', () => { // 监听新增事件
      console.log('收到课题新增通知，正在刷新列表...');
      this.pageno = 0; // 返回首页，因为新项目可能排在第一页
      this.getlist();
    });

  },
  onUnload() {
    // --- 页面卸载时移除事件监听，防止内存泄漏 ---
    uni.$off('project-updated');
    uni.$off('project-added');
  },

  onReachBottom() {
    console.log('onReachBottom page', this.pageno);
    if (this.init.code != 1) return;
    this.getlist();
  },
  onPullDownRefresh() {
    console.log('onPullDownRefresh page');
    this.pageno = 0;
    this._stopPullDown = true;
    this.getlist();
  },
  methods: {
    async getlist() {
      if (this.pageno < 0 || this._loading) return;

      this.pagepost.pageno = this.pageno + 1;
     this.pagepost.once = !this.init.once; 

      this._loading = true;

      try {
        var retjson = await this.callfunc({
          func: 'project.list', 
          data: this.pagepost
        });

        if (retjson.code != 1) {
          this.alert(retjson.errmsg);
          return;
        }

        this.pageno++;
        if (this.pageno == 1) this.init.list = []; 

        this.init = this.objdeepmerge(this.init, retjson);

        console.log(this)
        if (retjson.once) {
          if (retjson.lis) {
                this.init.lis = retjson.lis;
            }
        }

        // 设置查询组件的初始值
        this.getrefs('query').then(ref => {
          ref.setdata(retjson.searchwhere?.query || {});
        });

        // 判断是否还有下一页
        if (retjson.list && retjson.list.length < this.pagepost.pagecount) {
          this.pageno = -1;
        }

      } catch (error) {
        console.error('获取列表失败:', error);
        this.alert('获取列表失败');
      } finally {
        this._loading = false;
        uni.stopPullDownRefresh();
      }
    },

    segment_change(e) {
      this.pagepost.liid = e.value.id;
      this.pageno = 0;
      this.getlist();
      uni.pageScrollTo({ scrollTop: 0, duration: 800 });
    },

    query_confirm(dat) {
      this.pagepost.query = dat;
      this.pageno = 0;
      this.getlist();
      uni.pageScrollTo({ scrollTop: 0, duration: 800 });
    },

    edit(item) {
      item = item || { data: { id: 0, _idx: -1 } };
      uni.navigateTo({
        url: `/pages/lab/project_edit?id=${item.data.id}`
      });
    },

    goAdd() {
      uni.navigateTo({
        url: '/pages/lab/project_add'
      });
    },

    async del(item) {
      if (await this.askmsg('是否确定删除该在研课题？', '确认删除') != 'ok') return;

      var retjson = await this.callfunc({
        func: 'project.del',
        data: { id: item.data.id }
      });

      if (retjson.code != 1) {
        this.alert(retjson.errmsg);
        return;
      }
      this.init.list[item.data._idx]._del = true;
      setTimeout(() => {
        this.init.list.splice(item.data._idx, 1);
      }, 500);
    },

    showmenu(idx) {
      var dat = this.init.list[idx];
      dat._idx = idx;
      var items = [];
      items.push({ func: 'edit', name: '编辑', data: dat });
      items.push({ func: 'del', name: '删除', style: 'color:var(--dag5)', data: dat });
      this.popmenu({ items });
    }
  }
};
</script>

<style scoped>
.sti {
  position: sticky;
  z-index: 10;
  background: var(--bg1);
  padding: 0.5rem;
  border-bottom: 1px solid var(--bg6);
}
.project-item {
  padding: 1rem;
  margin: 0.5rem;
  border: 1px solid var(--bg6);
  border-radius: 8px;
  background-color: var(--bg2);
}
.project-header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 0.5rem;
}
.title {
  font-size: 1.1em;
  font-weight: bold;
  color: var(--text1);
}
.record-no {
  font-size: 0.8em;
  color: var(--text3);
}
.project-details {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}
.summary {
  font-size: 0.9em;
  color: var(--text2);
  line-height: 1.3;
}
.org-name, .status, .progress {
  font-size: 0.85em;
  color: var(--text3);
}

.members {
  font-size: 0.85em;
  color: var(--text3);
  word-break: break-all; 
}
</style>