import React,{Component} from 'react';
import Taro from '@tarojs/taro';
import {Text, View} from '@tarojs/components'
import dayjs from 'dayjs';
import './index.less';
import DateTimePicker from '../../components/common/DateTimePicker';

import ImagePicker from '../../components/common/imagePicker'

import {radiusRange} from '../../utils/config';

import {AtButton, AtTextarea, AtIcon, AtCalendar} from 'taro-ui'
import {addPublicRelease,getWorkingHoursList} from '../../utils/servers/servers';

import {getNumHourse} from '../../utils/tools';

import 'taro-ui/dist/style/components/form.scss';
import 'taro-ui/dist/style/components/button.scss';
import 'taro-ui/dist/style/components/loading.scss';
import 'taro-ui/dist/style/components/icon.scss';
import 'taro-ui/dist/style/components/icon.scss';
import 'taro-ui/dist/style/components/textarea.scss';
import 'taro-ui/dist/style/components/calendar.scss';

import './publicContent.less';
import InquiryModal from "../../components/common/inquiryModal";

class PublicContent extends Component{
  constructor(props) {
    super(props);
    this.state={
      rangeStartVal:'',
      rangeEndVal:'',
      rangeEndMinuteVal:'',
      rangeStartMinuteVal:'',
      reason:'',
      imgs:[],
      validDates:[],
      totalDuration:0,
      loading:false,
      workTypeList:[],
      workType:0,
    }
    this.onSubmit = this.onSubmit.bind(this);
    this.selectArrder = this.selectArrder.bind(this);
    this.onChange = this.onChange.bind(this);
    this.getWorkingHoursList = this.getWorkingHoursList.bind(this);
  }

  componentDidMount() {
    Taro.eventCenter.on('result', () => {
      this.rangeEndRef && this.rangeEndRef.clear();
      this.rangeStartRef && this.rangeStartRef.clear();
      this.imagePickerRef && this.imagePickerRef.clear();
      this.setState({
        rangeStartVal:'',
        rangeEndVal:'',
        rangeEndMinuteVal:'',
        rangeStartMinuteVal:'',
        reason:'',
        imgs:[],
        validDates:[],
        totalDuration:0,
        loading:false,
      })
    })
    this.getWorkingHoursList();
  }

  getNumHourse(startTime,endTime){
    this.setState({
      totalDuration:getNumHourse(startTime,endTime,this.state.validDates.length)
    })
  }


  onSubmit(){
    if(!this.state.rangeStartMinuteVal){
      Taro.showToast({title:'请选择公出开始时间',icon:'none'})
      return ;
    }
    if(!this.state.rangeEndMinuteVal){
      Taro.showToast({title:'请选择公出结束时间',icon:'none'})
      return ;
    }
    if(!(this.props.selectArrderLocation.longitude && this.props.selectArrderLocation.latitude)){
      Taro.showToast({title:'请选择公出地点',icon:'none'})
      return ;
    }
    if(!this.state.reason){
      Taro.showToast({title:'请输入公出事由',icon:'none'})
      return ;
    }
    if(this.state.totalDuration === 0){
      Taro.showToast({title:'公出时间不足0小时',icon:'none'})
      return ;
    }
    this.setState({
      loading:true
    })
    addPublicRelease({
      uid:this.props.enterpriseInfor.id,
      releaseStarts:this.state.rangeStartMinuteVal,
      releaseEnds:this.state.rangeEndMinuteVal,
      remarks:this.state.reason,
      userName: this.props.selectArrderLocation.name,
      longitude: this.props.selectArrderLocation.longitude,
      latitude: this.props.selectArrderLocation.latitude,
      annexUrl: this.state.imgs.length === 0 ? '' : this.state.imgs.join(','),
      duration: this.state.totalDuration,
      validDate: JSON.stringify(this.state.validDates)
    }).then(v=>{
      this.setState({
        loading:false
      })
      if(v.error.length === 0){
        Taro.eventCenter.trigger('publicContent',v.data)
      }else{
        Taro.showToast({
          title:v.error[0].message,
          icon:'none'
        })
      }
    }).catch(()=>{
      this.setState({
        loading:false
      })
    });
  }

