import React, { Component } from "react";
import Taro from "@tarojs/taro";
import { View, Image, Button, Picker, Text } from '@tarojs/components'
import { AtInput, AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui";
import { typeList, vehiclelist } from '../../utils/tools/config';
import { getNumHourse, removeNull } from "../../utils/tools";
import { detailsAdd } from "../../utils/servers/servers";
import Right from '../../image/right.png';
import Icons from '../../image/returns.png';
import dayjs from "dayjs";
import './index.less';

import "taro-ui/dist/style/components/icon.scss";

class Modal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        type: {},
        vehicle: {},
        rangeStartMinuteVal: '',
        rangeEndMinuteVal: '',
      }
    };
  }

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

  onPickerHide() {
    this.setState({
      isPickerRender: false,
    });
  }

  onSetPickerTime(val) {
    let data = val.detail;
    this.setState({
      rangeStartMinuteVal: data.selectStartTime,
      rangeEndMinuteVal: data.selectEndTime,
    });
    let arr = [];
    if (data.startTime && data.endTime) {
      let a = dayjs(data.startTime);
      let b = dayjs(data.endTime);
      let num;
      if (a.hour() <= b.hour()) {
        num = b.diff(a, "day") + 1;
      } else {
        num = b.diff(a, "day") + 2;
      }
      let strAdd = data.startTime;
      for (let i = 0; i < num; i++) {
        let time = dayjs(strAdd).add(i, "days").format("YYYY-MM-DD");
        arr.push({ value: time });
      }
    }
    this.setState({
      rangeEndVal: dayjs(data.endTime).format("YYYY-MM-DD"),
      rangeStartVal: dayjs(data.startTime).format("YYYY-MM-DD"),
      validDates: arr,
    }, () => {
      let a1 = dayjs(dayjs(data.endTime).format("YYYY-MM-DD HH:mm:ss"));
      let b1 = dayjs(dayjs(data.startTime).format("YYYY-MM-DD  HH:mm:ss"));
      this.getNumHourse(b1, a1);
    });
  }

  // 差旅费报销
  onSubmit() {
    const { data } = this.state
    const { eaid } = this.props
    let type = data.type.value
    if (!type && type != 0) {
      Taro.showToast({ title: "请选择费用类型", icon: "none", });
      return
    }
    if (type == 1) {
      if (!data.vehicle.value && data.vehicle.value != 0) {
        Taro.showToast({ title: "请选择交通工具", icon: "none", });
        return
      }
      if (data.vehicle.value == 0 && !data.vehicleOther) {
        Taro.showToast({ title: "请填写其他工具说明", icon: "none", });
        return
      }
      if (!this.state.rangeStartMinuteVal || !this.state.rangeEndMinuteVal) {
        Taro.showToast({ title: "请选择时间", icon: "none", });
        return
      }
      if (!data.startDistrict) {
        Taro.showToast({ title: "请填写始发地", icon: "none", });
        return
      }
      if (!data.endDistrict) {
        Taro.showToast({ title: "请填写目的地", icon: "none", });
        return
      }
    }
    if (!data.amount) {
      Taro.showToast({ title: "请填写报销金额", icon: "none", });
      return
    }
    var isMoney = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
    if (!isMoney.test(data.amount)) {
      Taro.showToast({ title: "请填写正确的报销金额", icon: "none", });
      return
    }
    if (type == 1) {
      data.startTime = this.state.rangeStartMinuteVal
      data.endTime = this.state.rangeEndMinuteVal
    }
    if (data.vehicle.value != 0) {
      data.vehicleOther = undefined
    }
    let obj = {
      ...data,
      ...{ eaid, type: data.type.value, vehicle: data.vehicle.value, }
    }
    this.setState({
      loading: true,
    });
    detailsAdd(removeNull(obj))
      .then((v) => {
        this.setState({
          loading: false,
        });
        if (v.error.length === 0) {
          this.props.onClose()
          if (type == 1) {
            Taro.setStorageSync('location', { start: data.startDistrict, end: data.endDistrict })
          }
        } else {
          Taro.showToast({
            title: v.error[0].message,
            icon: "none",
          });
        }
      })
      .catch(() => {
        this.setState({
          loading: false,
        });
      });
  }

  swap() {
    const temp = this.state.data.startDistrict;
    this.setState({
      data: {
        ...this.state.data,
        ...{
          startDistrict: this.state.data.endDistrict,
          endDistrict: temp
        }
      }
    });
  }


  render() {
    const { data } = this.state
    const { visible = "", onClose } = this.props
    return (
      <AtModal
        isOpened={visible != ""}
        closeOnClickOverlay={false}
      >
        <AtModalHeader>{visible == "add" ? "新增费用" : visible == "edit" && "编辑费用"}</AtModalHeader>
        <AtModalContent>
          <View className="modal" style={{ minHeight: data.type.value == 1 && "200px" }}>
            <View className="picker">
              <View className="ptit"><View style={{ color: "red" }}>*&nbsp;</View>类型:</View>
              <Picker
                value={data.type.value == 0 ? typeList.length - 1 : data.type.value - 1}
                range={typeList} rangeKey='label' mode='selector'
                onChange={(e) => {
                  let obj = {
                    type: typeList[e.detail.value]
                  }
                  console.log(this.props.visible, "======", e.detail.value)
                  if (this.props.visible == "add" && e.detail.value == 0) {
                    console.log("--")
                    let location = Taro.getStorageSync('location')
                    if (location) {
                      obj.startDistrict = location.start
                      obj.endDistrict = location.end
                    }
                  }
                  this.setState({
                    data: { ...data, ...obj }
                  })
                }}>
                <View className='selModal'>
                  <View className='selTitle'>{!data.type.label ? "点击选择" : data.type.label}</View>
                </View>
              </Picker>
            </View>
            {/* 其他 */}
            {/* {data.type.value == 0 &&
              <View>
                <AtInput
                  required
                  name='vehicleOther'
                  title='类型说明:'
                  type='text'
                  placeholder='其他说明'
                  value={data.vehicleOther}
                  onChange={e => {
                    this.setState({
                      data: { ...data, vehicleOther: e }
                    })
                  }}
                />
              </View>} */}
            {/* 交通费 */}
            {data.type?.value == 1 &&
              <View className="picker">
                <View className="ptit"><View style={{ color: "red" }}>*&nbsp;</View>交通工具:</View>
                <Picker
                  value={data.vehicle.value == 0 ? vehiclelist.length - 1 : data.vehicle.value - 1}
                  range={vehiclelist} rangeKey='label' mode='selector'
                  onChange={(e) => {
                    this.setState({
                      data: { ...data, vehicle: vehiclelist[e.detail.value] }
                    })
                  }}>
                  <View className='selModal'>
                    <View className='selTitle'>{!data.vehicle.label ? "点击选择" : data.vehicle.label}</View>
                  </View>
                </Picker>
              </View>}
            {/* 其他 */}
            {data.vehicle?.value == 0 &&
              <View>
                <AtInput
                  required
                  name='vehicleOther'
                  title='工具说明:'
                  type='text'
                  placeholder='其他交通工具说明'
                  value={data.vehicleOther}
                  onChange={e => {
                    this.setState({
                      data: { ...data, vehicleOther: e }
                    })
                  }}
                />
              </View>}
            {data.type?.value == 1 &&
              <View className="pub">
                <View className="ptit"><View style={{ color: "red" }}>*&nbsp;</View>时间:</View>
                <View className="ptxt"
                  onClick={() => {
                    this.setState({
                      isPickerRender: true,
                    });
                  }}
                >
                  {
                    this.state.rangeStartMinuteVal &&
                      this.state.rangeEndMinuteVal
                      ? <View className="pick">
                        <View className="ptime">{this.state.rangeStartMinuteVal.slice(0, 16)}</View>
                        &nbsp;&nbsp;至&nbsp;&nbsp;
                        <View className="ptime">{this.state.rangeEndMinuteVal.slice(0, 16)}</View>
                      </View>
                      : <View>选择时间</View>
                  }
                </View>
              </View>}
            {data.type?.value == 1 &&
              <View className="pub">
                <View className="ptit"><View style={{ color: "red" }}>*&nbsp;</View>地点:</View>
                <View className="ptxt">
                  <AtInput name="startDistrict" className="pin" type='text' placeholder='始发地' value={data.startDistrict}
                    onChange={e => {
                      this.setState({
                        data: { ...data, startDistrict: e }
                      })
                    }}

                  />
                  <Image src={Icons} className='icons' mode='aspectFit' onClick={this.swap.bind(this)} />
                  <AtInput name="endDistrict" className="pin" type='text' placeholder='目的地' value={data.endDistrict}
                    onChange={e => {
                      this.setState({
                        data: { ...data, endDistrict: e }
                      })
                    }}
                  />
                </View>
              </View>}
            <View>
              <AtInput
                required
                name='amount'
                title='金额:'
                type='digit'
                placeholder='请填写金额（元）'
                value={data.amount}
                onChange={e => {
                  this.setState({
                    data: { ...data, amount: e }
                  })
                }}
              />
            </View>
          </View>
        </AtModalContent>
        <AtModalAction>
          <Button onClick={onClose}>取消</Button>
          <Button onClick={this.onSubmit.bind(this)}>确定</Button>
        </AtModalAction>
        <timePicker
          config={{
            endDate: true,
            column: "minute",
            dateLimit: false,
            limitStartTime: dayjs()
              .subtract(3, "year")
              .format("YYYY-MM-DD HH:mm:ss"),
            limitEndTime: dayjs()
              .add(3, "year")
              .format("YYYY-MM-DD HH:mm:ss"),
          }}
          isPartition
          pickerShow={this.state.isPickerRender}
          onconditionaljudgment={(v) => {
            let a = dayjs(
              dayjs(v.detail.endTime)
                .second(0)
                .format("YYYY-MM-DD HH:mm:ss")
            );
          }}
          onhidepicker={() => {
            this.onPickerHide();
          }}
          onsetpickertime={(v) => {
            this.onSetPickerTime(v);
          }}
        />
      </AtModal>
    )
  }
}

export default Modal;
