<template>
  <view :style="{ height: height }" class="flex flex-col overflow-hidden u-font-14">
    <view class="container flex flex-col flex-1 mx-auto overflow-hidden bg-gray-100">
      <!-- 角色栏 -->
      <Roles style="z-index: 100" />
      <!-- 日常任务面板 -->
      <Globals v-if="globals.length" />
      <!-- 任务详情 -->
      <div v-if="globalData && permanents.length" class="flex flex-1">
        <PatientList ref="PatientList" v-if="showPage === 'function'" class="flex flex-1" />
        <div v-else class="flex flex-1 items-center justify-center flex-col">
          <div>详情内容在详情页内查看</div>
          <div class="text-blue-500" @click="jumpDetail">点击此处跳转</div>
        </div>
      </div>
    </view>
  </view>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';

export default {
  data() {
    return {
      height: '',
      show: false,
      count: 0,
      chooseItem: false,
      name: '',
      urlData: null,
      showStatus: 0,
      showPage: '',
      isBack: false,
    };
  },

  computed: {
    ...mapState('task', ['permanents']),
    ...mapState('user', ['user', 'token']),
    ...mapState('role', ['visibleRoles', 'roleId']),
    ...mapState('project', ['project']),
    ...mapState('carbasics', ['globalData']),
    ...mapGetters('user', ['userId']),
    ...mapGetters('task', ['globals']),
    ...mapGetters('project', ['projectId']),
  },

  async onLoad(options) {
    if (!this.isBack) {
      this.init(options);
    }
  },

  watch: {
    /**
     * 当角色发生变化时
     * 重新查询永久日常任务和普通日常任务
     * 注意: 切换角色后 重新设置了时间基准点 时间基准点一定会变
     * 所以监听时间基准点获取 可变日常任务即可 这里不用获取 避免重复获取
     */
    roleId(val) {
      if (val) {
        const params = { roleId: val, projectId: this.projectId };
        this.getPermanent(params);
      }
    },
    // 收到跳转新项目的消息
    newProjectInfo(val) {
      if (val && val.projectId && val.url) {
        this.$u.route('/', { u: this.userId, p: val.projectId, url: val.url });
        this.clearTasksData();
        this.setRoleId('');
        const options = this.$route.query;
        this.init(options);
        this.getByProject(val.projectId);
      }
    },

    globalData(val) {
      this.urlData = val;
      var strList = val.url.split('/');
      this.showPage = strList[strList.length - 1];
    },

    showPage(val) {
      if (val !== 'function') {
        let jumpUrl = `/pages/detail-webview/detail-webview?jumpUrl=${this.urlData.url}&projectId=${this.projectId}&roleId=${this.roleId}&userId=${this.userId}`;
        for (let key in this.urlData) {
          if (key !== 'url') {
            jumpUrl += `&${key}=${this.urlData[key]}`;
          }
        }
        console.log('jumpUrl: ', jumpUrl);
        uni.navigateTo({ url: jumpUrl });
      }
    },
  },

  mounted() {
    const system = uni.getSystemInfoSync();
    this.height = system.windowHeight + 'px';
  },

  onUnload() {
    // this.clearTasksData();
    this.setRoleId('');
  },

  methods: {
    ...mapActions('user', ['getToken']),
    ...mapActions('task', ['getPermanent']),
    ...mapMutations('user', ['setToken']),
    ...mapMutations('project', ['setProject', 'setProjectName', 'setOrganData']),
    ...mapMutations('role', ['setInvisibleRoles', 'setVisibleRoles', 'setRoleId']),

    // 点击跳转到详情页
    jumpDetail() {
      let jumpUrl = `/pages/detail-webview/detail-webview?jumpUrl=${this.urlData.url}&projectId=${this.projectId}&roleId=${this.roleId}&userId=${this.userId}`;
      for (let key in this.urlData) {
        if (key !== 'url') {
          jumpUrl += `&${key}=${this.urlData[key]}`;
        }
      }
      uni.navigateTo({ url: jumpUrl });
    },

    // 初始化 定期任务
    async initPlanTasks() {
      this.setPrevPlaceholderTasks(); // 向上加载空数据
      this.setNextPlaceholderTasks(); // 向下加载空数据
      // // this.$nextTick(() => this.$refs.timeLine.setScrollPosition()); // 滚动到对应位置
      await this.getInitTasks(); // 获取初始数据

      // 滚动到对应位置
      // let timer = null;
      // timer = setInterval(() => {
      //   if (this.showScrollTo) {
      //     clearInterval(timer);
      //     this.$nextTick(() => this.$refs.timeLine.setScrollPosition());
      //   }
      // }, 1000);
    },

    // 切换了 颗粒度 || 角色时候 获取初始定期任务
    getInitTasks() {
      // 预加载 上下的定期任务
      function preloadFn(that) {
        const detailId = that.tasks.findIndex(task => task.detailId);
        const arr = [];
        // setTimeout(() => {
        //   that.tasks.forEach(task => {
        //     if (task.detailId) {
        //       arr.push(task);
        //     }
        //   });
        //   that.$nextTick(() => that.$refs.timeLine.setScrollPosition());
        // }, 100);
        if (detailId !== -1) {
          // 只要有1个真实的任务 就预加载上下周期的任务
          const { pageCount } = that.$t.task;
          that.$nextTick(() => {
            // 向上拿数据
            const { tasks, timeGranularity } = that;
            that.getTasks({ timeNode: +tasks[detailId].planStart, queryType: 0, queryNum: pageCount });
            // 向下拿数据
            const nextQueryTime = +that.$t.time.add(+arr[arr.length - 1].planStart, 1, timeGranularity);
            that.getTasks({ timeNode: nextQueryTime, queryType: 1, queryNum: pageCount });
          });
        } else {
          // 没有任务 上下显示时间刻度
          // 向上加载
          // that.setPrevPlaceholderTasks();
          // // 向下加载
          // that.setNextPlaceholderTasks();
        }
      }
      // 根据时间基准点和角色查找定期任务
      this.getTasks({ queryType: 0 }); // 向上获取定期任务数据

      // 根据项目id获取角色列表
      this.getTasks({ queryType: 1 }, preloadFn); // 向下获取定期任务数据
    },

    /**
     * 根据时间基准点和角色查找定期任务
     * @param {object} query
     * @param {string} query.roleId 角色id
     * @param {string} query.timeNode 时间基准点 默认当前
     * @param {string} query.timeUnit 时间颗粒度 默认天
     * @param {string} query.queryNum 查找颗粒度数量 默认3个
     * @param {number} query.queryType 0向上查找 1向下查找(默认) 下查包含自己，上查不包含
     */
    getTasks(query, fn) {
      this.setShowSkeleton(true);
      const params = this.generateGetTaskParam(query);

      this.$t.$q.getRegularTask(params, (err, data) => {
        this.setShowSkeleton(false);
        if (err) {
          // TODO: 提示错误
          console.error('err: ', err);
        } else {
          this.setShowScrollTo(true);
          // 有数据用数据替换刻度
          // 没有数据 继续加载刻度
          if (data && data.length) {
            this.replacePrevData(data, params.queryType);
            params.queryType === 0 ? this.setTopEnd(false) : this.setBottomEnd(false);
          } else {
            // TODO: 0 -> 向上  1 -> 向下
            params.queryType === 0 ? this.setPrevPlaceholderTasks() : this.setNextPlaceholderTasks();
          }
          if (this.tasks.length && fn) {
            fn(this);
          }
        }
      });
    },

    /**
     * 生成getTasks所用的参数
     * @param {object} query getTasks传递的参数
     */
    generateGetTaskParam(query) {
      const { roleId, timeNode, timeUnit, projectId } = this;
      return {
        roleId,
        timeNode: query.timeNode || timeNode,
        timeUnit: query.timeUnit || timeUnit,
        queryNum: query.queryNum || 3,
        queryType: query.queryType,
        projectId,
      };
    },

    /**
     * 初始化
     * @param {object | null} options
     */
    init(options) {
      // 参数里有项目名称  就设置标题里的项目名称
      options && options.pname && this.setProjectName(options.pname);

      if (!options || !options.p) {
        this.$t.ui.showToast('缺少项目信息参数'); // 没有项目id参数
      } else {
        uni.setNavigationBarTitle({ title: options.pname });
        if (options.p !== this.$t.storage.getStorageSync('projectId')) {
          this.$t.storage.setStorageSync('roleId', '');
        }
        // TODO
        this.getProjectById({ projectId: options.p, num: 0 }); // 根据项目id获取项目信息
        this.getByProject(options.p);
      }
    },

    /**
     * 通过项目id获取项目信息
     * @param {object} params 提交的参数
     */
    async getProjectById(params) {
      try {
        const data = await this.$u.api.findProjectById(params);
        this.setProject(data);
        // 根据项目id获取角色列表
        this.getRoles(params);
      } catch (error) {
        console.log('error: ', error || '获取项目信息失败');
      }
    },

    /**
     * 通过项目id获取角色信息
     * @param {string} projectId
     * @param {object} params 提交的参数
     */
    getRoles(params) {
      this.$t.$q.findShowRole(params, (err, data) => {
        if (err) {
          console.error('err: ', err || '获取角色信息失败');
        } else {
          this.setInvisibleRoles(data ? data.invisibleList : []);
          this.setVisibleRoles(data ? data.visibleList : []);
          this.setInitialRoleId(data ? data.visibleList : []);
        }
      });
    },

    // 设置 初始显示角色信息
    async setInitialRoleId(visibleList) {
      if (!visibleList || !visibleList.length) return;
      const index = visibleList.findIndex(item => +item.mine === 1);
      const currentRole = index > 0 ? visibleList[index] : visibleList[0];
      const storageRoleId = this.$t.storage.getStorageSync('roleId');
      const params = { param: { projectId: this.projectId } };
      const data = await uni.$u.api.queryLastRoleChoose(params);
      if (data && data.roleId) {
        this.setRoleId(data.roleId);
      } else {
        const currentRoleId = storageRoleId ? storageRoleId : currentRole ? currentRole.id : '';
        const saveParams = { param: { roleId: currentRoleId, projectId: this.projectId } };
        await uni.$u.api.saveRoleRecord(saveParams);
        this.setRoleId(currentRoleId);
      }
      // 清空storage
      this.$t.storage.setStorageSync('roleId', '');
    },

    // 清除已有的任务数据
    clearTasksData() {
      // 清空日常任务的数据
      this.setPermanents([]);
      this.setDailyTasks([]);
      // 清空定期任务数据
      this.clearTasks();
      // 到顶的标志复位
      // 到底的标志复位
      this.clearEndFlag();
    },

    // 根据当前打开的项目id 查询当前项目的配置信息
    async getByProject(projectId) {
      try {
        const param = { projectId };
        const data = await this.$u.api.getByProject(param);
        if (data && data.organizationType === 3) {
          this.showEXP = true;
          this.showGuide = true;
          this.setOrganData(data);
        } else if (data && data.organizationType === 0) {
          this.setOrganData(data);
        } else {
          this.showEXP = false;
          this.showGuide = false;
        }
      } catch (error) {
        console.log('error: ', error);
      }
    },
  },

  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {
    if (this.showPage === 'function' && this.$refs.PatientList) {
      this.$refs.PatientList.getData(true);
    }
    if (this.isBack) {
      this.isBack = false;
      setTimeout(() => {
        uni.navigateTo({ url: `/pages/patientLine/patientLine?caseType=${this.globalData.createAuth - 0 === 0 ? 1 : 0}` });
      }, 500);
    }
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
}
.border-b {
  border-bottom: 1px solid #e4e7ed;
}
</style>
