import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Input, Textarea, View, Text, Picker, Button, Image } from '@tarojs/components'
import Taro from '@tarojs/taro';
import {
  AtButton, AtModal, AtModalContent, AtModalAction
} from "taro-ui";
import dayjs from 'dayjs';
import Skeleton from 'taro-skeleton'
import HistoricalClock from '../../components/historicalClock';
import ImagePicker from '../../components/common/imagePicker';
import { add, minus, asyncAdd } from '../../actions/counter'
import { recordAdd, myDuration, getInfo, } from '../../utils/servers/servers';
import Select from "../../image/dui.png";
import './index.less';
import 'taro-ui/dist/style/components/noticebar.scss';
import 'taro-ui/dist/style/components/icon.scss';
import 'taro-ui/dist/style/components/list.scss';
import "taro-ui/dist/style/components/radio.scss";
import "taro-ui/dist/style/components/icon.scss";

@connect(({ counter }) => ({
  counter
}), (dispatch) => ({
  add() {
    dispatch(add())
  },
  dec() {
    dispatch(minus())
  },
  asyncAdd() {
    dispatch(asyncAdd())
  }
}))

class PunchClocks extends Component {
  constructor(props) {
    super(props);
    this.state = {
      imgs: [],
      nowTime: '00:00:00',
      loading: false,
      selector: [{ value: 0, lable: "调研阶段" },],
      dateSel: dayjs().format('YYYY-MM-DD'),
      duration: "",
      selectorChecked: {},
      remark: "",
      data: {},
      isOpened: false,
      clockId: "",
    }
    this.onChange = this.onChange.bind(this);
    this.publicReleaseClockIn = this.publicReleaseClockIn.bind(this);
    this.onClose = this.onClose.bind(this);
  }
  nowTime = null;

  componentDidMount() {
    this.imagePickerRef && this.imagePickerRef.clear();
    this.getInfo()
  }

  getInfo() {
    getInfo().then(v => {

    })
  }
  componentWillMount() {
    this.nowTime = setInterval(() => {
      this.setState({
        nowTime: dayjs().format('HH:mm:ss')
      })
    }, 1000)

    Taro.eventCenter.on('GoPunchIn', (arg) => {
      this.setState({
        data: arg
      })
    })
  }

  componentDidHide() {

  }

  onChange(value, type) {
    let arr = this.state.imgs.concat([]);
    if (type === "add") {
      arr.push(value);
    } else if (type === "remove") {
      arr.splice(value, 1);
    }
    this.setState({
      imgs: arr,
    });
  }

