<template>
  <view class="backlog-list">
    <view class="list-container">
      <view
        v-for="(item, index) in typeMap"
        :key="index"
        class="list-item"
        @click="handleTo(item.type)">
        <view class="list-item-body">
          <image :src="item.icon" class="label-icon" alt="" />

          <view class="main-info">
            <view class="box">
              <view class="left title">
                {{ item.label }}
              </view>
              <view
                v-if="item.firstData"
                class="time">
                {{ item.firstData | formatTime }}
              </view>
            </view>
            <view class="box desc">
              <view class="left text">
                {{ formatMsg(item) || '&nbsp;' }}
              </view>
              <view v-if="item.num && item.num > 0" class="num">
                {{ item.num > 99 ? '99+' : item.num }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import * as API from 'API/crm/message'
  import { MessageNum } from 'API/crm/message'
  import { WaitingQueryOaExamineList } from 'API/oa/examine.js'

  import { mapGetters } from 'vuex'
  import moment from 'moment'

  export default {
    name: 'BacklogList',
    filters: {
      formatTime(firstData) {
        if (!firstData.updateTime) return '--'
        return moment(firstData.updateTime).format('MM月DD日')
      }
    },
    data() {
      return {
        detailComponent: '',
        height: 0,

        loading: false,
        backlogDetail: {},
        examineList: [],

        activate: true,

        typeMap: [
          {
            label: '今日需联系线索',
            type: 11,
            component: 'DetailLeadsItem',
            fn: API.TodayLeads,
            icon: this.$static('images/backlog/today_leads.png'),
            firstData: null,
            field: 'todayLeads'
          },
          {
            label: '今日需联系客户',
            type: 1,
            component: 'DetailCustomerItem',
            fn: API.TodayCustomer,
            icon: this.$static('images/backlog/today_customer.png'),
            firstData: null,
            field: 'todayCustomer'
          },
          {
            label: '今日需联系商机',
            type: 12,
            component: 'DetailBusinessItem',
            fn: API.TodayBusiness,
            icon: this.$static('images/backlog/today_business.png'),
            firstData: null,
            field: 'todayBusiness'
          },
          {
            label: '分配给我的线索',
            type: 2,
            component: 'DetailLeadsItem',
            fn: API.FollowLeads,
            icon: this.$static('images/backlog/leads.png'),
            firstData: null,
            field: 'followLeads'
          },
          {
            label: '分配给我的客户',
            type: 3,
            component: 'DetailCustomerItem',
            fn: API.FollowCustomer,
            icon: this.$static('images/backlog/my_customer.png'),
            firstData: null,
            field: 'followCustomer'
          },
          {
            label: '待进入公海的客户',
            type: 4,
            component: 'DetailCustomerItem',
            fn: API.PutInPoolRemind,
            icon: this.$static('images/backlog/seas.png'),
            firstData: null,
            field: 'putInPoolRemind'
          },
          {
            label: '待审核的合同',
            type: 5,
            component: 'DetailContractItem',
            fn: API.CheckContract,
            icon: this.$static('images/backlog/wait_contract.png'),
            firstData: null,
            field: 'checkContract'
          },
          {
            label: '待审核的回款',
            type: 6,
            component: 'DetailReceivablesItem',
            fn: API.CheckReceivables,
            icon: this.$static('images/backlog/wait_refound.png'),
            firstData: null,
            field: 'checkReceivables'
          },
          {
            label: '待回款提醒',
            type: 7,
            component: 'DetailAwaitReceivablesItem',
            fn: API.RemindReceivablesPlan,
            icon: this.$static('images/backlog/remind-refound.png'),
            firstData: null,
            field: 'remindReceivablesPlan'
          },
          {
            label: '即将到期的合同',
            type: 8,
            component: 'DetailContractItem',
            fn: API.EndContract,
            icon: this.$static('images/backlog/over_contract.png'),
            firstData: null,
            field: 'endContract'
          },
          {
            label: '待审核的办公',
            type: 100,
            component: 'DetailExaminationItem',
            fn: WaitingQueryOaExamineList,
            icon: this.$static('images/backlog/oa.png'),
            firstData: null,
            field: 'examineNum'
          }
        ]
      }
    },
    computed: {
    ...mapGetters({
      authData: 'user/authData'
    })
    },
    mounted() {
      this.getMessageNum()
    },
    wkActivated() {
      this.getMessageNum()
    },
    methods: {
      getMessageNum() {
        if (this.loading) return
        this.loading = true
        Promise.all([
          MessageNum(),
          WaitingQueryOaExamineList({
            limit: 1,
            page: 1,
            status: 1
          })
        ]).then(resArr => {
          this.loading = false
          const res = {
          ...resArr[0],
          examineNum: resArr[1].totalRow
          }
          this.examineList = resArr[1].list || []
          const keys = [
            'todayCustomer',
            'followLeads',
            'followCustomer',
            'putInPoolRemind',
            'endContract',
            'checkContract',
            'checkReceivables',
            'remindReceivablesPlan',
            'todayLeads',
            'todayBusiness',
            'examineNum'
          ]
          const data = {}
          keys.forEach(key => {
            this.backlogDetail[key] = Number(res[key]) || 0
            data[key] = Number(res[key]) || 0
          })
          this.typeMap = this.typeMap.filter(o => res.hasOwnProperty(o.field))
          this.setNumber()
        }).catch(() => {
          this.loading = false
          this.backlogDetail = {}
          this.setNumber()
        })
      },

      /**
       * 设置待办事项数量
       */
      setNumber() {
        let data = this.backlogDetail
        this.typeMap.forEach((item, index) => {
          if (data.hasOwnProperty(item.field)) {
            item.num = data[item.field] || 0
          } else {
            item.num = 0
          }
          this.$set(this.typeMap, index, item)
        })
        this.getFirstData()
      },

      /**
       * 获取每一项的第一条待办
       */
      getFirstData() {
        this.typeMap.forEach((typeObj, index) => {
          if (typeObj.num > 0) {
            let params = {
              page: 1,
              limit: 1
            }
            if (typeObj.type === 9) {
              params.status = 1
            } else {
              params = Object.assign(params, {type: 1, isSub: 1})
            }

            if (typeObj.type !== 10) {
              typeObj.fn(params).then(res => {
                console.log(typeObj.label, res.list)
                typeObj.firstData = res.list[0] || null
                this.$set(this.typeMap, index, typeObj)
              }).catch(() => {})
            } else if (typeObj.type === 9) {
              typeObj.firstData = this.examineList[0] || null
              this.$set(this.typeMap, index, typeObj)
            } else {
              typeObj.fn({
                page: 1,
                limit: 1,
                by: 1
              }).then(res => {
                console.log(typeObj.label, res.list)
                typeObj.firstData = res.list[0] || null
                this.$set(this.typeMap, index, typeObj)
              }).catch()
            }
          }
        })
      },

      formatMsg(data) {
        // 1今日需联系客户 2分配给我的线索 3分配给我的客户 4待进入公海的客户 5待审核合同
        // 6待审核回款 7待回款提醒 8即将到期的合同 9待回访合同 10待审核发票
        let num = data.num
        if (num === 0) return `暂无${data.label}`
        let str = ''
        let obj = data.firstData
        if (!obj) return `暂无${data.label}`
        if (num > 1) {
          switch (data.type) {
          case 1:
            str = `${obj.customerName}等${num}个客户需要您今日联系`
            break;
          case 2:
            str = `${obj.leadsName}等${num}个线索需要您今日跟进`
            break;
          case 3:
            str = `${obj.customerName}等${num}个客户需要您今日跟进`
            break;
          case 4:
            str = `${obj.customerName}等${num}个客户即将进入公海`
            break;
          case 5:
            str = `您有${num}个新的合同正在等待审批`
            break;
          case 6:
            str = `您有${num}个回款申请正在等待审批`
            break;
          case 7:
            str = `您有${num}个回款计划即将到期`
            break;
          case 8:
            str = `${obj.name}等${num}个合同即将到期`
            break;
          case 9:
            // 待回访合同
            break;
          case 10:
            // 待审核发票
            break;
          case 11:
            str = `${obj.leadsName}等${num}个线索需要您今日联系`
            break;
          case 12:
            str = `${obj.businessName}等${num}个商机需要您今日联系`
            break;
          case 100:
            str = `${obj.createUser.realname}等${num}人发起了申请，正在等待您的审批`
            break;
          }
        } else {
          switch (data.type) {
          case 1:
            str = `${obj.customerName}需要您今日联系`
            break;
          case 2:
            str = `${obj.leadsName}需要您今日跟进`
            break;
          case 3:
            str = `${obj.customerName}需要您今日跟进`
            break;
          case 4:
            str = `${obj.customerName}还有${obj.poolDay}天即将进入公海`
            break;
          case 5:
            str = `${obj.ownerUserName}提交了新的合同，正在等待您的审批`
            break;
          case 6:
            str = `${obj.ownerUserName}提交了回款申请，正在等待您的审批`
            break;
          case 7:
            str = `${obj.customerName}的第${obj.num}期回款即将到期`
            break;
          case 8:
            str = `${obj.name}即将到期`
            break;
          case 9:
            // 待回访合同
            break;
          case 10:
            // 待审核发票
            break;
          case 11:
            str = `${obj.leadsName}需要您今日联系`
            break;
          case 12:
            str = `${obj.businessName}需要您今日联系`
            break;
          case 100:
            str = `${obj.createUser.realname}发起了${obj.categoryTitle}，正在等待您的审批`
            break;
          }
        }
        return str || ''
      },

      handleTo(type) {
        let path = type !== 1 ? '/pages_message/backlogDetailTab' : '/pages_message/backlogDetailFilter'
        // if (type === 10) path = 'oa/journal'
        this.$Router.navigateTo({
          url: path,
          query: {
            type: type === 10 ? 2 : type
          }
        })
      },
    }
  }
</script>

<style scoped lang="scss">
.backlog-list {
  width: 100%;
  height: 100%;
  overflow: auto;

  .list-container {
    flex: 1;
    padding: 15rpx 0;
    overflow: auto;

    .list-item {
      width: 100%;
      background-color: white;
      padding: 0 32rpx;
      &:last-child {
        border-bottom: 0 none;
      }

      .list-item-body {
        text-align: left;
        border-bottom: 1rpx solid $border-color;
        padding: 18rpx 0;
        @include left;

        .label-icon {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          margin-right: 20rpx;
        }

        .main-info {
          flex: 1;
          font-size: 30rpx;
          overflow: hidden;
          .box {
            @include left;
            &.desc {
              margin-top: 10rpx;
            }
            .left {
              flex: 1;
              margin-right: 20rpx;
              @include ellipsis;
            }
            .title {
              font-weight: 500;
            }
            .time {
              color: #999;
              font-size: 26rpx;
            }

            .text {
              font-size: 28rpx;
              color: $gray;
            }
            .num {
              min-width: 36rpx;
              height: 36rpx;
              line-height: 36rpx;
              font-size: 24rpx;
              padding: 0 5rpx;
              color: white;
              border-radius: 36rpx;
              background-color: $error;
              @include center;
            }
          }
        }
      }
    }
  }
}
</style>