  selectArrder(){
    const key = 'AWBBZ-GRAC2-JFYUO-CLA7I-JAHXK-YFFGT'; //使用在腾讯位置服务申请的key
    const referer = '科德打卡定位'; //调用插件的app的名称
    const category = '公司企业,房产小区';
    Taro.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&category=' + category
    });
  }

  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,
    })
  }

  getWorkingHoursList(){
    getWorkingHoursList({}).then((v)=>{
      if(v.error.length === 0){
        let obj = Taro.getStorageSync('userInfor');
        let index = v.data.findIndex(value=>value.type === obj.workTimeInfor.type);
        this.setState({
          workType:index !== -1 ? index : 0
        })
        this.setState({
          workTypeList:v.data
        })
      }else{
        Taro.showToast({
          title:v.error[0].message,
          icon:'none'
        })
      }
    }).catch(err=>{
      console.log(err)
    })
  }

  render() {
    return (
      <View className='publicContent'>
        <View className='formItem'>
          <View className='formName'>公出企业:</View>
          <View className='formValue'>{this.props.enterpriseInfor.name}</View>
        </View>
        <View className='formItem'>
          <View className='formName'>作息时间类型:</View>
          <View className='formValue'>
            <picker onChange={(e)=>{
              this.setState({
                workType: e.detail.value
              })
              if(this.state.workTypeList[e.detail.value]){
                let obj = Taro.getStorageSync('userInfor');
                obj.workTimeInfor = this.state.workTypeList[e.detail.value];
                Taro.setStorageSync('userInfor', obj);
                this.rangeEndRef.clear();
                this.rangeStartRef.clear();
                this.setState({
                  rangeStartVal:'',
                  rangeStartMinuteVal: '',
                  validDates:[],
                  totalDuration:0
                })
              }
            }} value={this.state.workType} rangeKey='name' range={this.state.workTypeList}>
              <view >
                {this.state.workTypeList[this.state.workType] ? this.state.workTypeList[this.state.workType].name : ''}
              </view>
            </picker>
          </View>
        </View>
        <View className='formItem'>
          <View className='formName'>公出开始时间:</View>
          <View className='formValue'>
            <DateTimePicker ref={ref=>this.rangeStartRef = ref} onOk={(current)=>{
              let arr = [];
              if(this.state.rangeEndVal){
                if(dayjs(current.current).isAfter(dayjs(this.state.rangeEndMinuteVal))){
                  Taro.showToast({title:'开始时间不能在结束时间之后',icon:'none'})
                  this.rangeStartRef.clear();
                  this.setState({
                    rangeStartVal:'',
                    rangeStartMinuteVal: '',
                    validDates:[],
                    totalDuration:0
                  })
                  return;
                }
              }
              if(this.state.rangeEndVal){
                let str = dayjs(current.current).format('YYYY-MM-DD');
                arr.push({value:str});
                let a = dayjs(this.state.rangeEndVal);
                let b = dayjs(str);
                let num = a.diff(b, 'days');
                let strAdd = str;
                for(let i = 0;i<num;i++){
                  let time = dayjs(strAdd).add(1, 'days').format('YYYY-MM-DD');
                  strAdd = time
                  arr.push({value:time});
                }
              }
              this.setState({
                rangeStartVal:dayjs(current.current).format('YYYY-MM-DD'),
                rangeStartMinuteVal: dayjs(current.current).format('YYYY-MM-DD HH:mm:ss'),
                validDates:arr
              },()=>{
                if(this.state.rangeEndVal){
                  let a1 = dayjs(dayjs(current.current).format('YYYY-MM-DD HH:mm:ss'));
                  let b1 = dayjs(dayjs(this.state.rangeEndMinuteVal).format('YYYY-MM-DD  HH:mm:ss'));
                  this.getNumHourse(a1,b1)
                }
              })
            }} onClear={()=>{
              this.setState({
                rangeStartVal:'',
                rangeStartMinuteVal: '',
                validDates:[],
                totalDuration:0
              })
            }} initValue={dayjs()} wrap-class="my-class"  select-item-class="mySelector" />
          </View>
        </View>
        <View className='formItem'>
          <View className='formName'>公出结束时间:</View>
          <View className='formValue'>
            <DateTimePicker ref={ref=>this.rangeEndRef = ref} onOk={(current)=>{
              let arr = [];
              if(this.state.rangeStartVal){
                if(dayjs(current.current).isBefore(dayjs(this.state.rangeStartMinuteVal))){
                  Taro.showToast({title:'结束时间不能在开始时间之前',icon:'none'})
                  this.rangeEndRef.clear();
                  this.setState({
                    rangeEndVal:'',
                    rangeEndMinuteVal: '',
                    validDates:[],
                    totalDuration:0
                  })
                  return;
                }
              }
              if(this.state.rangeStartVal){
                let str = dayjs(current.current).format('YYYY-MM-DD');
                arr.push({value:this.state.rangeStartVal});
                let a = dayjs(this.state.rangeStartVal);
                let b = dayjs(str);
                let num = b.diff(a, 'days');
                let strAdd = this.state.rangeStartVal;
                for(let i = 0;i<num;i++){
                  let time = dayjs(strAdd).add(1, 'days').format('YYYY-MM-DD');
                  strAdd = time
                  arr.push({value:time});
                }
              }
              this.setState({
                rangeEndVal:dayjs(current.current).format('YYYY-MM-DD'),
                rangeEndMinuteVal: dayjs(current.current).format('YYYY-MM-DD HH:mm:ss'),
                validDates:arr,
              },()=>{
                if(this.state.rangeStartVal){
                  let a1 = dayjs(dayjs(current.current).format('YYYY-MM-DD HH:mm:ss'));
                  let b1 = dayjs(dayjs(this.state.rangeStartMinuteVal).format('YYYY-MM-DD  HH:mm:ss'));
                  this.getNumHourse(b1,a1)
                }
              })
            }} onClear={()=>{
              this.setState({
                rangeEndVal:'',
                rangeEndMinuteVal: '',
                validDates:[],
                totalDuration:0
              })
            }} initValue={dayjs()} wrap-class="my-class"  select-item-class="mySelector" />
          </View>
        </View>
        <View className='formItem'>
          <View className='formName'>总时长:</View>
          <View className='formValue'>
            {this.state.totalDuration}小时
          </View>
        </View>
        {this.state.validDates.length !== 0? <View className='formItem' style={{display:'block',paddingTop:'15px'}}>
          <View className='formName'>
            <View>去除放假时间:</View>
            <View className='tips'>绿色方块为公出时间,长按即可去除放假时间</View>
          </View>
          <AtCalendar
            currentDate={this.state.rangeStartVal}
            minDate={this.state.rangeStartVal}
            maxDate={this.state.rangeEndVal}
            isSwiper={false}
            validDates={this.state.validDates}
            onDayLongClick={(item)=>{
              if(!(dayjs(item.value).isSame(this.state.rangeStartVal) || dayjs(item.value).isSame(this.state.rangeEndVal))){
                if(!(dayjs(item.value).isAfter(this.state.rangeStartVal) && dayjs(item.value).isBefore(this.state.rangeEndVal))){
                  return;
                }
              }else{
                Taro.showToast({title:'开始结束时间不能取消',icon:'none'})
                return
              }
              let index = this.state.validDates.findIndex(v=>{
                let lv = dayjs(v.value).isSame(item.value);
                return lv
              })
              if(index<0){
                let arr = item.value.split('-');
                this.state.validDates.push({value:arr.join('-')})
                this.setState({
                  validDates:this.state.validDates,
                  totalDuration: this.state.totalDuration + 7.5
                })
              }else{
                this.state.validDates.splice(index,1)
                this.setState({
                  validDates:this.state.validDates,
                  totalDuration: this.state.totalDuration - 7.5
                })
              }
            }}
          />
        </View> : null}
        <View className='formItem' style={{paddingBottom:0}}>
          <View className='formName'>公出地点:</View>
          <View className='formValue' onClick={this.selectArrder}>
              <Text className='formValueText'>{this.props.selectArrderLocation.name}</Text>
              <AtIcon value='chevron-right' size='30' color='#bbbbbb'/>
          </View>
        </View>
        <View className='tips'>以地图中红标为中心{radiusRange}米范围为可打卡区域,移动红标只需要拖动地图即可</View>
        <View className='formItem' style={{display:'block',paddingTop:'15px'}}>
          <View className='formName'>公出事由:</View>
          <View className='formValue' style={{paddingTop:'10px',textAlign:'left'}}>
            <AtTextarea
              value={this.state.reason}
              onChange={(v)=>{
                this.setState({
                  reason:v
                })
              }}
              maxLength={200}
              placeholder='请输入公出事由'
            />
          </View>
        </View>
        <View className='formItem' style={{display:'block'}}>
          <View className='formName'>附件:</View>
          <View className='formValue' style={{paddingTop:'10px',textAlign:'left'}}>
            <ImagePicker
              showAddBtn={true}
              ref={ref => this.imagePickerRef = ref}
              url='/api/admin/release/upload'
              onChange={this.onChange}
            />
          </View>
        </View>
        <View className='operation'>
          <AtButton disabled={this.state.loading} type='secondary' circle onClick={()=>{
            Taro.eventCenter.trigger('enterpriseBack')
          }}>
            上一步
          </AtButton>
          <AtButton type='primary' loading={this.state.loading} circle onClick={()=>{
            if(this.state.loading){
              return;
            }
            this.setState({
              isInquiryOpened:true,
              inquiryTitle:'提醒',
              inquiryContent:'您确定要提交此申请吗?',
              inquiryFn:()=>{
                this.onSubmit();
              }
            })
          }}>
            提交申请
          </AtButton>
        </View>
        <InquiryModal
          isOpened={this.state.isInquiryOpened}
          title={this.state.inquiryTitle}
          content={this.state.inquiryContent}
          onClose={()=>{
            this.setState({
              isInquiryOpened:false,
              inquiryTitle:'',
              inquiryContent:'',
            })
          }}
          onDetermine={()=>{
            this.state.inquiryFn();
            this.setState({
              isInquiryOpened:false,
              inquiryTitle:'',
              inquiryContent:'',
              inquiryFn:()=>{}
            })
          }}
        />
      </View>
    )
  }
}

export default PublicContent;
