import React, { Component } from "react";
import PunchClocks from './punchClocks';
import MessageNoticebar from "../../components/common/messageNoticebar";
import { AtModal, } from "taro-ui"
import Taro from "@tarojs/taro";
import { updateLocation } from '../../utils/servers/servers';

class PunchClock extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      isOpened: false,
      isHome: false,
    }
    this.onClose = this.onClose.bind(this);
    this.handleConfirm = this.handleConfirm.bind(this);
  }

  componentDidShow() {
    if (this.state.isHome) {
      Taro.eventCenter.trigger('punchClockComponentDidShow');
      //获取地区选定数据
      const chooseLocation = requirePlugin("chooseLocation");
      const location = chooseLocation.getLocation();
      if (location) {
        this.setState({
          data: location,
          isOpened: true
        })
        // 清除数据
        chooseLocation.setLocation(null);
      }
    }
  }

  onClose() {
    this.setState({
      data: {},
      isOpened: false,
      isHome: false,
    })
  }

  getId(id, uid) {
    this.setState({ id, uid })
  }
  // 判断是否是首页打卡切换位置
  getHome() {
    this.setState({ isHome: true })
  }

  handleConfirm() {
    const { id, uid, data } = this.state
    updateLocation({
      id,
      uid,
      longitude: data.longitude,
      latitude: data.latitude,
      districtName: data.name,
    }).then(v => {
      this.onClose()
      Taro.hideLoading()
      if (v.error.length === 0) {
        Taro.showToast({ title: '打卡位置已更新', icon: 'none' });
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      this.onClose()
      Taro.hideLoading()
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  componentDidMount() {
    Taro.eventCenter.trigger('GoPuncsshIn', { data: 'unread' })
  }

  render() {
    return (
      <>
        <MessageNoticebar />
        {
          // 刷新打卡页
          !this.state.isOpened && <PunchClocks getId={this.getId.bind(this)} getHome={this.getHome.bind(this)} />
        }
        <AtModal
          isOpened={this.state.isOpened}
          title='提示'
          cancelText='取消'
          confirmText='确认'
          onClose={this.onClose}
          onCancel={this.onClose}
          onConfirm={this.handleConfirm}
          content='您确定是否切换位置？切换位置，将重新提交“公出审核”，如您的公出审核已通过，则需再次审核。'
        />
      </>
    )
  }
}

export default PunchClock;
