import React, { useState, useEffect, useRef } from 'react';
import styles from './css/index.less';
import './css/index.less';
import { InputNumber, Descriptions, Spin, Form, Radio, Modal, Button, message } from 'antd';

import moment from 'moment';

import { connect } from 'umi';

import TitleBack from '../../../components/TitleBack/TitleBack';
import TextArea from 'antd/lib/input/TextArea';

import { getUrlLast } from '../../../utils/string';
const BookingDetail = (props: any) => {
  const { dispatch, location, DataSave, history, DataSaveDetail, token, load } = props;

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

  useEffect(() => {
    if (DataSave != null) {
      // 已预约时间段
      let arr = DataSave.subscribeTime.split(',');
      let time1 = parseInt(moment(arr[0], 'HH:mm').format('HH'));
      let time2 = parseInt(moment(arr[arr.length - 1], 'HH:mm').format('HH'));
      let Time = '';
      for (let i = time1; i <= time2; i++) {
        i < 10 ? (Time = `${Time}0${i}:00,`) : (Time = `${Time}${i}:00,`);
      }
      setExtractTime(Time);
      if (DataSave.managerFeeStatus != 0) {
        RA(2, { accountCategoriesId: DataSave.id });
      }
    } else {
      history.push('/CommunityManagement/FacilityBookings');
    }
  }, [DataSave]);

  // const statusDes = ["全部", "已申请", "已预订", "已使用", "已取消", "已完成"]
  const statusDes = ['All', 'Applied', 'Reserved', 'Used', 'Cancelled', 'Completed'];

  const [modalVisible, setModalVisible] = useState(false);
  const [modalItem, setModalIteme] = useState({ title: '', tab: 1 });
  const [backFeeFlag, setBackFeeFlag] = useState(false); // 部分退费 与 全部退费
  const [curbackFee, setCurBackFee] = useState(0);
  const [ExtractTime, setExtractTime] = useState(null as any); // 已预约时间段

  // 设置默认全款退费
  useEffect(() => {
    if (DataSaveDetail != null) {
      setCurBackFee(DataSaveDetail.marginFee);
    }
  }, [DataSaveDetail]);

  const radioStyle = { display: 'block', height: '50px', lineHeight: '50px' };

  const formRef = useRef(null);

  // 切换全额还是部分退款
  const backFee = (e: any) => {
    if (e.target.value == 1) {
      setBackFeeFlag(false);
      setCurBackFee(DataSaveDetail.marginFee);
    } else {
      setBackFeeFlag(true);
    }
  };

  // 点击退款
  const onFinish = (values: any) => {
    var val = values;
    if (backFeeFlag && val.backMarginFeeReason == null) {
      message.error('Back MarginFee Reason Is Empty!', 3);
    } else {
      var RAVAL = {
        accountCategoriesId: DataSave.id,
        backMarginFee: curbackFee.toString(),
        backMarginFeeReason: val.backMarginFeeReason,
        accountName: DataSave.accountName,
        backFeeStatus: curbackFee == DataSaveDetail.marginFee ? '0' : '1',
        marginFee: DataSaveDetail.marginFee.toString(),
      };

      RA(3, RAVAL);
    }
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  // 退款金额改变
  const getBackMarginFee = (e: any) => {
    setCurBackFee(e);
  };
  // 设置弹窗内容 退押金还是 取消预订
  const makeFee = () => {
    setModalIteme({ title: 'Deposit And Fee', tab: 2 });
    setModalVisible(true);
  };
  const showModal = () => {
    setModalIteme({ title: 'Cancel Reservation', tab: 1 });
    setModalVisible(true);
  };

  // 弹窗确认
  const handleOk = (e: any) => {
    setModalVisible(false);
    if (modalItem.tab == 1) {
      var RAVAL = {
        accountCategoriesId: DataSave.id,
        userToken: token,
      };
      RA(5, RAVAL);
    } else {
      var RAVAL2 = {
        accountCategoriesId: DataSave.id,
        accountName: DataSave.accountName,
        managerFee: DataSave.communityManagerFee.toString(),
        marginFee: DataSave.communityMargin.toString(),
      };
      RA(4, RAVAL2);
    }
  };
  // 隐藏弹窗
  const handleCancel = (e: any) => {
    setModalVisible(false);
  };
  return (
    <>
      {DataSave != null ? (
        <Spin spinning={load}>
          <div className={styles.base}>
            <TitleBack
              title={'View Facility Bookings'}
              url={getUrlLast(location.pathname) + '?Facility=false'}
            />
            <Descriptions>
              <Descriptions.Item label="Booking Status">
                {statusDes[DataSave.status]}
              </Descriptions.Item>
              <Descriptions.Item label="Order Time">
                {/* {timestampToTime3(DataSave.createTime.time)} */}
                {moment(DataSave.createTime.time).format('MM-DD  HH:mm')}
              </Descriptions.Item>
            </Descriptions>

            <hr />

            <Descriptions>
              <Descriptions.Item label="Service Community">
                {DataSave.communityName}
              </Descriptions.Item>
              <Descriptions.Item label="Booking Facilities">
                {DataSave.categoriesName}
              </Descriptions.Item>
              <Descriptions.Item label="Booking Time">
                {DataSave.subscribeDate} {ExtractTime}
              </Descriptions.Item>
              <Descriptions.Item label="User Name">{DataSave.accountName}</Descriptions.Item>
              <Descriptions.Item label="Contact Number">{DataSave.accountPhone}</Descriptions.Item>
              <Descriptions.Item label="Unit">
                {DataSave.buildNumber} #{DataSave.floorNumber}-{DataSave.roomNumber}
              </Descriptions.Item>
            </Descriptions>

            <hr />

            {/* 已交押金且未产生退费 */}
            {DataSave != null &&
            DataSave.managerFeeStatus == 1 &&
            DataSave.communityManagerFee > 0 ? (
              <>
                <Form
                  ref={formRef}
                  name="basic2"
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                >
                  <Descriptions>
                    <Descriptions.Item label="Management Expense">
                      $ {parseInt(DataSave.communityManagerFee).toFixed(2)}
                    </Descriptions.Item>
                    <Descriptions.Item label="Deposit">
                      $ {parseInt(DataSave.communityMargin).toFixed(2)}
                    </Descriptions.Item>
                  </Descriptions>

                  <Radio.Group onChange={backFee} defaultValue={1}>
                    <Radio value={1} style={radioStyle}>
                      Full Refund
                    </Radio>
                    <Radio value={2} style={radioStyle}>
                      Partial Refund
                      {backFeeFlag ? (
                        <>
                          <InputNumber
                            placeholder="00.00"
                            min={0}
                            max={parseInt(DataSave.communityMargin).toFixed(2) as any}
                            maxLength={6}
                            step={0.01}
                            prefix="$"
                            onChange={getBackMarginFee}
                            style={{ width: 80, marginLeft: 10 }}
                          />
                        </>
                      ) : null}
                    </Radio>
                  </Radio.Group>

                  {backFeeFlag ? (
                    <div style={{ marginTop: 16 }}>
                      <Form.Item name="backMarginFeeReason">
                        <TextArea
                          autoSize={false}
                          style={{ padding: 8, width: 400, height: 80 }}
                          placeholder="Reasons for partial refund of deposit..."
                        ></TextArea>
                      </Form.Item>
                    </div>
                  ) : null}
                  <div style={{ marginTop: 16 }}>
                    <Form.Item>
                      <Button type="primary" htmlType="submit" loading={load}>
                        Deposit Refunds
                      </Button>
                    </Form.Item>
                  </div>
                  <hr />
                </Form>
              </>
            ) : null}

            {/* 未交押金 */}
            {DataSave != null && DataSave.status == 1 && DataSave.managerFeeStatus == 0 ? (
              <>
                <div style={{ paddingBottom: 16 }}>
                  <Descriptions style={{ marginBottom: 6 }}>
                    <Descriptions.Item label="Management fee required">
                      $ {parseInt(DataSave.communityManagerFee).toFixed(2)}
                    </Descriptions.Item>
                    <Descriptions.Item label="Deposit is required">
                      $ {parseInt(DataSave.communityMargin).toFixed(2)}
                    </Descriptions.Item>
                  </Descriptions>

                  <Button className="pay" loading={load} onClick={makeFee}>
                    Go Pay
                  </Button>
                </div>
                <hr />
              </>
            ) : null}

            {/* 取消预订按钮 */}
            {DataSave.status == 1 || DataSave.status == 2 ? (
              <Button onClick={showModal} loading={load}>
                Cancel Reservation
              </Button>
            ) : null}

            {/* 弹窗 */}
            <Modal
              okText="Yes"
              cancelText="No"
              title={modalItem.title}
              visible={modalVisible}
              onOk={handleOk}
              onCancel={handleCancel}
            >
              {modalItem.tab == 1 ? (
                <p>
                  Are you sure you want to cancel the booking {DataSave.subscribeDate} ,
                  {DataSave.subscribeTime}, {DataSave.facilityTitle}
                </p>
              ) : (
                <p>
                  Confirm receipt of all usage amount of the facility ?
                  <div>
                    {DataSave.subscribeDate} {DataSave.subscribeTime} {DataSave.facilityTitle}
                  </div>
                </p>
              )}
            </Modal>
          </div>
        </Spin>
      ) : null}
    </>
  );
};

function mapStateToProps(state: any) {
  const { DataSave, DataSaveDetail } = state.FacilityBookings;
  const { token } = state.login;
  const load =
    typeof state.loading.models.FacilityBookings == 'undefined'
      ? true
      : state.loading.models.FacilityBookings;
  return {
    DataSave,
    DataSaveDetail,
    token,
    load,
  };
}

export default connect(mapStateToProps)(BookingDetail);
