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

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';

// categoriesDetailsImageName: ["test.jpg"],
// categoriesName: ["篮球场A&test.jpg"],
// reservationQuantumTime: ["09:00-07:00"]

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

const Facility = (props:any) => {
  
  const { dispatch, location, token,sourceData,DataSave,Result} = 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);

  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

    // 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 onBillChange = (values: any, allValues: any) => {
    if (values["communityName"] != null) {      
      setExtend(values["communityName"])
    }
  }
  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)
  }

  return (
    <div className={styles.base}>
     
        {/* 头部组件v1.2 */}
      <TitleBack title={PATHNAME} url={getUrlLast(location.pathname) + "?Facility=true"} />  
      <Form ref={formRef}  name="basic" onFinish={onFinish} onFinishFailed={onFinishFailed} onValuesChange={onBillChange} validateMessages={validateMessages} >
        
      <Row gutter={32}>
        <Col>Community</Col>
          <Col><Form.Item name="communityName"  ><SearchOptionsCommnity disabled={pictrueExtend.tab!=3?true:false} /></Form.Item></Col>
      </Row>
      <Row gutter={32} style={{marginTop:28}}>
        <Col>Facility</Col>
        <Col><Form.Item name="facilityName" rules={[{required:openCheck}]}><Input placeholder="Facility Name" disabled={facilityDetail}/></Form.Item></Col>
        <Col>Fee($)</Col>
          <Col><Form.Item name="communityManagerFee" rules={[{required:openCheck}]}><Input onKeyUp={keyup_communityManagerFee} prefix="$"  placeholder="00.00" disabled={facilityDetail}  allowClear/></Form.Item></Col>
        <Col>Deposit</Col>
          <Col><Form.Item name="communityMargin" rules={[{required:openCheck}]}><Input onKeyUp={keyup_communityMargin} prefix="$" placeholder="00.00" disabled={facilityDetail}  allowClear/></Form.Item></Col>
      </Row>

        <Row gutter={32} style={{ marginTop: 28 }}>
          {
            extend != null ?<>
              <Col>Category Of Facilities</Col>
              <Col>
                <Form.Item name="categoriesName" >
                  <PictureOptions disabled={facilityDetail}              
                  data={{
                    userToken: token,
                    imageType: 'categoriesImageName',
                    extends: extend,
                      }} /></Form.Item >   </Col>                           
              </> : null
          }
      </Row>
        <Row gutter={32} style={{ marginTop: 28 }}>
          {
            extend != null ?<>
              <Col>Facility Details</Col>
              <Col>
              <Form.Item name="categoriesDetailsImageName" >
                <PictureOptionsRow disabled={facilityDetail}
                data={{
                  userToken: token,
                  imageType: 'categoriesDetailsImageName',
                  extends: extend,
                }} /></Form.Item ></Col>
              </>
              :null
          }
      </Row>
      <Line />
      <Row gutter={32} style={{marginTop:28}}>
          <Col >Opening Hours</Col>
          {/* <Input placeholder="09:00-20:00" suffix={<FieldTimeOutlined />} style={{width:160}}/> */}
        <Col><Form.Item name="categoriesOpenTime" rules={[{required:openCheck}]}><RangePicker format={'HH'} hourStep={1} /></Form.Item></Col>
      </Row>

      <Row gutter={32} style={{}}>
        <Col>Appointment Settings</Col>
        <Col>
          <Row gutter={20}>
            <Col><Form.Item name="cancelReservationDay" rules={[{required:openCheck}]} label="Early cancellation"><Input onKeyUp={keyup.bind(this,"cancelReservationDay")} placeholder="Cancel the reservation" style={{width:160}} disabled={facilityDetail} suffix="Day"/></Form.Item></Col>
              <Col><Form.Item name="nomarginCancelReservationDay" rules={[{required:openCheck}]}  label="Automatic cancellation without deposit"><Input onKeyUp={keyup.bind(this,"nomarginCancelReservationDay")} placeholder="No deposit,cancellation" style={{ width: 160 }} disabled={facilityDetail} suffix="Day" /></Form.Item></Col>            
            <Col><Form.Item name="canReservationDay" rules={[{required:openCheck}]} label="Advance booking is available"><Input onKeyUp={keyup.bind(this,"canReservationDay")} placeholder="Bookable" style={{width:160}} disabled={facilityDetail} suffix="Day"/></Form.Item></Col>
          </Row>
          <Row  gutter={8}>
              <Col> 
              <Form.Item name="periodType" rules={[{required:openCheck}]} label="Appointment Cycle">
              <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>
            </Col>
            <Col><Form.Item name="canReservationNum" rules={[{required:openCheck}]} ><Input onKeyUp={keyup.bind(this,"canReservationNum")} placeholder="times" style={{width:120}} disabled={facilityDetail} suffix="Times"/></Form.Item></Col>
          </Row>
        </Col>  
      </Row>   

      {/* <Row gutter={32} style={{ marginTop: 28 }}>
      <Col>Appointment Period</Col>
          <Col><TimeSelect putSubmit={TimeSelectRef} defaultValue={timeExtend} disabled={facilityDetail}/></Col>
        </Row> */}
        {
          facilityDetail ?  <><Line /><Button type="primary" onClick={Subscribe}>Subscribe</Button></>  :
            <><Line /><Button type="primary" htmlType="submit">Submit</Button></>                                                
        }

        </Form>
    </div>
  );
};

function mapStateToProps(state:any) {
  const { sourceData, DataSave ,Result} = state.FacilityBookings;   
  const { token } = state.login;  
  return {
    DataSave,
    sourceData,
    token,
    Result
  };
}
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",
// }

