<template>
  <u-navbar  :titleStyle="{ color: '#000' }" :autoBack="false" title="日报详情" :placeholder="true" :safeAreaInsetTop="true" bgColor="#fff">
    <template #left>
      <view class="u-navbar__content__left__item">
        <u-icon name="arrow-left" size="20" color="#000" @click="returnTo('business/common/projectMange/record/index')"></u-icon>
      </view>
    </template>
  </u-navbar>

  <oa-scroll
    customClass="record-container scroll-height"
    :pageSize="pageSize"
    :total="total"
    :isSticky="true"
    :customStyle="{
      //#ifdef APP-PLUS || MP-WEIXIN
      height: `calc(100vh - 44px)`,
      //#endif
      //#ifdef H5
      height: `calc(100vh - 44px)`,
      //#endif
    }"
    :refresherLoad="true"
    :refresherEnabled="true"
    :refresherDefaultStyle="'none'"
    :refresherThreshold="44"
    :lowerThreshold="44"
    :refresherBackground="'#f5f6f7'"
    @load="load"
    @refresh="refresh"
    :data-theme="'theme-' + proxy.$settingStore.themeColor.name"
  >
    <template #default>
      <view class="content-area radius bg-white" v-for="(item, index) in dataList" :key="index" style="margin-top: 6px">
        <view class="content-area-top menu-item" style="float: right; padding: 10px 0px">
          <view class="content-area-top-time"> </view>
          <u-icon class="content-area-top-icon" name="more-dot-fill" size="20" color="#000" @click="moreClick(item)"></u-icon>
        </view>
        <view class="content-area-header flex mb10">
          <img :src="item?.avatar" class="content-area-header-avatarImg mr10" v-if="item?.avatar" />
          <u-avatar
            v-if="!item?.avatar"
            class="content-area-header-avatar mr10"
            :text="item.createBy.length > 2 ? item.createBy.slice(1, 3) : item.createBy"
            shape="square"
            size="40"
            fontSize="12" 
            color="#ffffff"
            :bgColor="proxy.$settingStore.themeColor.color"
          ></u-avatar>
          <view>
            <view class="content-area-header-title font16 mb5">{{ item.createBy ? item.createBy : " " }} {{ item.submitDate.slice(0, 10) != item.reportDate ? "( " + item.reportDate + " )" : "" }}</view>
            <view class="content-area-header-time font14">{{ item.submitDate ? item.submitDate.replace("T", " ") : " " }}</view>
          </view>
        </view>

        <view class="content-area-center mb10" v-for="child in item.workContents" :key="child">
          <view class="content-area-center-top flex">
            <view class="content-area-center-top-title mr10" style="color: #559aff" @click="toProjectMange(child.projectId)">{{ child.projectName ? child.projectName : " " }}</view>
            <view class="content-area-center-top-time" :style="{ color: proxy.$settingStore.themeColor.color }">{{ child.workTime }}h</view>
          </view>
          <u-text :text="child.workContent" color="#000000" size="14"></u-text>
        </view>
        <view class="content-area-center mb10">
          <view class="content-area-center-top"> 明日计划 </view>
          <u-text :text="item.tomorrowPlan ? item.tomorrowPlan : '无'" color="#000000" size="14"></u-text>
        </view>
        <view class="content-area-center mb10">
          <view class="content-area-center-top"> 工作协调 </view>
          <u-text :text="item.coordinateWork ? item.coordinateWork : '无'" color="#000000" size="14"></u-text>
        </view>
        <view class="content-area-center mb10">
          <view class="content-area-center-top">图片</view>
          <view class="imageBox" v-if="JSON.parse(item.reportImage) && JSON.parse(item.reportImage).length > 0">
            <image class="image m5" style="width: 50px" mode="widthFix" v-for="(a, index2) in JSON.parse(item.reportImage)" :key="index2" :src="a.url" @click="previewImage(index,index)" />
          </view>
          <view class="imageBox" v-else>无</view>
        </view>

        <view class="content-area-center mb10">
          <view class="content-area-center-top">附件 </view>
          <view v-if="JSON.parse(item.reportFile) && JSON.parse(item.reportFile).length > 0">
            <uni-link v-for="(file, index2) in JSON.parse(item.reportFile)" :key="index2" :href="file.url" text="file.url" style="color: rgba(0, 0, 0, 0.7)">{{ file.name }}</uni-link>
          </view>
          <view v-else>无</view>
        </view>
        <view class="content-area-center mb10" style="display: flex; flex-wrap: wrap" v-if="item.pmReportReaders.read > 0 || item.pmReportReaders.unRead > 0">
          <u-tabs
            :list="item.tabsList"
            :current="item.tab"
            @click="tabsClick(index, $event.value)"
            lineColor="#333"
            :activeStyle="{ color: '#333', fontSize: '14px' }"
            :inactiveStyle="{ color: '#909399', fontSize: '14px' }"
            :scrollable="false"
            style="width: 100%"
          ></u-tabs>
          <view class="content-area-header mt20 mb10 text-center" style="display: inline-block" v-for="(item2, index2) in item.tabsList[item.tab].treeSelectNodes" :key="index2">
            <img v-if="item2?.avatar" class="content-area-header-avatarImg mlr5" :src="item2.avatar" style="display: block; width: 40px; height: 40px" />
            <u-avatar
              v-if="!item2.avatar"
              class="content-area-header-avatar mlr5"
              :text="item2.nickName.length > 2 ? item2.nickName.slice(1, 3) : item2.nickName"
              shape="square"
              size="40"
              fontSize="12"
              color="#ffffff"
              :bgColor="proxy.$settingStore.themeColor.color"
            ></u-avatar>
            <u-text :text="item2.nickName" color="#000000" size="14" align="center"></u-text>
          </view>
        </view>
      </view>
    </template>

  </oa-scroll>
  <u-popup :show="popup.show" mode="bottom" bgColor="#fff" :round="10" @close="popup.show = false">
    <view
      :style="{
        borderTopLeftRadius: '10px',
        borderTopRightRadius: '10px',
        overflow: 'hidden',
      }"
    >
      <u-button
        class="custom-style"
        type="info"
        size="normal"
        :text="`查看${eventList.createBy}的所有日报`"
        :customStyle="{
          height: '50px',
          color: '#3c9cff',
          borderWidth: 0,
          borderRadius: 0,
          borderBottomWidth: '1px',
        }"
        @click="handleSubmit(eventList)"
      ></u-button>
      <u-button
        class="custom-style"
        type="info"
        size="normal"
        text="取消"
        :customStyle="{
          height: '50px',
          color: '#3c9cff',
          border: 'none',
          borderRadius: 0,
        }"
        @click="popup.show = false"
      ></u-button>
    </view>
  </u-popup>
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import { onLoad, onShow, onReady, onHide, onLaunch, onBackPress, onUnload, onNavigationBarButtonTap, onPageScroll } from "@dcloudio/uni-app";
import { ref, reactive, computed, getCurrentInstance, toRefs, inject } from "vue";
/*----------------------------------接口引入-----------------------------------*/
import { projectApi } from "@/api/business/project.js";
import { dUserList } from "@/api/system/user.js";
import { deptUserTreeSelect } from "@/api/system/user.js";
/*----------------------------------组件引入-----------------------------------*/
/*----------------------------------store引入-----------------------------------*/
/*----------------------------------公共方法引入-----------------------------------*/
/*----------------------------------公共变量-----------------------------------*/
const { proxy } = getCurrentInstance();
/*----------------------------------变量声明-----------------------------------*/
const tree = ref({
  value: "tree_root",
  label: "Root",
  children: [],
});
const reportDetailData = ref([]);
const pmReportReaders = ref([]); //已读未读集合
const state = reactive({
  loading: true,
  dataList: [], //日报列表
  options: {
    //日报详情参数
    reportId: "",
  },
  userData: [], //用户列表
  pageSize:1,
  total:10,
  submitDate:undefined,
  popup: {
    show: false, //弹窗显示
    content: "", //提示信息
  },
  eventList: {}, //数据存储
});

