import React, { useState, useEffect, useRef } from 'react';
import './css/index.less';
import { Input, InputNumber, Button, Form, Select, message, Spin } from 'antd';
const { Option } = Select;

import { connect, history } from 'umi';
import PictureOptionsRow from '@/components/PictureOptions/PictureOptionsRow';
import TitleBack from '@/components/TitleBack/TitleBack';
import { getNumber } from '@/utils/string';

import SearchOptionsCommnity from '@/components/SearchOptions/SearchOptionsCommnity';

import { NewFaci } from '@/utils/tip';

import Facilitys from '@/components/Facilitys/Facilitys';

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

const module = 'FacilityBookings';
import moment from 'moment';

import OnTime from '@/components/OnTime/OnTime';

const Facility = (props: any) => {
  const { dispatch, location, token, sourceData, DataSave, Result, load, FacilitysList } = props;

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

  const [pictrueExtend, setPictrueExtend] = useState({ pic: null, pics: null, tab: 3 });
  const [facilityDetail, setFacilityDetail] = useState(false);
  const [PATHNAME, setPATHNAME] = useState('');

  const formRef = useRef(null as any);

  const [fileList, setFileList] = useState([] as any); // 图片列表组

  // 监听是否选择了小区
  const [imgOpen, setImgOpen] = useState(true);
  const [ctyName, setCtyName] = useState(null);
  const [soltTime, setSoltTime] = useState(['', '']); // 已选时间

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

  useEffect(() => {
    if (Result != null) {
      ResultClear();
      history.push('/CommunityManagement/FacilityBookings');
    }
  }, [Result]);

  const RA_S = () => {
    if (DataSave != null) {
      RA(7, {
        userToken: token,
        facilitieId: DataSave.id,
      });
    } else {
      history.go(-1);
    }
  };
  useEffect(() => {
    if (sourceData != null) {
      console.log(sourceData);
      setCtyName(DataSave.communityName);

      setSoltTime(sourceData.reservationQuantumTime); // 设置时间
      // 中断
      // setPictrueExtend({tab:null,pic:null,pics:null})

      // 设施图片默认值
      let list: any = sourceData.categoriesName.map((item: any, index: any) => {
        let sam = {
          id: index,
          name: item.name,
          fileList: [
            {
              uid: index,
              name: item.imgName,
              status: 'done',
              url: item.url,
            },
          ],
        };
        // 设施图片列表默认值
        form.setFieldsValue({
          ['shebei_' + index]: item.name,
        });
        return sam;
      });

      dispatch({ type: module + '/genxin', list });

      // 当是查看的时候禁止点击
      location.pathname.indexOf('FacilityDetail') > -1 ? setImgOpen(true) : setImgOpen(false);

      setFileList(sourceData.categoriesDetailsImageName); //设置图片组名称
      // delete sourceData.categoriesDetailsImageName;

      // 设置表单默认值
      formRef.current.setFieldsValue(sourceData);
    } else {
      // 新增页面进来 先清一遍 图片列表
      let list: any = [];
      dispatch({ type: module + '/genxin', list });
    }
  }, [sourceData]);

  useEffect(() => {
    var tmp = pictrueExtend;
    if (location.pathname.indexOf('FacilityEdit') > -1) {
      setPATHNAME('Edit Facility');
      tmp.tab = 1;
      setPictrueExtend(tmp);
      RA_S();
    } else if (location.pathname.indexOf('FacilityDetail') > -1) {
      setFacilityDetail(true); // 设置禁止

      tmp.tab = 2;
      setPictrueExtend(tmp);
      setPATHNAME('Facility Detail');
      RA_S();
    } else {
      tmp.tab = 3;
      setPictrueExtend(tmp);
      setPATHNAME('Add Facility');
    }
  }, []);

  // const TimeSelectRef = (values:any) => {
  //   setRef3(values)
  // }

  // 提交
  const onFinish = (values: any) => {
    var result = values;
    // 过滤表单;
    let imgs: any = [];

    for (let i in FacilitysList) {
      imgs[i] = `${FacilitysList[i].name}&${FacilitysList[i].fileList[0].name}`;
    }

    if (imgs.length == 0) {
      // 图片设施判断
      message.error('Please Upload At Least One Facility!');
    } else if (soltTime.length < 2 || !soltTime[0]) {
      // 判断时间选择
      message.error('Please Fill In The Appointment Period!');
    } else if (soltTime[1] <= soltTime[0]) {
      // 开始时间与结束时间选择错误
      message.error('Wrong selection of start time and end time!');
    } else if (
      // 提前预订时间大于 取消时间
      result.canReservationDay < result.cancelReservationDay ||
      result.canReservationDay < result.nomarginCancelReservationDay
    ) {
      message.error('Reservation should be greater than cancellation time!');
      // } else if (   // 暂时去掉这个需求判断
      //   // 不为 0 的时候  No Deposit To Cancel Reservation  必须要小于 Booking
      //   result.nomarginCancelReservationDay != 0 &&
      //   result.canReservationDay <= result.nomarginCancelReservationDay
      // ) {
      //   message.error('nomarginCancelReservationDay 要小于 Booking !');
    } else {
      let categoriesName: any = imgs; // 设施图片
      result.categoriesName = categoriesName; // 设施内容
      result.reservationQuantumTime = soltTime; // 开放时间段
      result.categoriesOpenTime = `${soltTime[0]}-${soltTime[1]}`; // 预约时间段  二开需要
      result.communityManagerFee = result.communityManagerFee ? result.communityManagerFee : '0.00'; // 价格押金没有为0
      result.communityMargin = result.communityMargin ? result.communityMargin : '0.00'; // 价格押金没有为0
      delete result.startTime;
      delete result.endTime;
      delete result.picList;

      if (sourceData != null) {
        result.id = DataSave.id;
        if (Result == null) {
          RA(17, result);
        }
      } else {
        RA(6, result);
      }
    }
    return false;
  };

  const onFinishFailed = (errorInfo: any) => {
    // console.log('Failed:', errorInfo);
  };
  const Subscribe = () => {
    history.push(getUrlLast(location.pathname) + '/FacilityApply');
  };
  const keyup_tool = (value: any) => {
    return getNumber(value.replace(/[^\d^\.]+/g, ''));
  };
  const keyup_communityManagerFee = (e: any) => {
    e.target.value = keyup_tool(e.target.value);
    formRef.current.setFieldsValue({ communityManagerFee: e.target.value });
  };
  const keyup_communityMargin = (e: any) => {
    e.target.value = keyup_tool(e.target.value);
    formRef.current.setFieldsValue({ communityMargin: e.target.value });
  };

  const keyup = (keyname: any, e: any) => {
    e.target.value = e.target.value.replace(/[^\d^\.]+/g, '');
    var tmp = {};
    tmp[keyname] = e.target.value;
    formRef.current.setFieldsValue(tmp);
  };

  // 选择小区名字并赋值
  const opname = (value: any) => {
    console.log('选择的小区是：' + value);
    console.log('储存的小区是：' + ctyName);
    if (value == '') {
      eliminate();
    } else {
      if (ctyName == null) {
        setImgOpen(false); // 允许图片上传
        setCtyName(value); // 给小区赋值
        form.setFieldsValue({
          communityName: value, // 给表单赋值
        });
      } else if (value != ctyName) {
        // eliminate();
        // 清空设施列表图
        console.log('不等于');
        setCtyName(value); // 给小区赋值
        let list: any = [];
        dispatch({ type: module + '/genxin', list });
        setFileList(null);
        //去掉图片组
        form.setFieldsValue({
          categoriesDetailsImageName: [],
        });
      }
    }
  };

  // 切换小区清除小区附件列表
  const eliminate = () => {
    setCtyName(null);
    // 设置是否能点击上传
    setImgOpen(true);
    // 清空设施列表图
    let list: any = [];
    dispatch({ type: module + '/genxin', list });

    setFileList(null);
    //去掉图片组
    form.setFieldsValue({
      categoriesDetailsImageName: [],
    });
  };

  // 子组件清除表单的 输入框值
  const dumps = (key: any) => {
    form.setFieldsValue({
      ['shebei_' + key]: '',
    });
  };

  // 下拉选择
  const startTimes = (value: any) => {
    let s = soltTime;
    if (sourceData != null) {
      s[0] = moment(value).format('HH:mm');
    } else {
      s[0] = value;
    }
    setSoltTime(s);
  };
  // 结束时间
  const endTimes = (value: any) => {
    let s = soltTime;
    if (sourceData != null) {
      s[1] = moment(value).format('HH:mm');
    } else {
      s[1] = value;
    }
    setSoltTime(s);
  };

  return (
    <>
      <Spin spinning={load}>
        <div className={'base basediy'}>
          {/* 头部组件v1.2 */}
          <TitleBack title={PATHNAME} url={getUrlLast(location.pathname) + '?Facility=true'} />
          <Form
            ref={formRef}
            form={form}
            name="basic"
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            validateMessages={validateMessages}
          >
            {/* 选择小区 */}
            <Form.Item label="Community" name="communityName" rules={NewFaci[0]}>
              <SearchOptionsCommnity
                // ubmit={extendName}
                defaultName={DataSave != null ? DataSave.communityName : null}
                opname={opname}
                disabled={facilityDetail}
              />
            </Form.Item>

            {/* 设施名称 以及费用 */}
            <Input.Group>
              <Form.Item label="Facility" name="facilityName" rules={NewFaci[1]}>
                <Input placeholder="Facility Name" disabled={facilityDetail} maxLength={30} />
              </Form.Item>
              <Form.Item label="Fee($)" name="communityManagerFee">
                {/* <span className="divIconMoney">$</span> */}
                <InputNumber
                  onKeyUp={keyup_communityManagerFee}
                  prefix="$"
                  placeholder="00.00"
                  disabled={facilityDetail}
                  min={0}
                  max={999}
                  step={0.01}
                  style={{ width: '120px' }}
                />
              </Form.Item>

              <Form.Item label="Deposit" name="communityMargin">
                {/* <span className="divIconMoney">$</span> */}
                <InputNumber
                  onKeyUp={keyup_communityMargin}
                  prefix="$"
                  placeholder="00.00"
                  disabled={facilityDetail}
                  min={0}
                  max={999}
                  step={0.01}
                  style={{ width: '120px' }}
                />
              </Form.Item>
            </Input.Group>

            <hr></hr>

            {/* 设施品类上传 */}
            <Form.Item
              label="Facility Classification"
              className="flex required"
              style={{ marginBottom: 0 }}
            >
              <Facilitys
                disabled={imgOpen}
                updata={{
                  // userToken: token,
                  imageType: 'categoriesImageName',
                  extends: ctyName,
                }}
                dumps={dumps}
              ></Facilitys>
            </Form.Item>

            {/* 设施详情上传 */}
            <Form.Item
              name="categoriesDetailsImageName"
              label="Facility Details"
              rules={NewFaci[4]}
            >
              <PictureOptionsRow
                over={imgOpen}
                data={{
                  // userToken: token,
                  imageType: 'categoriesDetailsImageName',
                  extends: ctyName,
                }}
                limitNums={99}
                value={fileList}
              />
            </Form.Item>

            {/* 时间 */}
            <Form.Item label="Opening Hours" className="required">
              <Form.Item name="startTime" noStyle>
                <OnTime
                  placeholder={'Start Time'}
                  type={0}
                  openSelect={startTimes}
                  defaultValue={soltTime[0]}
                  disabled={imgOpen}
                />
              </Form.Item>
              <span className="diyspan">-</span>
              <Form.Item name="endTime" noStyle>
                <OnTime
                  placeholder={'Closing Time'} // 默认值
                  openSelect={endTimes}
                  type={0}
                  defaultValue={soltTime[1]}
                  disabled={imgOpen}
                />
              </Form.Item>
            </Form.Item>

            <hr></hr>

            {/* ------------- */}
            <p className="diyp">Appointment Settings : </p>

            {/* 预约设置 */}
            <Input.Group>
              <Form.Item name="cancelReservationDay" label="Early Cancellation" rules={NewFaci[5]}>
                <Input
                  onKeyUp={keyup.bind(this, 'cancelReservationDay')}
                  disabled={facilityDetail}
                  prefix="Advance"
                  suffix="Day"
                  style={{ width: 160, textAlign: 'center' }}
                  placeholder="0"
                  maxLength={2}
                />
              </Form.Item>
              <Form.Item
                label="No Deposit To Cancel Reservation"
                name="nomarginCancelReservationDay"
                rules={NewFaci[6]}
              >
                <Input
                  onKeyUp={keyup.bind(this, 'nomarginCancelReservationDay')}
                  disabled={facilityDetail}
                  prefix="Advance"
                  suffix="Day"
                  style={{ width: 160, textAlign: 'center' }}
                  placeholder="0"
                  maxLength={2}
                />
              </Form.Item>
              <Form.Item label="Booking" name="canReservationDay" rules={NewFaci[7]}>
                <Input
                  onKeyUp={keyup.bind(this, 'canReservationDay')}
                  placeholder="0"
                  style={{ width: 160, textAlign: 'center' }}
                  disabled={facilityDetail}
                  prefix="Advance"
                  suffix="Day"
                  maxLength={2}
                />
              </Form.Item>
            </Input.Group>

            {/* 设置次数 */}
            <Input.Group>
              <Form.Item label="Appointment Cycle" name="periodType" rules={NewFaci[8]}>
                <Select
                  placeholder="Period"
                  allowClear
                  style={{ width: 120 }}
                  disabled={facilityDetail}
                >
                  <Option value="1">Week</Option>
                  <Option value="2">Month</Option>
                  <Option value="3">Year</Option>
                </Select>
              </Form.Item>
              <Form.Item name="canReservationNum" rules={NewFaci[9]}>
                <Input
                  onKeyUp={keyup.bind(this, 'canReservationNum')}
                  placeholder="Second"
                  style={{ width: 120 }}
                  disabled={facilityDetail}
                  suffix="Second"
                />
              </Form.Item>
            </Input.Group>

            <hr></hr>
            {/* <Row gutter={32} style={{ marginTop: 28 }}>
        <Col>Appointment Period</Col>
            <Col><TimeSelect putSubmit={TimeSelectRef} defaultValue={timeExtend} disabled={facilityDetail}/></Col>
          </Row> */}
            {facilityDetail ? (
              <>
                {imgOpen ? (
                  <Button type="primary" onClick={Subscribe} loading={load} disabled={imgOpen}>
                    Subscribe
                  </Button>
                ) : (
                  ''
                )}
              </>
            ) : (
              <>
                <Button type="primary" htmlType="submit" loading={load}>
                  Submit
                </Button>
              </>
            )}
          </Form>
        </div>
      </Spin>
    </>
  );
};

function mapStateToProps(state: any) {
  const { sourceData, DataSave, Result, FacilitysList } = state.FacilityBookings;
  const { token } = state.login;
  const load =
    typeof state.loading.models.FacilityBookings == 'undefined'
      ? false
      : state.loading.models.FacilityBookings;
  return {
    DataSave,
    sourceData,
    token,
    Result,
    load,
    FacilitysList,
  };
}
export default connect(mapStateToProps)(Facility);
