<template>
  <div class="version">
    <div class="title">
      版本号 {{ version }}
    </div>
    <div class="content">
      <div class="other-submit">
        <div class="notification-wrap">
          <p
            class="notification"
            v-for="item in otherServices"
            :key="item.serve_name"
          >【{{ item.serve_name }}】服务将于{{ item.expire_date }}到期</p>
        </div>
      </div>

      <div style="display:flex;max-height: 50px;font-size: 18px;font-family: PingFangSC-Medium, PingFang SC;font-weight: 500;color: #333333;line-height: 25px;">
        <span
          class="iconfont iconHI"
          style="color:#63BA4E;margin-right: 8px;font-size:20px"
        />
        <div style="text-align: center;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;overflow: hidden;">
          {{ clientName }}
        </div>
      </div>
      <div class="serve-tip" v-if="expiredDate">
        服务有效期至：{{ expiredDate }} (<span :class="[expiredDay < 7 ? 'red': '']">{{ expiredDay }}天</span>)
      </div>
      <div class="serve-tip" v-if="Number(quantityData.use_ratio)>Number(quantityData.quantity_notice_ratio)">
        合同单量已用比例(剩余单量):{{ quantityData.use_ratio }} %({{ quantityData.remainder_order_quantity }}</span>)
      </div>
      
      <div style="height: 17px;font-size: 12px;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: #989898;line-height: 17px;">
        数据更新 {{ updateTime }}
        <span
          style="margin-left:8px;cursor: pointer;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: #63A4FE;"
          @click="refresh"
        >刷新</span>
      </div>
    </div>
    <Modal
      v-model="showTip"
      mask
      :mask-closable="maskClosable"
      title="服务到期提示"
      title-align="left"
      class-name="noticeTipOverDay"
      :footer-hide="hideFoot"
      width="450px"
    >
      <p style="display: flex;align-items: center;"><i class="iconfont iconios-alert alertIcon" /><span>云雀服务将于{{ expiredDate }}到期，为了保证您的正常使用，请及时续费！</span></p>
      <footer style="display: flex; justify-content: center; margin-top: 12px;padding-top: 16px;"> 
        <!-- border-top: 1px solid #DEDEDE; -->
        <Button
          type="posdefault"
          style="margin-left: 16px"
          @click="cancelDialog()"
        >
          我知道了
        </Button>
      </footer>  
    </Modal>
    <Modal
      mask
      v-model="showTipNotic"
      :mask-closable="maskClosable"
      title="单量使用提醒"
      title-align="left"
      class-name="noticeTipOverDay"
      :footer-hide="hideFoot"
      width="450px"
    >
      <p style="display: flex;align-items: center;">
        <i class="iconfont iconios-alert alertIcon" />
        当前出库单量为{{ quantityData.current_out_quantity }}，已超出您购买的总单量{{ quantityData.contract_order_quantity }}的{{ quantityData.quantity_notice_ratio }}%，请联系服务人员即时扩充
      </p>
      <footer style="display: flex; justify-content: center; margin-top: 12px;padding-top: 16px;"> 
        <!-- border-top: 1px solid #DEDEDE; -->
        <Button
          type="posdefault"
          style="margin-left: 16px"
          @click="cancelDialog()"
        >
          我知道了
        </Button>
      </footer>  
    </Modal>
  </div>
</template>

<script>
import pkg from '../../../package.json';
const R3 = window.R3;
const { network, urlSearchParams } = R3;