const { dataList, userData, tabsList, tabsCurrent, pageSize, total, popup, eventList } = toRefs(state);
  /**
 * 返回上级页面
 * @param defaultPage 默认页面
 */
 function returnTo(defaultPage) {
    if(getCurrentPages().length > 1){
      uni.navigateBack()
    }else{
      uni.redirectTo({
        url: `/pages/${defaultPage}`
      })
    }
  }
/**
 * @tabs点击事件
 */
function tabsClick(index,e) {
  dataList.value[index].tab = e
}
function previewImage(index1,index2) {
  uni.previewImage({
    current: index2, // 当前显示图片索引
    urls: dataList.value[index1].images[index2], // 需要预览的图片http链接列表
  });
}

/**
 * @初始化
 */
function init() {
  dataList.value = [];
  state.loading = true;
  /** 查询树结构用户列表  回显抄送人*/
  deptUserTreeSelect({ pageNum: "1", pageSize: "1000" }).then((res) => {
    tree.value = res.data;
    projectApi()
      .ReportRecord({
        reportId: state.options.reportId,
        pageNum: 1,
        pageSize: 1,
      })
      .then((requset) => {
        dataRebuild(requset.data.records);
        state.loading = false;
      }).catch((err) => {
        state.loading = false;
      });
  });
}
/**
 * 
 * @param item 数据重组
*/
function dataRebuild(item,type){
  for(let i=0;i<item.length;i++){
    item[i].tabsList = [
      { name: "已读(" + item[i].pmReportReaders.read + ")", value: 0, 
      treeSelectNodes:proxy.$common.findTreeNodes(tree.value, item[i].pmReportReaders.readAlready),num:item[i].pmReportReaders.read},
      { name: "未读(" + item[i].pmReportReaders.unRead + ")", value: 1, 
      treeSelectNodes:proxy.$common.findTreeNodes(tree.value,item[i].pmReportReaders.readNotAlready),num:item[i].pmReportReaders.read},
    ];
    item[i].tab = 0
    var imgs = JSON.parse(item[i].reportImage);
    var files = JSON.parse(item[i].reportFile);
    imgs.forEach(function (val) {
      item[i].images.push(val.url);
    });
    files.forEach(function (val) {
      item[i].files.push(val.url);
    });
    //数据插入
    if(type == "refresh"){
      dataList.value.unshift(item[i])
    }else{
      dataList.value.push(item[i])
    }
    // 未读状态变更
    if(item[i].readFlag == "0"){
      projectApi()
      .ReportRecordReadFlag({ reportId: item[i].id })
      .then((res) => {
        if (res.status != "SUCCESS") {
          proxy.$modal.msgError("读取异常");
        }
      });
    }
  }
  
}
/**
 * 跳转项目概览
 * @param id 项目id
 */