  publicReleaseClockIn() {
    if (!this.state.dateSel) {
      Taro.showToast({ title: '请选择研发时间！', icon: 'none' });
      return
    }
    if (!this.state.duration) {
      Taro.showToast({ title: '请填写研发工时！', icon: 'none' });
      return
    }
    if (!this.state.selectorChecked) {
      Taro.showToast({ title: '请选择研发阶段！', icon: 'none' });
      return
    }
    Taro.showLoading({ title: '打卡中...' });
    recordAdd({
      pid: this.state.data.id,
      projectStatus: this.state.selectorChecked.value,
      duration: this.state.duration,
      content: this.state.remark,
      annexUrl: this.state.imgs.join(','),
      processStatus: 1,
      recordTime: this.state.dateSel,
    }).then(v => {
      Taro.hideLoading()
      if (v.code === 200) {
        Taro.showToast({ title: '打卡成功', icon: 'none' });
        this.setState({
          clockId: v.data.id,
          isOpened: true,
        })
      } else {
        Taro.showToast({ title: v.msg, icon: 'none' })
      }
    }).catch(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  refresh() {
    this.getData(() => {
      Taro.startLocationUpdate({
        success: () => {
          Taro.onLocationChange((v) => {
            this.getSpacing(v.latitude, v.longitude)
          })
        }
      })
    });
  }

  onClose() {
    const { clockId } = this.state
    this.imagePickerRef && this.imagePickerRef.clear();
    this.setState({
      dateSel: dayjs().format('YYYY-MM-DD'),
      duration: "",
      selectorChecked: {},
      remark: "",
      imgs: [],
      isOpened: false,
    })
    if (!!clockId) {
      Taro.navigateTo({
        url: `/pages/detail/index?id=${clockId}&type=0`
      })
    }
  }

  render() {
    const { data } = this.state;
    return (
      <View className='punchClock'>
        <View className='header'>
          <Skeleton
            title
            avatar
            row={2}
            animateName='elastic'
            avatarShape='square'
            loading={this.state.loading}
          >
            {
              !data.id ?
                <View className='content'>
                  <View className='punchClockContent'
                    onClick={this.publicReleaseClockIn}
                    style={{
                      boxShadow: '1px 1px 15px 1px #acb8ad',
                      background: '#828e83',
                      marginTop: '85px',
                    }}>
                    <View className='punchClockTitle'>研发打卡</View>
                    <View className='punchClockTime'>{this.state.nowTime}</View>
                  </View>
                  <View className='noData'>
                    <View className='tipsNoData'>
                      {/* 暂无打卡项目 */}
                    </View>
                    <View className='goOut' onClick={() => {
                      Taro.switchTab({
                        url: '/pages/project/index',
                      })
                    }}>
                      点击前往选择项目
                    </View>
                  </View>
                </View> :
                <View className='headerContent'>
                  <View className='item' style={{ width: "100%", display: "flex", flexDirection: "row", JustifyContent: "space-between" }}>
                    <View className="item_name">{data.name}</View>
                    <AtButton type="primary" size="small"
                      onClick={() => {
                        Taro.switchTab({
                          url: "/pages/project/index",
                        });
                      }}>切换</AtButton>
                  </View>

                  <View className='item'>
                    <View className='ititle'><Text style={{ color: "red", width: "7px" }}>*</Text>研发时间：
                      <Picker mode='date'
                        onChange={e => {
                          this.setState({
                            dateSel: e.detail.value
                          })
                        }}>
                        <View className='picker'>
                          {!!this.state.dateSel ? this.state.dateSel : "请选择"}
                        </View>
                      </Picker>
                    </View>
                  </View>

                  <View className='items'>
                    <View className='ititle'><Text style={{ color: "red", width: "7px" }}>*</Text>研发工时：
                      <Input value={this.state.duration} type='digit' className='input' placeholder='请输入'
                        style={{ textAlign: "center", background: "#D7D7D7", borderRadius: "15px", padding: "3px 5px" }}
                        // border: "1px solid #d6e4ef",
                        onInput={e => {
                          this.setState({
                            duration: e.detail.value
                          })
                        }}
                      />小时&nbsp;
                      <Text style={{ color: "red", fontSize: "10px" }}>注：工时可含1个小数点</Text>
                    </View>
                  </View>

                  <View className='item'>
                    <View className='ititle'><Text style={{ color: "red", width: "7px" }}>*</Text>研发阶段：
                      <Picker mode='selector' range={this.state.selector} rangeKey="lable"
                        onChange={e => {
                          this.setState({
                            selectorChecked: this.state.selector[e.detail.value]
                          })
                        }}>
                        <View className='picker'>
                          {!!this.state.selectorChecked.lable ? this.state.selectorChecked.lable : "请选择"}
                        </View>
                      </Picker>
                    </View>
                  </View>

                  <View className='items'>
                    <View className='ititles'><Text style={{ width: "7px" }}></Text>研发记录：
                      <Textarea
                        value={this.state.remark}
                        placeholder="请填写研发过程记录"
                        style='background:#D7D7D7;width:66%;min-height:70px;padding:10px;border-radius: 10px'
                        autoHeight
                        onInput={e => {
                          this.setState({
                            remark: e.detail.value
                          })
                        }}
                      />
                    </View>
                  </View>
                  <View className='items'>
                    <View className='ititles'><Text style={{ width: "7px" }}></Text>上传附件：</View>
                    <ImagePicker
                      showAddBtn
                      ref={(ref) => (this.imagePickerRef = ref)}
                      url="/api/project/upload"
                      onChange={this.onChange}
                    />
                    <View>
                      <Text className='text'>注：包括研发日志、实验报告、实验记录、检测报告、会议纪要、会议照片等</Text>
                    </View>
                  </View>

                  <View className='content'>
                    <View className='punchClockContent'
                      onClick={this.publicReleaseClockIn}
                      style={{
                        boxShadow: '1px 1px 15px 1px #acb8ad',
                        background: '#009DD9',
                      }}>
                      <View className='punchClockTitle'>研发打卡</View>
                    </View>
                  </View>
                </View>
            }
          </Skeleton>
        </View >

        <AtModal
          width="90%"
          isOpened={this.state.isOpened}
        // onClose={this.props.onClose}
        // onCancel={this.props.onClose}
        >
          <AtModalContent>
            <View className='tips'>
              <Image src={Select} className="img" />
              <View className="tit">成功打卡</View>
              <View className="txt">您的研发打卡，已经确定</View>
              <View className="txt">请注意查看打卡审核情况！</View>
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button onClick={this.onClose}>确定</Button>
          </AtModalAction>
        </AtModal>

      </View >
    )
  }
}

export default PunchClocks