export default {
  name: 'LarkFrontEndServePanel',

  props: {
    clientName: {
      type: String,
      default: ''
    },
    updateTime: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      version: pkg.version,
      expiredDate: '',
      expiredDay: '',
      otherServices: [],
      speed: 5000, // 自动切换的时间间隔，单位为毫秒
      showTip: false,
      showCancel: false,
      hideFoot: true,
      maskClosable: false,
      quantity:false, // 合同占用比例
      showTipNotic:false,
      quantityData:{}
    };
  },
  created() {
    this.getServiceExpiry('login')
    this.getConfigFn();
    console.log('service_pinel_created')
  },
  mounted() {

  },
  methods: {
    // 获取版本号和产品动态列表
    async getConfigFn() {
      const res = await network.get('/p/cs/release_announce');
      const resData = res.data || {};
      const { code, data } = resData || {};
      if (code === 0) {
        const { version, release_announce:releaseList } = data || {};
        if (version) {
          this.version = version;
        }
        if (releaseList && releaseList.length) {
          const updateInfo = {
            propType: 'dynamic_list',
            data: releaseList,
          }
          this.$emit('receivePropHandle', updateInfo);
        }
      }
    },
    refresh() {
      this.getServiceExpiry('refresh')
      this.$emit('refresh')
    },
    getServiceExpiry(type) {
      network.get('/p/cs/customer_subscription').then(res => {
        if (res.data.code === 0) {
          const data = res.data.data
          // 获取云雀订阅
          const larkServiceIndex = data.findIndex(item => item.serve_name === '云雀')
          if(larkServiceIndex > -1){
            const larkService = data[larkServiceIndex]
            this.quantityData = larkService
            this.expiredDate = larkService.expire_date
            this.expiredDay = larkService.day
            this.quantity = larkService.current_out_quantity
            if(Number(larkService.use_ratio)>=Number(larkService.quantity_notice_ratio) && larkService.use_ratio){
              const today = new Date().toDateString();
              const userInfoName = JSON.parse(localStorage.userInfo).name

              const lastReminderDate = localStorage.getItem(`${userInfoName}lastReminderDate`);
                  // 如果今天还没有提醒过
                if (lastReminderDate !== today) {
                  this.showTipNotic = true
                   // 更新最后提醒日期
                  localStorage.setItem(`${userInfoName}lastReminderDate`, today);
                }
             }
            
            if((larkService.day <= larkService.notice_day) && type == 'login'){
              this.checkIsNeedPop();
              // this.recordLoginTime(larkService.day,larkService.notice_day);
              // this.$Modal.fcError({  //fcError
              //   title: '服务到期提示',
              //   mask: true,
              //   width: 450,
              //   maskClosable: false,
              //   className: 'noticeTipOverDay',
              //   okText: '我知道了',
              //   content: '云雀服务将于'+larkService.expire_date+'到期，为了保证您的正常使用，请及时续费！'
              // });
            }
          }
          // 获取其他订阅
          data.splice(larkServiceIndex, 1)
          this.otherServices = data

          // otherServices数量大于1时，需要把第一个dom再队列尾部放一个，让整个动画重置位移时，过渡更自然
          if (this.otherServices.length > 1) {
            this.otherServices.push(this.otherServices[0])
          }
          this.$nextTick(() => {
            this.setAnimation()
          })
        }
      })
    },
    getLocalDateString() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    checkIsNeedPop() {
      //  过期提示弹框是否提示过
      try {
        const userInfo = JSON.parse(window.localStorage.getItem('userInfo')) || {};
        const { id } = userInfo;
        const currentDay = this.getLocalDateString();
        const popKey = `EXPIRY_${currentDay}_${id}`;
        const isHasPoped = localStorage.getItem(popKey) || null;
        if (!isHasPoped) {
          this.showTip = true;
          localStorage.setItem(popKey, true);//今天是否提示过
        }
      } catch (error) {
        console.log(`expriy_tip_error`, error);
      }
    },
    // 判断是否今日第一次进入该页面
    recordLoginTime(day, noticeDay) {
        let firstLoginDate = localStorage.getItem('firstLoginDate') ? JSON.parse(localStorage.getItem('firstLoginDate')) : [];
        // 获取当前时间（年月日）
        let now = new Date().toLocaleDateString();
        // 转换成时间戳
        let time = Date.parse(new Date(now));
        let id = JSON.parse(window.localStorage.getItem('userInfo')).id;
        let obj = {
          time,
          id,
          day,
          noticeDay
        };
        let isHaveId = false;
        if (firstLoginDate.length > 0) {
          for (let i = 0; i < firstLoginDate.length; i++) {
            if (firstLoginDate[i].id == id) {
              isHaveId = true;
              if (time > firstLoginDate[i].time) {
                this.showTip = true;
                firstLoginDate[i].time = time;
                localStorage.removeItem('task');
                localStorage.setItem('firstLoginDate', JSON.stringify(firstLoginDate));
              } else if((day != firstLoginDate[i].day || noticeDay != firstLoginDate[i].notice_day) && (day <=noticeDay)){
                this.showTip = true;
                firstLoginDate[i].time = time;
                localStorage.removeItem('task');
                localStorage.setItem('firstLoginDate', JSON.stringify(firstLoginDate))
              }
              break;
            }
          }
          if (!isHaveId) {
            // this.selectStorageInModal = true;
            this.showTip = true;
            firstLoginDate.push(obj);
            localStorage.removeItem('task');
            localStorage.setItem('firstLoginDate', JSON.stringify(firstLoginDate));
          }
        } else {
          // this.selectStorageInModal = true;
          this.showTip = true;
          firstLoginDate.push(obj);
          localStorage.removeItem('task');
          localStorage.setItem('firstLoginDate', JSON.stringify(firstLoginDate));
        }
      },
    cancelDialog() {
      this.showTip = false;
      this.showTipNotic = false;
    },
    // 设置消息滚动动画
    setAnimation() {
      if (this._timer) {
        clearInterval(this._timer)
        this._timer = null
      }
      if (this.otherServices.length <= 0) {
        return
      }
      const doms = document.querySelectorAll('.version .notification')
      const len = doms.length
      const times = len // 有多少元素(克隆的最后一个元素除外)就向上移动多少次。每移动times次重置初始位移
      this._loopTimes = 1 // 当前循环次数
      const wrap = document.querySelector('.version .notification-wrap')
      this._timer = setInterval(() => {
        const offset = `-${16 * (this._loopTimes % times)}px`
        // console.log('移动',offset, this._loopTimes)


        wrap.style.transition = 'all 0.3s linear'
        if(this._loopTimes % times === times - 1) {
          // 滚动到最后一个元素时，等动画结束，立马重置到初始位置
          wrap.addEventListener('transitionend', this.resetPosition)
        } else {
          wrap.removeEventListener('transitionend', this.resetPosition)
        }
        wrap.style.transform = `translateY(${offset})`;

        this._loopTimes++
      }, this.speed)
    },
    // 重置位置
    resetPosition(e) {
      const dom = e.target
      dom.style.transition = 'none'
      dom.style.transform = `translateY(0)`
      this._loopTimes++
    }
  },
  beforeDestroy() {
    if (this._timer) {
      clearInterval(this._timer)
      this._timer = null
    }
  }
};
</script>

