/*
 * @Descripttion: 远程探视卡片组件
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-11-25 10:00:23
 * @LastEditors: OBKoro1
 * @LastEditTime: 2021-12-30 17:21:44
 */
import { fhGetRemoteVisitsList } from '../../../api/remote/index'
import { fhGetVisitInfo } from '../../../api/newborn/index'
const app = getApp()
const dayjs = require('../../../src/js/dayjs/index')
const days = ['日', '一', '二', '三', '四', '五', '六']
const nearlyDate = Array(7)
  .fill(1)
  .map((_, index) => {
    const times = Date.now() + index * 86400000
    return {
      date: dayjs(times).format('YYYY-MM-DD'),
      monthDate: dayjs(times).format('MM-DD'),
      year: new Date(times).getFullYear(),
      week: `周${days[new Date(times).getDay()]}`,
      data: []
    }
  })

const componentOptions = {
  // 组件选项
  options: {
    multipleSlots: true,
    addGlobalClass: true
  },
  behaviors: [],
  properties: {
    /* 组件枚举 */
    // default -> 默认类型（会自动把相同时间的归类）
    // nearly -> 未来七天的数据，按照未来七天（包括今天）的数据
    type: {
      type: String,
      value: 'default'
    },
    // 额外的请求参数
    params: {
      type: Object,
      value: {}
    }
  },
  // 组件数据
  data: {
    isEmpty: true,
    listData: []
  },
  // 数据监听器
  observers: {},
  // 组件方法
  methods: {
    async init(tag) {
      if(tag === 'remote') {
        const form = {}
      if (this.data.type === 'nearly') {
        form.visitStartTime = nearlyDate[0].date + ' 00:00:00'
        form.visitEndTime = nearlyDate[nearlyDate.length - 1].date + ' 23:59:59'
      }
      form.memberType = 'PATIENT'
      form.pageNumber = 1
      form.pageSize = 99999
      const memberId = app.getMemberId()
      try {
        const { results } = await fhGetRemoteVisitsList(memberId, {
          ...form,
          ...this.data.params
        })
        const arr = results.results
        arr.forEach(item=> item.visitType = 'ILLNESS')
        const data = this[this.data.type + 'Fun'](arr)
        const isEmpty = data.every(item => !item.data.length)
        this.setData({
          listData: data,
          isEmpty
        })
        return Promise.resolve({
          ...results,
          isEmpty
        })
      } catch (e) {
        console.log('debug axios', e)
      }
      }else{
        this.getVisitInfo()
      }
    },
    defaultFun(data) {
      const nameContainer = {}
      data.forEach(item => {
        nameContainer[item.visitDate] = nameContainer[item.visitDate] || []
        nameContainer[item.visitDate].push(item)
      })
      let results = Object.keys(nameContainer).map(item => ({
        date: item,
        monthDate: dayjs(item).format('MM-DD'),
        year: new Date(item).getFullYear(),
        week: `周${days[new Date(item).getDay()]}`,
        data: nameContainer[item]
      }))
      results.sort((a, b)=> {
        return b.date < a.date ? -1 : 1
      })
      return results
    },
    async getVisitInfo(){
      try{
        const phoneNumber = wx.getStorageSync('auth-phone')
        const { results } = await fhGetVisitInfo({ visitState: this.data.params.visitStateList } ,phoneNumber)
        let babyVisitRecords = results.babyVisitRecords
        babyVisitRecords.forEach(item =>{ 
          item.visitType = 'newborn'
          item.babyName = `${item.motherName}之${item.sex === 0 ? '子(男孩)' : '女(女孩)'}`
        })
        let list = [...results.babyVisitRecords, ...results.remoteVisitRecords]
        let arr = []
        list.forEach(item => {
          if(item.visitType !== 'SIGNATURE') arr.push(item)
        })
        arr = this.defaultFun(arr)
        const isEmpty = arr.every(item => !item.data.length)
        this.setData({
          listData:arr,
          isEmpty
        })
      }
      catch (e) {
        console.log('debug axios', e)
      }
    },
    nearlyFun(list) {
      const data = JSON.parse(JSON.stringify(nearlyDate))

      data.forEach(item => {
        item.data = list.filter(
          r => dayjs(r.visitDate).valueOf() === dayjs(item.date).valueOf()
        )
      })

      return data  
    },
  },
  // 组件生命周期
  lifetimes: {
    created() {},
    attached() {},
    ready() {},
    moved() {},
    detached() {}
  },
  definitionFilter() {},
  // 页面生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      // 重新执行定时器等操作
    },
    // 页面被隐藏
    hide() {
      // 清除定时器等操作
    },
    // 页面尺寸变化时
    resize() {}
  }
}

Component(componentOptions)