function toProjectMange(id) {
  proxy.$tab.navigateTo(`/pages/business/common/projectMange/overview/index?id=${id}`);
}
/**
 * @scrollView加载数据
 */
 function load() {
  projectApi().ReportRecord(
    {
      upOrDown:0,
      slideSum:1,
      submitDate:dataList.value[dataList.value.length-1].submitDate,
      projectAscription:2
    }
  ).then((requset) => {
    if(requset?.data?.records.length>0){
      dataRebuild(requset.data.records,"load");
    }
  })
}
/**
 * @scrollView刷新数据
 */
 function refresh() {
  projectApi().ReportRecord(
    {
      upOrDown:1,
      slideSum:1,
      submitDate:dataList.value[0].submitDate,
      projectAscription:2
    }
  ).then((requset) => {
    if(requset?.data?.records.length>0){
      dataRebuild(requset.data.records,"refresh");
    }
  })
}
/** 更多按钮点击事件 */
function moreClick(event) {
  state.popup.show = true;
  state.eventList = event;
}
/** 编辑、删除日报*/
function handleSubmit(e) {
  state.popup.show = false;
  proxy.$tab.navigateTo(`/pages/business/common/projectMange/record/detailsAll?reportId=${e.id}`);
}
onReady(() => {});

onShow(() => {
  //调用系统主题颜色
  proxy.$settingStore.systemThemeColor([1]);
});

onLoad((options) => {
  state.options.reportId = options?.reportId;
  init();
});

onUnload(() => {
  projectApi()
    .ReportRecordReadFlag({ reportId: state.options.reportId })
    .then((requset) => {
      uni.$emit("projectMange_record", true); //监听器
    })
    .catch((err) => {
      uni.$emit("projectMange_record", true); //监听器
    });
});
</script>

<style lang="scss" scoped>
.content-area {
  margin: 0;
  padding: 15px 20px;
  overflow: hidden;

  &-header {
    &-avatar {
      margin: auto 0;
    }
    &-avatarImg {
      width: 35px;
      height: 35px;
      border-radius: 4px;
    }

    &-title {
      margin: 0 0 15px 0;
      font-weight: 600;
      color: #000000;
    }
  }

  &-center {
    line-height: 25px;
    &-top {
      color: #000000;
      font-weight: 600;
    }
  }
}
</style>