<style lang="less" scoped>
.version {
  margin-bottom: 20px;
  .title {
    height: 17px;
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    line-height: 17px;
  }
  .content {
    padding: 20px 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-bottom: 1px solid #e9e9e9;
    position: relative;
  }
  .serve-tip {
    font-size: 14px;
    margin-top: 16px;
    margin-bottom: 4px;
  }
  .other-submit {
    color: red;
    position: absolute;
    right: 0;
    top: -20px;
    text-align: right;
    height: 16px;
    line-height: 16px;
    overflow: hidden;
    // border: 1px solid green;
  }
  .red {
    color: red;
  }

}
</style>
<style lang="less">
.noticeTipOverDay {
  // width: 600px;
  font-size: 20px;
  .ark-modal {
    margin-top: 35vh;
  }
}
.noticeTipOverDay .ark-modal-header-inner {
  height: 20px !important;
  line-height: 20px !important;
  font-size: 16px!important;
}
.noticeTipOverDay .alertIcon{
  color: red !important;
  font-size: 38px;
  margin-right: 10px;
} 
.noticeTipOverDay .ark-modal-body {
  font-size: 18px;
  line-height: 28px;
}
.noticeTipOverDay .ark-modal-confirm-footer {
    text-align: center;
    margin-left: 36px;
    margin-top: 10px;
    .ark-btn {
      width: 90px;
      height: 30px;
      font-size: 14px;
      border-radius: 4px;
    }
}
</style>
