import React, { useState, useEffect, useRef } from 'react';
import styles from './css/Bookings.less';
import './css/Bookings.less';
import { Spin, Input, DatePicker, Button, Form, Radio, Row, Col, message } from 'antd';

import { DollarOutlined, ClockCircleOutlined } from '@ant-design/icons';

import { connect } from 'umi';

import TitleBack from '../../../components/TitleBack/TitleBack';
import SearchOptionsCommnity from '../../../components/SearchOptions/SearchOptionsCommnity';

import { numberToString } from '../../../utils/string';
import { validateMessages } from '@/utils/params';

// 日期
import moment from 'moment';
import { BookingsTip } from '@/utils/tip';
// 自定义时间段
import OnTime from '@/components/OnTime/OnTime';

const Bookings = (props: any) => {
  const { dispatch, Data3, Result, DataSave, token, load, resultTime } = props;

  const RA = (index: any, values: any) => {
    dispatch({ type: 'FacilityBookings/RA', playload: { index: index, body: values } });
  };
  const IA = () => {
    dispatch({ type: 'FacilityBookings/IA' });
  };
  const SAClear = () => {
    dispatch({ type: 'FacilityBookings/SA', playload: null });
  };
  const ResultClear = () => {
    dispatch({ type: 'FacilityBookings/ResultClear' });
  };

  const [comminityValues, setComminityValues] = useState(null);
  // 已选设施列表信息
  const [curString, setCurString] = useState({
    communityManagerFee: null,
    communityMargin: null,
    categoriesOpenTime: null,
  } as any);
  const [loading, setLoading] = useState(false);

  const formRef = useRef(null as any);

  const [prohibit, setProhibit] = useState(true); // 输入框是否不可选
  const [result, setResultTime] = useState(null as any); // 已预约时间段
  const [soltTime, setSoltTime] = useState(['', '']); // 已选时间

  const [bookTime, setBookTime] = useState(1); // 默认延后预订时间

  // 表单标识
  const [form] = Form.useForm();

  useEffect(() => {
    if (DataSave != null) {
      setComminityValues(DataSave.communityName);
      RA(1, { userToken: token, communityName: DataSave.communityName, facilitieId: DataSave.id });
    }
  }, [DataSave]);

  useEffect(() => {
    IA();
  }, []);

  useEffect(() => {
    if (Result != null) {
      message.error(Result.msg);
      if (Result.index == 1) {
        IA();
      }
      setLoading(false);
      ResultClear();
    }
  }, [Result]);

  // 选择小区监听是不是有值
  useEffect(() => {
    setLoading(false);
    if (!Data3) {
      // 如果没有值 要把Data3 从 false  复原成  null   并提示
      dispatch({ type: 'FacilityBookings/returnPage3' });
      // 再次把下方判断条件清空 和 禁用
      setCurString({ communityManagerFee: null });
      setProhibit(true);
      setResultTime(null);
      setSoltTime([]);
    }
  }, [Data3]);

  // 监听 已选时间段
  useEffect(() => {
    if (resultTime != null) {
      setResultTime(resultTime);
    }
  }, [resultTime]);

  const format = 'HH:mm';

  const checkParam = (values: any) => {
    var flag = true;

    for (var i in values) {
      // console.log(values[i]);
      if (values[i] == null) {
        flag = false;
      } else {
        if (values[i].length == 0) {
          flag = false;
        }
      }
    }
    return flag;
  };

  // 保存提交
  const onFinish = (value: any) => {
    var tmp = value;
    // 判断时间选择
    if (soltTime.length < 2 || !soltTime[0]) {
      message.error('Please Fill In The Appointment Period!');
      return false;
    }
    // 手机判断
    if (tmp.accountPhone.length != 11 && tmp.accountPhone.length != 8) {
      message.error('Please Fill In The Contact Information Correctly!');
      return false;
    }
    if (value.categoriesName != null) {
      tmp.categoriesId = value.categoriesName.categoriesId;
      tmp.facilitiesId = value.categoriesName.facilitiesId;
      tmp.categoriesName = value.categoriesName.categoriesName;
    }
    if (value.subscribeDate != null) {
      tmp.subscribeDate = value.subscribeDate.format('YYYY-MM-DD');
    }
    if (value.reservedTimeList != null) {
    }
    if (comminityValues != null) {
      tmp.communityName = comminityValues;
    }
    if (curString != null) {
      tmp.communityManagerFee = numberToString(curString.communityManagerFee);
      tmp.communityMargin = numberToString(curString.communityMargin);
    }
    if (tmp.accountName.length < 2) {
      message.error('User Name Should be limit 2~30!', 3);
    } else if (
      soltTime &&
      moment(soltTime[0], 'HH:mm').format('HH') > moment(soltTime[1], 'HH:mm').format('HH')
    ) {
      // 判断选的时间 是不是结束时间小于开始时间
      message.error('Appointment time range error');
    } else {
      tmp.reservedTimeList = soltTime; // 预约时间

      RA(11, tmp);
    }
  };
  // 选择设施
  const RadioChoose = (e: any) => {
    // 先清空表单其他值
    // form.resetFields()
    form.setFieldsValue({
      accountName: '',
      accountPhone: '',
      buildNumber: '',
      floorNumber: '',
      roomNumber: '',
      subscribeDate: '',
      startTime: '',
      endTime: '',
    });
    // 再把提示时间删除
    setResultTime(null);

    // 然后在做切换
    Data3.map((item: any, index: any) => {
      item.categorieList.map((thing: any, i: any) => {
        if (thing.categoriesId == e.target.value.categoriesId) {
          setCurString({
            communityManagerFee: parseInt(item.communityManagerFee).toFixed(2),
            communityMargin: parseInt(item.communityMargin).toFixed(2),
            categoriesOpenTime: item.categoriesOpenTime,
            categoriesId: thing.categoriesId,
            facilitiesId: thing.facilitiesId,
          });

          // 选择后取消输入框禁止
          setProhibit(false);
          // 赋值给延后天数
          setBookTime(-item.canReservationDay + 1);
        }
      });
    });
  };

  // 选择小区名字发起请求
  const getFacility = (values: any) => {
    SAClear();
    setComminityValues(values);
    RA(1, { userToken: token, communityName: values });
    setLoading(true);
    // 如果切换了小区 再次把下方判断的内容清空 和 禁用
    setCurString({
      communityManagerFee: null,
    });
    setProhibit(true);
    setResultTime(null);
    setSoltTime([]);
    // formRef.current.resetFields({ accountName: null }); // 清空已填写的表单
  };

  // 设置之前时间不能选择
  function disabledDate(current: any) {
    return current && current <= moment().subtract(bookTime, 'days').endOf('day');
  }

  // 确认日期
  const confirmData = (value: any) => {
    console.log(value);
    let data = {
      categoriesId: curString.categoriesId,
      facilitiesId: curString.facilitiesId,
      subscribeDate: moment(value).format('YYYY-MM-DD'),
    };

    RA(50, data);
  };

  // 下拉选择
  const startTimes = (value: any) => {
    let s = soltTime;
    s[0] = value;
    setSoltTime(s);
  };
  // 结束时间
  const endTimes = (value: any) => {
    let s = soltTime;
    s[1] = value;
    setSoltTime(s);
  };

  return (
    <div className={styles.base}>
      {/* 头部组件v1.2 */}
      <TitleBack title="Facility Bookings" />

      <div className={styles.box1}>
        <div className={styles.box1item1}>Project : </div>
        <div className={styles.box1item2}>
          <Spin spinning={loading} tip="Finding...">
            <SearchOptionsCommnity
              alone={true}
              placeholder={'Community Name'}
              opname={getFacility}
              defaultName={DataSave != null ? DataSave.communityName : null}
              // onSubmit={getFacility}
            />
          </Spin>
          {/* <Input.Search style={{ width: 200, height: 32 }} onSearch={getFacility} loading={loading} defaultValue={}/> */}
        </div>
      </div>
      {Data3 && Data3.length > 0 ? (
        <>
          <Form
            ref={formRef}
            form={form}
            name="basic"
            onFinish={onFinish}
            validateMessages={validateMessages}
            // autocomplete="off"
          >
            <div className="box2 required">
              <div className={styles.box2item1}>Facility Bookings : </div>
              <div className={styles.box2item2}>
                <Form.Item name="categoriesName">
                  <Radio.Group defaultValue={1} onChange={RadioChoose}>
                    {Data3.map((item: any, index: any) => {
                      var tmp = new Array();
                      item.categorieList.map((thing: any, i: any) => {
                        tmp.push(
                          <Radio key={thing.categoriesId} value={thing}>
                            {thing.categoriesName}
                          </Radio>,
                        );
                      });

                      return tmp;
                    })}
                  </Radio.Group>
                </Form.Item>
              </div>
            </div>
            <div className={styles.line}></div>

            <div className="box3 required">
              <div className={styles.box3item1}>User Name : </div>
              <div className={styles.box3item2}>
                <Form.Item name="accountName" rules={BookingsTip[0]}>
                  <Input
                    style={{ width: 200 }}
                    placeholder="Name Of Subscriber"
                    disabled={prohibit}
                    maxLength={30}
                  />
                </Form.Item>
              </div>
              <div className={styles.box3item3}>Contact Details : </div>
              <div className={styles.box3item4}>
                <Form.Item name="accountPhone" rules={BookingsTip[1]}>
                  <Input
                    style={{ width: 200 }}
                    placeholder="Contact Information"
                    disabled={prohibit}
                    maxLength={11}
                  />
                </Form.Item>
              </div>
            </div>

            <div className="box4 required">
              <div className={styles.box4item1}>Unit : </div>
              <div className="divbox4">
                <Form.Item name="buildNumber" rules={BookingsTip[2]}>
                  <Input
                    placeholder="Blk"
                    style={{ width: 80 }}
                    disabled={prohibit}
                    maxLength={10}
                  />
                </Form.Item>
                <span className="jio">#</span>
                <Form.Item name="floorNumber" rules={BookingsTip[3]}>
                  <Input
                    placeholder="Floor"
                    style={{ width: 80 }}
                    disabled={prohibit}
                    maxLength={10}
                  />
                </Form.Item>
                <span className="heng">--</span>
                <Form.Item name="roomNumber" rules={BookingsTip[4]}>
                  <Input placeholder="Room" style={{ width: 80 }} disabled={prohibit} />
                </Form.Item>
              </div>
            </div>
            <div className={styles.line}></div>

            <div className="box5 required">
              <div className={styles.box5item1}>Booking Schedule : </div>
              <div className={styles.box5item2}>
                <Row gutter={8}>
                  <Col>
                    <Form.Item name="subscribeDate" rules={BookingsTip[5]}>
                      <DatePicker
                        placeholder="Select Date"
                        disabledDate={disabledDate}
                        onChange={confirmData}
                        disabled={prohibit}
                      />
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item label="Opening Hours" className="required">
                      <Form.Item name="startTime" noStyle>
                        <OnTime
                          placeholder={'Start Time'}
                          disabled={prohibit}
                          limit={curString.categoriesOpenTime}
                          openSelect={startTimes}
                          type={0}
                          inhibitTime={result}
                        />
                      </Form.Item>
                      <span className="diyspan"> </span>
                      <Form.Item name="endTime" noStyle>
                        <OnTime
                          placeholder={'Closing Time'} // 默认值
                          disabled={prohibit} // 是否禁止
                          limit={curString.categoriesOpenTime} // 禁止时间段
                          openSelect={endTimes} //  时间类型
                          type={0}
                          inhibitTime={result}
                        />
                      </Form.Item>
                    </Form.Item>
                  </Col>
                </Row>
              </div>
            </div>

            {/* 提示已选时间段 */}
            {result != null && result.length > 0 ? (
              <div className={styles.box3}>
                <div className={styles.box3item1}>Reserved Time Period：</div>
                <div className="boxdiyitem">
                  {result.map((item: any, index: any) => {
                    return (
                      <span className="diyspan3" key={index}>
                        {item}
                      </span>
                    );
                  })}
                </div>
              </div>
            ) : null}

            {curString.communityManagerFee != null && Data3 ? (
              <>
                <div className={styles.box6}>
                  <div className={styles.box6item1}>Management fee required : </div>
                  <div className={styles.box6item2}>
                    <DollarOutlined style={{ color: '#999' }} /> {curString.communityManagerFee}
                  </div>
                </div>

                <div className={styles.box6}>
                  <div className={styles.box6item1}>Deposit is required : </div>
                  <div className={styles.box6item2}>
                    <DollarOutlined style={{ color: '#999' }} /> {curString.communityMargin}
                  </div>
                </div>

                <div className={styles.box6}>
                  <div className={styles.box6item1}>Opening Hours : </div>
                  <div className={styles.box6item2}>
                    <ClockCircleOutlined style={{ color: '#999' }} /> {curString.categoriesOpenTime}
                  </div>
                </div>
              </>
            ) : null}

            <div className={styles.line}></div>
            <Button
              htmlType="submit"
              type="primary"
              loading={load}
              disabled={prohibit}
              style={{ width: 80, height: 32 }}
            >
              Submit
            </Button>
          </Form>
        </>
      ) : null}
    </div>
  );
};

function mapStateToProps(state: any) {
  const { Data3, Result, DataSave, resultTime } = state.FacilityBookings;
  const load =
    typeof state.loading.models.FacilityBookings == 'undefined'
      ? true
      : state.loading.models.FacilityBookings;
  const { token } = state.login;
  return {
    Data3,
    Result,
    DataSave,
    token,
    resultTime,
    load,
  };
}
export default connect(mapStateToProps)(Bookings);
