import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import dateformat from 'dateformat'
import CtsDateSelector from '../date-selector'

import classNames from 'classnames'
import PropTypes, { InferProps } from 'prop-types'
import CtsComponent from '../../common/component'
import { CtsDateRecordProps, CtsDateRecordState } from 'types/date-record'

/**
 * 日历组件
 */
export default class CtsDateRecord extends CtsComponent<CtsDateRecordProps, CtsDateRecordState> {
  // static options = {
  //   addGlobalClass: true
  // }

  public static defaultProps: CtsDateRecordProps
  public static propTypes: InferProps<CtsDateRecordProps>

  public constructor(props: CtsDateRecordProps) {
    super(props)
    this.state = {
      checkMonth: dateformat(new Date(), 'yyyy-mm'),
      checkDate: dateformat(new Date(), 'yyyy-mm-dd'),
      dateArr: [],
      isCurrentMonth: false
    }
  }

  public componentDidMount(): void {
    // 初始化日期数据
    const { checkMonth, checkDate, data } = this.props
    this.setState({
      checkMonth,
      checkDate
    }, () => {
      this.initDateArr(data)
    })
  }

  public componentWillReceiveProps(props: CtsDateRecordProps): void {
    // 初始化日期数据
    const { checkMonth, checkDate, data } = props
    this.setState({
      checkMonth,
      checkDate
    }, () => {
      this.initDateArr(data)
    })
  }

  // 初始化日期数据
  private initDateArr(data): void {
    const { mode } = this.props
    // console.log('日期数据：', data)

    // data.push({
    //   confirmStatus: 1,
    //   isDst: false,
    //   workDate: '2019-09-06',
    //   workMonth: '2019-09',
    //   worktime: 2
    // })

    // 记工的日期字段名是workDate，考勤的日期字段名是checkDate，打卡考勤的日期字段名是date
    let memberArr: any[] = []
    for (let item of data) {
      switch (mode) {
        case 'recordwork':
          memberArr.push(new Date(item.workDate).getDate())
          break
        case 'checkwork':
          memberArr.push(new Date(item.checkDate).getDate())
          break
        case 'checking':
          memberArr.push(new Date(item.date).getDate())
          break
        default:
          break
      }
    }

    // console.log(memberArr)

    let arr: any[] = [] // 所有日期数组数据

    // 这个月1日是星期几，这个月有多少天，获取上个月有多少天
    let d = new Date(this.state.checkMonth)
    d.setMonth(d.getMonth() + 1) // 下个月

    d.setDate(0) // 这个月最后一天
    let currentMonthDays = d.getDate() // 这个月有多少天
    // console.log(currentMonthDays)

    d.setDate(1) // 这个月第一天
    let firstDay = d.getDay() // 这个月1日是星期几
    // console.log(firstDay)

    d.setDate(0) // 上个月最后一天
    let prevMonthDays = d.getDate() // 上个月有多少天
    // console.log(prevMonthDays)

    // 上个月循环
    for (let i = firstDay; i > 0; i--) {
      arr.push({ status: 1, value: prevMonthDays + 1 - i })
    }
    // console.log(arr)
    // console.log(typeof new Date().getDate())

    // 是否是当前月
    const isCurrentMonth = Taro['common'].isCurrentDate(this.state.checkMonth, 'M')
    // console.log(isCurrentMonth)
    this.setState({ isCurrentMonth })

    // 当前月的日期循环
    for (let i = 1; i <= currentMonthDays; i++) {

      // 先判断是否是当前月
      if (isCurrentMonth) {
        // 判断是否是大于当前天，就为超出范围
        if (i > new Date().getDate()) {
          arr.push({ status: 1, value: i })
          continue
        }
      }

      // 返回的数据是否对应
      let index = memberArr.indexOf(i)
      // console.log(index)

      if (index > -1) {
        // 判断是记工还是考勤，字段不一样
        if (mode === 'recordwork') {
          // 记工

          // isDst：true为休息，false为未休息
          if (data[index].isDst) {
            arr.push({ status: 3, value: i })
          } else {
            // confirmStatus：0为未确认，1为已确认，统一为已记工状态
            if (data[index].confirmStatus === 0) {
              arr.push({ status: 4, value: i, isConfirm: true })
            } else if (data[index].confirmStatus === 1) {
              arr.push({ status: 2, value: i, worktime: data[index].worktime })
            }
          }
        } else if (mode === 'checkwork') {
          // 考勤

          if (data[index].type === 0) { // 休息
            arr.push({ status: 3, value: i })
          } else if (data[index].type === 1) { // 正常出勤
            arr.push({ status: 2, value: i })
          } else { // 缺勤
            arr.push({ status: 4, value: i })
          }
        } else if (mode === 'checking') {
          // 打卡考勤
          if (data[index].type === 0) { // 正常
            arr.push({ status: 0, value: i })
          } else if (data[index].type === 2) { // 异常（迟到，早退，缺卡）
            arr.push({ status: 2, value: i })
          }
        }
      } else {
        if (mode === 'checking') {
          arr.push({ status: 1, value: i }) // 考勤：未打卡4
        } else { 
          arr.push({ status: 4, value: i }) // 迟到，早退，缺卡
        }
      }
    }
    // console.log('日历状态：', arr)

    // 下个月循环
    for (let i = 0; i < 35 - (firstDay + currentMonthDays); i++) {
      arr.push({ status: 1, value: i + 1 })
    }
    // console.log(arr)
    this.setState({
      dateArr: arr
    }, () => {
      // console.log(this.state.checkDate)
    })
  }

