import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Input, Textarea, View, Text, Picker, Button } from '@tarojs/components'
import { AtTextarea } from "taro-ui";
import Taro, { getCurrentInstance } from '@tarojs/taro';
import dayjs from 'dayjs';
import Skeleton from 'taro-skeleton'
import ImagePicker from '../../components/common/imagePicker';
import { updateRecord, recordDetails, myDuration, myDurationMonth } from '../../utils/servers/servers';
import { resourceAddress } from "../../utils/config";
import { stageList } from '../../utils/tools/config';
import './index.less';
// import '../punchClock/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";



class ReClockin extends Component {
  $instance = getCurrentInstance();

  constructor(props) {
    super(props);
    this.state = {
      imgs: [],
      loading: false,
      selector: stageList,
      dateSel: "",
      duration: "",
      hours: 0,
      selectorChecked: {},
      content: "",
      data: {},
      isOpened: false,
      dateList: [],
      year: 2000,
      month: 1,
      date: 1,
    }
    this.onChange = this.onChange.bind(this);
    this.updateRecordClockIn = this.updateRecordClockIn.bind(this);
    this.onSelectDate = this.onSelectDate.bind(this);
    this.onChangeDate = this.onChangeDate.bind(this);
    this.onMyDurationMonth = this.onMyDurationMonth.bind(this);
    this.onmyDuration = this.onmyDuration.bind(this);


  }


  componentDidMount() {
    this.getReleasetDails();
  }



  componentWillMount() {

  }

  componentDidHide() {

  }

  // 剩余打卡时间
  onmyDuration(id, recordTime) {
    myDuration({
      id,
      recordTime
    }).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(id, time) {
    myDurationMonth({
      id,
      year: time.year,
      month: time.month,
    }).then(v => {
      if (v.code === 200) {
        this.setState({
          dateList: v.data,
        })
      } else {
        Taro.showToast({ title: v.msg, icon: 'none' })
      }
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  // 项目详情
  getReleasetDails() {
    recordDetails({
      id: this.$instance.router.params.id,
    }).then((v) => {
      if (v.code === 200) {
        if (v.data) {
          let list = [];
          for (let i of (v.data.annexUrl || '').split(',')) {
            if (i) {
              list.push({ 'url': resourceAddress + i })
            }
          }
          this.onmyDuration(v.data.pid, v.data.recordTime)
          let date = dayjs(v.data.recordTime)
          this.onMyDurationMonth(v.data.pid, { year: date.year(), month: date.month() + 1 })
          this.setState({
            year: date.year(),
            month: date.month() + 1,
            date: date.date(),
            data: v.data,
            pid: v.data.pid,
            imgs: list,
            dateSel: v.data.recordTime,
            selectorChecked: this.state.selector[v.data.projectStatus],
            duration: v.data.duration,
            content: v.data.content,
            processStatus: v.data.processStatus,
            recordTime: v.data.recordTime,
            isOpened: true,
          }, () => {

          })
        }
      } else {
        Taro.showToast({ title: v.msg, icon: "none" });
      }
    }).catch((err) => {
      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,
    });
  }

  updateRecordClockIn() {
    let arr = []
    for (let i of this.state.imgs) {
      if (!!i.url) {
        arr.push(i.url.split(resourceAddress).join(""));
      } else {
        arr.push(i)
      }
    }
    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: '打卡中...' });
    updateRecord({
      id: this.$instance.router.params.id,
      pid: this.state.data.pid,
      projectStatus: this.state.selectorChecked.value,
      duration: this.state.duration,
      content: this.state.content,
      annexUrl: arr.join(','),
      processStatus: 1,
      recordTime: this.state.dateSel,
    }).then(v => {
      Taro.hideLoading()
      if (v.code === 200) {
        Taro.showToast({ title: '打卡成功', icon: 'none' });
        Taro.navigateBack({ delta: 1 });
      } else {
        Taro.showToast({ title: v.msg, icon: 'none' })
      }
    }).catch(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  onSelectDate(val) {
    let data = val.detail;
    this.setState({
      dateSel: data
    }, () => {
      this.onmyDuration(this.state.pid, data)
    })
  }

  onChangeDate(val) {
    let data = val.detail;
    !!this.state.pid && this.onMyDurationMonth(this.state.pid, data)
  }


  render() {
    const { data, dateList } = this.state;
    return (
      <View className='punchClock'>
        <View className='header'>
          <Skeleton
            title
            avatar
            row={2}
            animateName='elastic'
            avatarShape='square'
            loading={this.state.loading}
          >
            <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 className='picker'>
                    {this.state.dateSel}
                  </View>
                </View>
              </View>
              {
                this.state.isOpened &&
                <calendar
                  use_date_arr={dateList}
                  year={this.state.year}
                  month={this.state.month}
                  nowYear={this.state.year}
                  nowMonth={this.state.month}
                  nowDay={this.state.date}
                  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" }}
                    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 ? this.state.selectorChecked.lable : "请选择"}
                    </View>
                  </Picker>
                </View>
              </View>

              <View className='items'>
                <View className='ititles'><Text style={{ width: "7px" }}></Text>研发记录：
                  <AtTextarea
                    value={this.state.content}
                    onChange={value => {
                      this.setState({
                        content: value,
                      });
                    }}
                    maxLength={500}
                    placeholder="请填写研发过程记录"
                  />
                  {/* <Textarea
                    value={this.state.content}
                    style='background:#D7D7D7;width:66%;min-height:70px;border:1px solid #d6e4ef;padding:10px;border-radius: 10px' autoHeight
                    onInput={e => {
                      this.setState({
                        content: e.detail.value
                      })
                    }}
                  /> */}
                </View>
              </View>
              <View className='items'>
                <View className='ititles'><Text style={{ width: "7px" }}></Text>上传附件：</View>
                {this.state.isOpened &&
                  <ImagePicker
                    showAddBtn
                    files={this.state.imgs}
                    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.updateRecordClockIn}
                  style={{
                    boxShadow: '1px 1px 15px 1px #acb8ad',
                    background: '#009DD9',
                  }}>
                  <View className='punchClockTitle'>重新打卡</View>
                </View>
              </View>
            </View>

          </Skeleton>
        </View>

      </View>
    )
  }
}

export default ReClockin
