<template>
  <u-sticky class="shadow-default" bgColor="#fff" style="top: 0">
    <u-navbar :titleStyle="{ color: '#000' }" :autoBack="true" 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"></u-icon>
        </view>
      </template>
    </u-navbar>
    <u-tabs
      :list="tabsList"
      :current="tabsCurrent"
      @click="tabsClick"
      lineColor="#333"
      :activeStyle="{ color: '#333', fontSize: '14px' }"
      :inactiveStyle="{ color: '#909399', fontSize: '14px' }"
      :scrollable="false"
    ></u-tabs>
  </u-sticky>

  <oa-scroll
    customClass="record-container scroll-height"
    :pageSize="pageSize"
    :total="total"
    :isSticky="true"
    :customStyle="{
      //#ifdef APP-PLUS || MP-WEIXIN
      height: `calc(100vh - (138px + ${proxy.$settingStore.StatusBarHeight}))`,
      //#endif
      //#ifdef H5
      height: `calc(100vh - (138px))`,
      //#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 v-if="timedList.length > 0" @click="goTimingPage()" class="list-cell list-cell-arrow" style="margin: 20px 0; color: rgb(20, 158, 255); background-color: rgba(20, 158, 255, 0.1)">
        <view style="width: calc(100% - 51px); display: flex; padding-right: 10px">
          <u-icon name="info-circle" color="#2979ff" size="18" style="margin-right: 5px"></u-icon>
          <view v-if="timedList.length == 1">您有1条定时日志将于{{ timedList[0].timingTime.slice(0, 16) }}发布</view>

          <view v-else>您有{{ timedList.length }}条定时日志将于指定时间发布</view>
        </view>
      </view>

      <u-loading-page :loading="state.loading" fontSize="16" style="z-index: 99"></u-loading-page>


      <!-- start -->
      <view class="content-area" v-for="(el, index) in reportListNewData" :key="index">
        <view class="content-area-time font14" v-if="!el.id">{{ proxy.$time.jktTimes(el.submitDate, "否") }}</view>
        <view class="content-area-center bg-white" v-else style="margin:0 10px 10px;border-radius:10px">
          <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(el)"></u-icon>
          </view>
          <view class="flex mb10" @click="goContentDetails(el)">
            <img :src="el.avatar" class="content-area-center-avatarImg mr10" v-if="el.avatar" />
            <u-avatar
              v-if="!el.avatar"
              class="content-area-center-avatar mr10"
              :text="el.createBy.length > 2 ? el.createBy.slice(1, 3) : el.createBy"
              shape="square"
              size="35"
              fontSize="10"
              color="#ffffff"
              :bgColor="proxy.$settingStore.themeColor.color"
            ></u-avatar>
            <view>
              <view class="content-area-center-title font14 mb5">{{ el.createBy }}的日报</view>
              <view class="content-area-center-time font12">{{ proxy.$time.jktTimes(el.submitDate.replace("T", " ")) }}</view>
            </view>
          </view>
          <view class="mb5" @click="goContentDetails(el)">
            <u-text :text="el.contentText.length >= 100 ? el.contentText.slice(0, 100) + '···' : el.contentText" color="#666666" size="14"></u-text>
          </view>
          <view class="flex" v-if="el.createBy != useStore.nickName" @click="goContentDetails(el)">
            <u-tag class="mr10" type="info" text="已读" size="mini" plain v-if="el.readFlag === 1" style="margin: 0 auto"></u-tag>
            <u-tag class="mr10" type="error" text="未读" size="mini" plain v-if="el.readFlag === 0" style="margin: 0 auto"></u-tag>
            <u-text text="全文" :color="proxy.$settingStore.themeColor.color" size="14"></u-text>
          </view>
        </view>
      </view>
      <!-- end -->


    </template>
  </oa-scroll>

  <oa-tabbar :tabbarValue="0" :tabbarList="proxy.$constData.projectTabbar" :isSwitchTab="false"></oa-tabbar>

  <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
        v-if="state.tabsCurrent == 1"
        class="custom-style"
        type="info"
        size="normal"
        text="编辑"
        :customStyle="{
          height: '50px',
          color: '#3c9cff',
          borderWidth: 0,
          borderRadius: 0,
          borderBottomWidth: '1px',
        }"
        @click="handleSubmit('update', eventList)"
      ></u-button>
      <u-button
        class="custom-style"
        type="info"
        size="normal"
        text="一键复制"
        :customStyle="{
          height: '50px',
          color: '#3c9cff',
          borderWidth: 0,
          borderRadius: 0,
          borderBottomWidth: '1px',
        }"
        @click="handleSubmit('copy', eventList)"
      ></u-button>
      <u-button
        v-if="state.tabsCurrent == 1"
        class="custom-style"
        type="info"
        size="normal"
        text="删除"
        :customStyle="{
          height: '50px',
          color: '#f56c6c',
          borderWidth: 0,
          borderRadius: 0,
          borderBottomWidth: '3px',
        }"
        @click="handleModal('delete', `确认删除“ ${eventList.createBy} ” 的“ ${eventList.reportDate} ” 的日报？`)"
      ></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>

  <uni-popup ref="alertDialog" type="dialog">
    <uni-popup-dialog :type="state.tip.type" cancelText="取消" confirmText="确定" title="操作提醒" :content="state.tip.content" @confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
  </uni-popup>

  <u-modal
    :show="modal.show"
    title="操作提醒"
    :content="modal.content"
    :showCancelButton="true"
    :closeOnClickOverlay="true"
    @confirm="handleSubmit(state.modal.type, eventList)"
    @cancel="modal.show = false"
    @close="modal.show = false"
  ></u-modal>
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import { onLoad, onShow, onReady, onHide, onLaunch, onUnload, onNavigationBarButtonTap, onPageScroll } from "@dcloudio/uni-app";
import { ref, reactive, computed, getCurrentInstance, toRefs, inject } from "vue";
/*----------------------------------接口引入-----------------------------------*/
import { projectApi } from "@/api/business/project.js";
/*----------------------------------组件引入-----------------------------------*/
/*----------------------------------store引入-----------------------------------*/
import { useStores, commonStores } from "@/store/modules/index";
/*----------------------------------公共方法引入-----------------------------------*/
/*----------------------------------公共变量-----------------------------------*/
const { proxy } = getCurrentInstance();
const useStore = useStores();
/*----------------------------------变量声明-----------------------------------*/
const state = reactive({
  tabsList: [
    { name: "我收到的", value: 2 },
    { name: "我发出的", value: 3 },
    { name: "我负责的", value: 1 },
  ],
  tabsCurrent: 0,

  loading: false,
  reportListNewData:[],
  pageSize: 20,
  current: 1,
  total: 0,
  modalShow: false,
  modalType: "",
  modalEvent: {},

  popup: {
    show: false, //弹窗显示
    content: "", //提示信息
  },
  modal: {
    type: "", //操作类型
    show: false, //弹窗显示
    content: "", //提示信息
  },
  eventList: {}, //数据存储

  reportData: {},
  tip: {
    type: undefined, //弹框类型
    content: "", //提示信息
    data: {}, //带入数据
    operation: undefined, //操作类型
  },
  timedList: [],
  tree: [],
});