  // 选择当前月份
  private onMonthChange(val: string): void {
    let checkDate = this.state.checkDate

    // 判断是否为当前月，是则默认为当前日期，默认今天，否则默认返回上个月的1号
    if (new Date(val).getMonth() === new Date().getMonth()) {
      checkDate = dateformat(new Date(), 'yyyy-mm-dd')
    } else {
      let d = new Date(val)
      d.setDate(1)
      checkDate = dateformat(d, 'yyyy-mm-dd')
    }

    // console.log(val, checkDate)

    this.setState({
      checkMonth: dateformat(val, 'yyyy-mm'),
      checkDate
    }, () => {
      this.props.onMonthChange(dateformat(this.state.checkMonth, 'yyyy/mm'))
    })
  }

  // 选择当前日期
  private onDateChange(val: any): void {
    // console.log(val)
    // console.log(this.state.checkMonth)

    // 记工才有点击事件，考勤没有
    // if(this.props.mode === 'checkwork') return

    // 根据当前月，获取当前日期
    let date = new Date(this.state.checkMonth)
    date.setDate(val.value)
    // console.log(date)

    if (val.status === 1) return

    this.setState({
      checkDate: dateformat(date, 'yyyy-mm-dd')
    }, () => {
      this.props.onDateChange(dateformat(this.state.checkDate, 'yyyy/mm/dd'))
    })
  }

