import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Input, View, Text, Picker, Button, Image } from '@tarojs/components'
import Taro from '@tarojs/taro';
import {
  AtButton, AtModal, AtModalContent, AtModalAction, AtTextarea
} from "taro-ui";
import dayjs from 'dayjs';
import Skeleton from 'taro-skeleton'
import ImagePicker from '../../components/common/imagePicker';
import { add, minus, asyncAdd } from '../../actions/counter'
import { recordAdd, myDuration, getInfo, myDurationMonth } from '../../utils/servers/servers';
import Select from "../../image/dui.png";
import { stageList } from '../../utils/tools/config';
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: stageList,
      dateSel: dayjs().format('YYYY-MM-DD'),
      duration: "",
      hours: 0,
      selectorChecked: {},
      remark: "",
      data: {},
      isOpened: false,
      clockId: "",
      dateList: [],
      isCalendar: true,
      //isVacation: false, // 是否节假日
      isVopen: false, // 节假日提示

      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1,
      day: new Date().getDate(),

    }
    this.onChange = this.onChange.bind(this);
    this.publicReleaseClockIn = this.publicReleaseClockIn.bind(this);
    this.onClose = this.onClose.bind(this);
    this.onMyDurationMonth = this.onMyDurationMonth.bind(this);
    this.onmyDuration = this.onmyDuration.bind(this);
  }
  nowTime = null;

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

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

    })
  }

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

    Taro.eventCenter.on('GoPunchIn', (arg) => {
      this.setState({
        data: arg,
        isCalendar: false,
      }, () => {
        this.onmyDuration()
        !!arg.id && this.onMyDurationMonth({ id: arg.id }, { year, month })
      })
    })
  }

  // 剩余打卡时间
  onmyDuration() {
    if (!this.state.data.id) {
      return
    }
    myDuration({
      id: this.state.data.id,
      recordTime: this.state.dateSel,
    }).then(v => {
      if (v.code === 200) {
        this.setState({
          hours: v.data,
        })
      } else {
        Taro.showToast({ title: v.msg, icon: 'none' })
      }
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  onMyDurationMonth(val, time) {
    Taro.showLoading({ title: '加载中...' });
    myDurationMonth({
      id: val.id,
      year: time.year,
      month: time.month,
    }).then(v => {
      Taro.hideLoading()
      if (v.code === 200) {
        this.setState({
          dateList: v.data,
          isCalendar: true,
        })
      } else {
        Taro.showToast({ title: v.msg, icon: 'none' })
      }
    }).catch(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  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 (Object.keys(this.state.selectorChecked).length == 0) {
      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,
          isCalendar: false,
        })
      } else {
        Taro.showToast({ title: v.msg, icon: 'none' })
      }
    }).catch(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  onClose() {
    const { clockId } = this.state
    this.imagePickerRef && this.imagePickerRef.clear();
    this.setState({
      dateSel: dayjs().format('YYYY-MM-DD'),
      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1,
      day: new Date().getDate(),
      duration: "",
      selectorChecked: {},
      remark: "",
      imgs: [],
      isOpened: false,
      isCalendar: true,
    })
    if (!!clockId) {
      Taro.navigateTo({
        url: `/pages/detail/index?id=${clockId}&type=0`
      })
    }
  }
  // 选择日期
  onSelectDate(val) {
    let data = val.detail.selectDate;
    let obj = val.detail.obj
    let date = dayjs(data)
    this.setState({
      dateSel: data,
      year: date.year(),
      month: date.month() + 1,
      day: date.date(),
      isVacation: (obj.dayStatus == 3 || obj.dayStatus == 4) ? true : false,
    }, () => {
      this.onmyDuration()
    })
  }
  // 切换月份
  onChangeDate(val) {
    let data = val.detail;
    this.onMyDurationMonth(this.state.data, data)
  }

  render() {
    const { data, dateList, year, month, day, isVacation, isVopen } = 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'
                    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>研发时间：
                      <View className='picker'>
                        {this.state.dateSel}
                      </View>
                    </View>
                  </View>
                  {
                    this.state.isCalendar &&
                    <calendar
                      use_date_arr={dateList}
                      year={year}
                      month={month}
                      nowYear={year}
                      nowMonth={month}
                      nowDay={day}
                      onselectdate={(v) => {
                        this.onSelectDate(v)
                      }}
                      onchangedate={(v) => {
                        this.onChangeDate(v)
                      }}
                    />
                  }
                  <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: "#F5F5F5", borderRadius: "15px", padding: "3px 5px" }}
                        // border: "1px solid #d6e4ef",
                        onInput={e => {
                          this.setState({
                            duration: e.detail.value
                          })
                        }}
                      />&nbsp;小时&nbsp;
                      <Text style={{ color: "red", fontSize: "15px" }}>剩余打卡({this.state.hours}h)</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"
                        value={this.state.selectorChecked.value}
                        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>研发记录：
                      <AtTextarea
                        value={this.state.remark}
                        onChange={value => {
                          this.setState({
                            remark: value,
                          });
                        }}
                        maxLength={500}
                        placeholder="请填写研发过程记录"
                      />
                      {/* 
                      <Textarea
                        value={this.state.remark}
                        placeholder="请填写研发过程记录不能超过500字"
                        style='background:#D7D7D7;width:66%;min-height:70px;padding:10px;border-radius: 10px'
                        autoHeight
                        maxlength={500}
                        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={() => {
                        isVacation
                          ? this.setState({ isVopen: true })
                          : 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}
        >
          <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>

        <AtModal
          width="90%"
          isOpened={isVopen}
        >
          <AtModalContent>
            <View className='tips'>
              <View className="tits">提示</View>
              <View className="txts">
                节假日为法定休息日，不安排上班！
                如特殊原因且已与用人单位商议，需
                研发打卡，请点击“继续打卡”。
              </View>
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button
              onClick={() => {
                this.setState({
                  isVopen: false
                }, () => {
                  this.publicReleaseClockIn()
                })
              }}>继续打卡</Button>
            <Button
              onClick={() => {
                this.setState({
                  isVopen: false
                })
              }}>取消打卡</Button>
          </AtModalAction>
        </AtModal>
      </View >
    )
  }
}

export default PunchClocks