const { tabsList, tabsCurrent,reportListNewData, pageSize, current, total, popup, eventList, modal, timedList, tree } = toRefs(state);
/**
 * 操作弹框提醒
 * @param type  弹框类型
 * @param content 提示内容
 * @param item 带入数据
 * @param operation 操作类型
 */
function tips(type, content, item, operation) {
  state.tip.type = type;
  state.tip.content = content;
  state.tip.data = item;
  state.tip.operation = operation;
  proxy.$refs.alertDialog.open();
}
/**弹框确定操作 */
function dialogConfirm() {
  if (state.tip.operation == "delete") {
    handleSubmit("delete", state.tip.data);
  }
  if (state.tip.operation == "exit") {
    handleSubmit("exit", state.tip.data);
  }
  if (state.tip.operation == "copy") {
    handleSubmit("copy", state.tip.data);
  }
}
/**
 * @初始化
 */
function init() {
  let arrayList = [];
  projectApi()
    .ReportRecord({
      // startDate: "2024-07-10",
      // endDate: "2024-07-10",
      pageNum: state.current,
      pageSize: state.pageSize,
      projectAscription: state.tabsList[state.tabsCurrent].value,
    })
    .then((requset) => {
      requset.data.records.forEach((el) => {
        el.contentText = "";
        el.workContents.forEach((cl) => {
          el.contentText += `${cl.projectName} ${cl.workTime}h \n ${cl.workContent} \n`;
        });
      });
      state.total = requset.data.total;
      state.loading = false;

      var reportListData = requset.data.records;
      var groupBySubmitTime = reportListData.reduce((acc, current) => {
        const existIndex = acc.findIndex((item) => item.submitDate.slice(0, 10) === current.submitDate.slice(0, 10));
        if (existIndex === -1) {
          acc.push({ submitDate: current.submitDate, items: [current] });
        } else {
          acc[existIndex].items.push(current);
        }
        return acc;
      }, []);

      groupBySubmitTime.forEach(function (item, index) {
        item.items.unshift({ submitDate: item.submitDate });
        item.items.forEach(function (aa) {
          arrayList.push(aa);
        });
      });

      state.reportListNewData = arrayList;





      
    })
    .catch((err) => {
      state.loading = false;
    });
  projectApi()
    .TimedReports({})
    .then((requset) => {
      state.timedList = requset.data;
    })
    .catch((err) => {});
}