  public render(): JSX.Element {
    let { className, mode, checkDate } = this.props
    let { checkMonth, dateArr, isCurrentMonth } = this.state

    return (
      <View className={classNames('cts-date-record', className)}>
        <CtsDateSelector mode='month' data={checkMonth} onChange={this.onMonthChange.bind(this)} />

        <View className='recordwork-week'>
          <Text>日</Text><Text>一</Text><Text>二</Text><Text>三</Text><Text>四</Text><Text>五</Text><Text>六</Text>
        </View>

        {
          (mode === 'recordwork' || mode === 'checkwork') &&
          <View className='recordwork-day'>
            {
              dateArr.map((item, index) => {
                return (
                  <View
                    className={`
                    recordwork-day-item 
                    status${item.status} 
                    ${(new Date(checkDate).getDate() === item.value && item.status !== 1 && mode === 'recordwork') && 'status6'} 
                    ${(isCurrentMonth && new Date().getDate() === item.value && mode === 'recordwork' && item.status !== 1) && 'status5'}
                    ${mode === 'checkwork' ? 'status2-checkwork' : ''}
                  `}
                    key={String(index)}
                    onClick={this.onDateChange.bind(this, item)}
                  >
                    {/* {
                      // 状态提示，在status为3：休息，4：未记工时
                      item.status === 4 && <View className='status-tip tip1'>缺</View>
                    }
                    {
                      // 状态提示，在status为3：休息，4：未记工时
                      item.status === 3 && <View className='status-tip tip2'>休</View>
                    } */}

                    {
                      // 正常出勤 - 已记工 并且 缺勤 - 未记工
                      item.status === 2 || item.status === 3 || item.status === 4 ?
                        <View className='text' style={{ marginTop: Taro.pxTransform(0) }}>
                          <View className='recordwork-value'>{item.value}</View>
                          {
                            (mode === 'recordwork' && isCurrentMonth && new Date().getDate() === item.value && item.status === 4 && !item.isConfirm) ?
                              <View className='statusPos status5-text text2'>今天</View>
                              :
                              // 正常出勤 - 已记工
                              item.status === 2 ?
                                <View className='statusPos text1'>
                                  {
                                    mode === 'recordwork' ?
                                      `${item.worktime}天`
                                      :
                                      '出勤'
                                  }
                                </View>
                                :
                                // 休息 - 休息
                                item.status === 3 ?
                                  <View className='statusPos text1'>休息</View>
                                  :
                                  // 缺勤 - 未记工
                                  <View className='statusPos text2'>
                                    {
                                      mode === 'recordwork' ?
                                        `${item.isConfirm ? '未确认' : '未记工'}`
                                        :
                                        '缺勤'
                                    }
                                  </View>
                          }
                        </View>
                        :
                        <View>
                          <View>{item.value}</View>
                          <View className='statusPos'>{item.worktime}</View>
                        </View>
                    }
                  </View>
                )
              })
            }
          </View>
        }

        {
          mode === 'checking' &&
          <View className='recordwork-day checking-day'>
            {
              dateArr.map((item, index) => {
                return (
                  <View
                    className={`
                    recordwork-day-item 
                    status${item.status}
                    ${(new Date(checkDate).getDate() === item.value && item.status !== 1) && 'status6'} 
                  `}
                    key={String(index)}
                    onClick={this.onDateChange.bind(this, item)}
                  >
                    {
                      // 正常0，异常2(迟到，早退，缺卡)，未打卡4
                      (item.status === 0 || item.status === 2 || item.status === 4) ?
                        <View className='text' style={{ marginTop: Taro.pxTransform(0) }}>
                          <View className='recordwork-value'>{item.value}</View>
                          <View className={'checking-status-show ' + (item.status === 2 ? 'warning' : '')} style={{ visibility: (item.status === 0 || item.status === 2) ? 'visible' : 'hidden' }}></View>
                        </View>
                        :
                        <View>
                          <View>{item.value}</View>
                        </View>
                    }

                  </View>
                )
              })
            }
          </View>
        }

        {
          // 打卡考勤不显示
          mode !== 'checking' &&
          <View className='recordwork-note'>
            {
              mode === 'checkwork' &&
              <View>
                <Text className='status status2_'></Text>
                <Text className='status-note'>出勤</Text>
              </View>
            }
            <View>
              <Text className='status status4_'></Text>
              <Text className='status-note'>{mode === 'checkwork' ? '缺勤' : '未记工'}</Text>
            </View>
            <View>
              <Text className='status status3_'></Text>
              <Text className='status-note'>{mode === 'checkwork' ? '休息' : '已记工/记录休息/正常休息日'}</Text>
            </View>
          </View>
        }

      </View>
    )
  }
}

CtsDateRecord.defaultProps = {
  mode: 'recordwork',
  checkMonth: dateformat(new Date(), 'yyyy-mm'),
  checkDate: dateformat(new Date(), 'yyyy-mm-dd'),
  data: [],
  onMonthChange() { },
  onDateChange() { }
}

CtsDateRecord.propTypes = {
  mode: PropTypes.oneOf(['recordwork', 'checkwork', 'checking']),
  checkMonth: PropTypes.string,
  checkDate: PropTypes.string,
  date: PropTypes.array,
  onMonthChange: PropTypes.func,
  onDateChange: PropTypes.func
}