import React, { useState, useEffect, useRef } from 'react';
import './css/index.less';
import {
  Input,
  TimePicker,
  InputNumber,
  Button,
  Space,
  Pagination,
  Tooltip,
  Upload,
  Form,
  Select,
  message,
} from 'antd';
const { RangePicker } = TimePicker;
const { Option } = Select;

import { PlusOutlined, MinusCircleOutlined, ClearOutlined } from '@ant-design/icons';

import { Link, useIntl, connect, Dispatch, history } from 'umi';
import { FieldTimeOutlined } from '@ant-design/icons';

import PictureOptions from '../../../components/PictureOptions/PictureOptions';
import PictureOptionsRow from '../../../components/PictureOptions/PictureOptionsRow';
import TitleBack from '../../../components/TitleBack/TitleBack';
import TimeSelect from '../../../components/TimeSelect/TimeSelect';
import Line from '../../../components/Line/Line';
import { getNumber } from '../../../utils/string';

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

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

// categoriesDetailsImageName: ["test.jpg"],
// categoriesName: ["篮球场A&test.jpg"],
// reservationQuantumTime: ["09:00-07:00"]
import Facilitys from '@/components/Facilitys/Facilitys';

import { getUrlLast, numberToString } from '../../../utils/string';
import { checkParam, timeForm } from '@/utils/method';
import { validateMessages } from '@/utils/params';

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

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

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

  const openCheck = true;

  const [Ref3, setRef3] = useState([]);

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

  const formRef = useRef(null);

  // 再监听列表
  const [extImgList, setextImgList] = useState(imgList);
  useEffect(() => {
    console.log('变化');
    console.log(imgList);
    if (imgList != null) {
      setextImgList(imgList);
    }
  }, [imgList]);

  useEffect(() => {
    if (Result != null) {
      console.log('页面结果');
      console.log(Result);
      ResultClear();
      history.push('/CommunityManagement/FacilityBookings');
    }
  }, [Result]);

  const RA_S = () => {
    if (DataSave != null) {
      console.log('请求的设施ID为：' + DataSave.id);
      RA(7, {
        userToken: token,
        facilitieId: DataSave.id,
      });
    } else {
      history.go(-1);
    }
  };
  useEffect(() => {
    if (sourceData != null) {
      console.log('【传入详情，当前数据不为空】');
      console.log(sourceData);

      setExtend(sourceData.communityName);
      setTimeExtend(sourceData.reservationQuantumTime);
      // 中断
      // setPictrueExtend({tab:null,pic:null,pics:null})
      console.log('重点检查');
      console.log(sourceData);

      formRef.current.setFieldsValue(sourceData);
    }
  }, [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 = extImgList.filter((item: any) => (Object.keys(item).length == 0 ? false : true));
    console.log(imgs.length);
    // 开放时间判断
    if (imgs.length == 0) {
      message.error('Please upload at least one facility!');
    } else if (!result.endTime && !result.startTime) {
      message.error('Please select the opening time!');
    } else {
      // 先处理设施和时间
      let categoriesName: any = [];
      let reservationQuantumTime: any = [
        moment(result.startTime, 'HH:mm').format('HH:mm'),
        moment(result.endTime, 'HH:mm').format('HH:mm'),
      ];
      for (var i in imgs) {
        if (imgs[i].name && imgs[i].pic) {
          categoriesName[i] = `${imgs[i].name}&${imgs[i].pic}`;
        } else {
          message.error('Please fill in the name of the facility!');
          return;
        }
      }
      result.categoriesName = categoriesName; // 设施内容
      result.reservationQuantumTime = reservationQuantumTime; // 开放时间段
      result.categoriesOpenTime = `${result.startTime}-${result.endTime}`; // 预约时间段  二开需要
      delete result.startTime;
      delete result.periodType;
      delete result.picList;
      console.log(reservationQuantumTime);
      console.log(result);
      RA(6, result);
      // 如果有了 开始上传
      // if (categoriesName) {

      // }
    }
    return false;
    // if (Ref3.length!=0) {
    //   result.reservationQuantumTime = Ref3
    // } else {
    result.reservationQuantumTime = [timeForm(result.categoriesOpenTime, 'HH:mm')];
    var categoriesOpenTime = timeForm(result.categoriesOpenTime, 'HH:mm');
    result.categoriesOpenTime = categoriesOpenTime;
    // }
    // console.log(timeForm(result.categoriesOpenTime,'HH:mm'))
    // result.categoriesOpenTime = "09:00-20:00"
    if (result.communityManagerFee == null) {
      result.communityManagerFee = numberToString(0);
    } else {
      result.communityManagerFee = numberToString(result.communityManagerFee);
    }
    if (result.communityMargin == null) {
      result.communityMargin = numberToString(0);
    } else {
      result.communityMargin = numberToString(result.communityMargin);
    }
    if (
      result.canReservationDay <= result.cancelReservationDay ||
      result.canReservationDay <= result.nomarginCancelReservationDay
    ) {
      message.error('can Reservation Day is invaild!', 3);
      result.canReservationDay = null;
    } else {
      console.log('Should be check:', result);
      if (checkParam(result)) {
        //中断
        if (pictrueExtend.tab == 3) {
          if (Result == null) {
            console.log('提交');
            RA(6, result);
          }
        } else {
          result.id = DataSave.id;
          console.log('编辑');
          if (Result == null) {
            RA(17, result);
          }
        }
      } else {
        message.error('Error,Please finish it,not empty!', 3);
      }
    }
  };

  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 [imgOpen, setImgOpen] = useState(true);
  const [ctyName, setCtyName] = useState(null);

  // 生成数组 -- 时间
  const createArray = (num: any) => {
    var arr = [];
    for (let i = 1; i < num; i++) {
      if (i < 10) {
        arr[i] = `0${i}`;
      } else {
        arr[i] = i;
      }
    }
    return arr;
  };
  const Option = Select.Option;
  //小时
  const hourS = createArray(24).map((item) => (
    <Option value={item + ':00'} key={item}>{`${item}:00`}</Option>
  ));

  // 图片列表
  const fileList: any = [];
  // 表单标识
  const [form] = Form.useForm();
  // 选择小区名字并赋值
  const opname = (value: any) => {
    if (value) {
      setImgOpen(false); // 允许图片上传
      setCtyName(value); // 给小区赋值
      form.setFieldsValue({
        communityName: value, // 给表单赋值
      });
    } else {
      // 设置是否能点击上传
      setImgOpen(true);
    }
  };
  return (
    <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}
            opname={opname}
          />
        </Form.Item>

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

        <hr></hr>

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

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

        {/* 时间 */}
        <Form.Item label="Opening Hours" className="required">
          <Form.Item name="startTime" noStyle>
            <Select style={{ width: 140 }} placeholder="Start Time">
              {hourS}
            </Select>
          </Form.Item>
          <span className="diyspan">-</span>
          <Form.Item name="endTime" noStyle>
            <Select style={{ width: 140 }} placeholder="Closing Time">
              {hourS}
            </Select>
          </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"
            />
          </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"
            />
          </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"
            />
          </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 ? (
          <>
            <Button type="primary" onClick={Subscribe} loading={load}>
              Subscribe
            </Button>
          </>
        ) : (
          <>
            <Button type="primary" htmlType="submit" loading={load}>
              Submit
            </Button>
          </>
        )}
      </Form>
    </div>
  );
};

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

// ["10:00-12:00","13:00-14:00"]
// defultValue={[{ url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png", name: "篮球场A"},{ url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png", name: "篮球场B" }]}
// defultValue={[{ url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" }]}
// const Data = {
//   canReservationDay: "5",
//   canReservationNum: "6",
//   cancelReservationDay: "3",
//   categoriesOpenTime: "09:00-20:00",
//   communityManagerFee: "18",
//   communityMargin: "20",
//   communityName: "A9",
//   facilityName: "篮球场",
//   nomarginCancelReservationDay: "4",
//   periodType: "2",
// }