/**
 * @跳转详情
 */
function goContentDetails(e) {
  if (state.tabsCurrent == 0 && e.readFlag != 1) {
    projectApi()
      .ReportRecordReadFlag({ reportId: e.id })
      .then((res) => {
        if (res.status == "SUCCESS") {
          proxy.$tab.navigateTo(`/pages/business/common/projectMange/record/details?reportId=${e.id}`);
        } else {
          proxy.$modal.msgError("读取异常");
        }
      });
  } else {
    proxy.$tab.navigateTo(`/pages/business/common/projectMange/record/details?reportId=${e.id}`);
  }
}

/**
 * @scrollView加载数据
 */
function load() {
  state.pageSize += 10;
  init();
}

/**
 * @scrollView刷新数据
 */
function refresh() {
  state.pageSize = 20;
  init();
}

/**
 * @tabs点击事件
 */
function tabsClick(e) {
  state.tabsCurrent = e.index;
  init();
}

// 定时日志页面
function goTimingPage() {
  proxy.$tab.navigateTo(`/pages/business/common/projectMange/record/timingLog`);

  // proxy.$tab.navigateTo(`/pages/business/common/projectMange/report/timingLog`);
}
/** 更多按钮点击事件 */
function moreClick(event) {
  state.popup.show = true;
  state.eventList = event;
}

function handleModal(type, content) {
  state.modal.show = true;
  state.modal.type = type;
  state.modal.content = content;
}

/** 编辑、删除日报*/
function handleSubmit(type, item) {
  if (type === "update") {
    proxy.$tab.navigateTo(`/pages/business/common/projectMange/write/insert?templateId=1&id=${item.id}`);
    state.modal.show = false;
  } else if (type === "copy") {
    var workLongString = "";
    item.workContents.forEach((item) => {
      workLongString += item.projectName + ":" + item.workTime + "h\n" + item.workContent + "\n";
    });
    item.ccTo1 = item.ccTo.split(",").map(function (value, index) {
      return Number(value);
    });

    /** 查询树结构用户列表  回显抄送人*/

    item.tomorrowPlan = item.tomorrowPlan ? item.tomorrowPlan : "-";
    item.coordinateWork = item.coordinateWork ? item.coordinateWork : "-";
    // 触发方法
    proxy.$common.uniCopy({
      content: workLongString + "\n" + "明日计划:\n" + item.tomorrowPlan + "\n" + "工作协调:\n" + item.coordinateWork,
      success: (res) => {
        uni.showToast({
          title: res,
          icon: "none",
        });
      },
      error: (e) => {
        uni.showToast({
          title: e,
          icon: "none",
          duration: 3000,
        });
      },
    });
    state.popup.show = false;
  } else if (type === "delete") {
    projectApi()
      .ReportDelete(item.id)
      .then(() => {
        proxy.$modal.msg("日报删除成功！");
        state.modal.show = false;
        state.popup.show = false;
        init();
      })
      .catch((errors) => {
        proxy.$modal.msg(errors);
      });
  }
  state.modalShow = false;
}

onReady(() => {});

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

onLoad((options) => {
  init();
  uni.$on("projectMange_record", function (value) {
    init();
  });
});

onUnload(() => {
  uni.$off("projectMange_record"); //将值删除监听器
});
</script>

<style lang="scss" scoped>
.content-area {
  &-time {
    padding: 10px;
    text-align: left;
    color: #000000;
    font-weight: 600;
  }

  &-center {
    margin: 0;
    padding: 15px;
    overflow: hidden;
    border-bottom: 1px solid #eaeef1;

    &:last-child {
      border-bottom: 0px solid #eaeef1;
    }

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

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

.pp {
  text-align: left;
}
</style>
<style>
.pp .u-modal__content {
  justify-content: left !important;
}
</style>
