import React, { useState, useEffect, useRef } from 'react';

import { Input, Modal, Button, Form, Row, Col, message, Spin } from 'antd';
const { confirm } = Modal;

import { ExclamationCircleOutlined } from '@ant-design/icons';

import { connect } from 'umi';
import styles from './UsersAdd.less';
import Line from '../../../components/Line/Line';
import TitleBack from '../../../components/TitleBack/TitleBack';
import { checkParam } from '../../../utils/method';
import TableShow from '@/components/TableShow/TableShow';
import { timestampToTime } from '@/utils/time';
import { validateMessages } from '@/utils/params';

const UsersDetail = (props: any) => {
  const { dispatch, DataSave, DataSaveDetail, Result, returnValue, memberResult } = props;

  const RA = (index: any, values: any) => {
    dispatch({
      type: 'User/RA',
      playload: {
        index: index,
        body: values,
      },
    });
  };
  const ResultClear = () => {
    dispatch({ type: 'User/ResultClear' });
  };
  const MemberResultClear = () => {
    dispatch({ type: 'User/MemberResultClear' });
  };
  const permissionArr = JSON.parse(localStorage.getItem('permission') || '[]');
  const [memberDetail, setMemberDetail] = useState(false);
  const [memberData, setMemberData] = useState(null as any);
  const [editFlag, setEditFlag] = useState(false);

  // const user_status = [[1, "家属"], [2, "租户"]]
  const user_status = [
    [1, 'Family Member'],
    [2, 'Tenant'],
  ];
  const user_type_status = ['Unregistered', 'Registered', 'Deregistered'];

  const [DataSaveLoading, setDataSaveLoading] = useState(false);

  const [visible, setVisible] = useState(false);

  const formRef = useRef(null as any);

  const [loadding, setLoadding] = useState(false);

  // 提交
  const onFinish = (values: any) => {
    if (DataSave != null) {
      values.id = DataSave.id;
      values.enable = DataSave.enable;
    } else {
      values.id = null;
    }

    var tmp = Object.keys(values);
    console.log('添加业主提交的参数：' + tmp.length);
    console.log(values);

    if (checkParam(values)) {
      setVisible(true);
      RA(18, values);
    } else {
      message.error('Error,Please finish it,not empty!', 3);
    }
  };

  // 监听删除结果
  useEffect(() => {
    if (Result != null) {
      console.log(Result);
      if (Result.error_code !== '0000') {
        message.error(Result.error_msg);
        ResultClear();
        history.go(0);
      }
    }
  }, [Result]);

  // 监听返回内容
  useEffect(() => {
    console.log(returnValue);
    if (returnValue != null) {
      if (returnValue.error_code !== '0001') {
        message.success('Delete Successfully!', 3);
        // RA(13, {
        //   id: DataSave.id,
        //   owerName: DataSave.owerName,
        //   enable: DataSave.enable,
        //   buildingNumber: DataSave.buildingNumber,
        //   floorNumber: DataSave.floorNumber,
        //   roomNumber: DataSave.roomNumber,
        // });

        dispatch({
          type: 'User/ClearReturnValue',
          playload: {},
        });

        history.back();
      } else {
        message.error(returnValue.error_msg, 3);
      }
    }
  }, [returnValue]);

  // 监听数据返回
  useEffect(() => {
    if (DataSave != null) {
      console.log('给予页面数据');
      console.log(DataSave);
      var tmp = {
        owerName: DataSave.owerName,
        owerPhone: DataSave.owerPhone,
        owerEmail: DataSave.owerEmail,
      };
      formRef.current.setFieldsValue(tmp);
      RA(13, {
        id: DataSave.id,
        owerName: DataSave.owerName,
        enable: DataSave.enable,
        buildingNumber: DataSave.buildingNumber,
        floorNumber: DataSave.floorNumber,
        roomNumber: DataSave.roomNumber,
      });
    } else {
      history.go(-1);
    }
  }, [DataSave]);

  // 监听数据返回
  useEffect(() => {
    if (DataSaveDetail != null) {
      console.log('页面数据副歌');
      console.log(DataSaveDetail);
      setDataSaveLoading(false);
    }
  }, [DataSaveDetail]);

  // 存储住户详情页的数据
  useEffect(() => {
    console.log(memberDetail);
    if (DataSave) {
      if (!memberDetail) {
        var tmp = {
          owerName: DataSave.owerName,
          owerPhone: DataSave.owerPhone,
          owerEmail: DataSave.owerEmail,
        };
        formRef.current.setFieldsValue(tmp);
      }
    }
  }, [memberDetail]);

  useEffect(() => {
    if (location.pathname.indexOf('Edit') > -1) {
      setEditFlag(true);
    }
    setDataSaveLoading(true);
  }, []);

  // 住户详情页
  const tableShowCallback = (values: any) => {
    console.log('成员信息');
    console.log(values);
    setMemberData(values);

    setMemberDetail(true);
  };

  // 删除单元
  const deleteUnit = (values: any) => {
    if (permissionArr.indexOf('5') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }
    confirm({
      title: 'Are you sure delete this infomation?',
      icon: <ExclamationCircleOutlined />,
      content: 'Please click confirm to delete',
      okText: 'Confirm',
      okType: 'danger',
      cancelText: 'Cancel',
      onCancel() {},
      onOk() {
        if (DataSave != null) {
          // console.log(DataSave);
          var tmp = {
            owerName: DataSave.owerName,
            communityName: DataSave.communityName,
            unit: values,
          };
          RA(16, tmp);
        }
      },
    });
  };

  // 删除住户
  const DeleteMember = (values: any, e: any) => {
    console.log(values);
    if (permissionArr.indexOf('7') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }
    confirm({
      title: 'Are you sure delete this infomation?',
      icon: <ExclamationCircleOutlined />,
      content: 'Please click confirm to delete',
      okText: 'Confirm',
      okType: 'danger',
      cancelText: 'Cancel',
      onCancel() {},
      onOk() {
        setLoadding(true);
        RA(39, { id: values.id, ownerId: values.owner_id });
      },
    });
  };

  // 返回
  const titleBackCallBack = () => {
    setMemberDetail(false);
  };

  // 监听删除住户返回的结果
  useEffect(() => {
    if (memberResult != null) {
      setMemberDetail(false);
      setLoadding(false);
      message.success('Successfully delete!!!');
      RA(13, {
        id: DataSave.id,
        owerName: DataSave.owerName,
        enable: DataSave.enable,
        buildingNumber: DataSave.buildingNumber,
        floorNumber: DataSave.floorNumber,
        roomNumber: DataSave.roomNumber,
      });
      MemberResultClear();
    }
  }, [memberResult]);

  // 编辑手机号码验证
  const checkData = (rule: any, value: any, callback: any) => {
    if (value) {
      if (/^\d{8}$|^1[3|5|7|8]\d{9}$/.test(value)) {
        callback();
      } else {
        callback(new Error('The format is incorrect!'));
      }
    }
    callback('*it is required!');
  };

  return (
    <div className={styles.base}>
      <Spin spinning={visible} tip="Loading Submit">
        {memberDetail == false ? (
          <>
            {DataSave != null ? (
              <>
                <TitleBack
                  sublist={[
                    'Status : ' + user_type_status[DataSave.enable],
                    'Create Time : ' + timestampToTime(DataSave.createTime.time),
                  ]}
                  title={editFlag ? 'Edit Owner Infomation' : 'Owner Detail'}
                />
                <Form
                  ref={formRef}
                  name="basic"
                  onFinish={onFinish}
                  validateMessages={validateMessages}
                >
                  <div className={styles.box1}>
                    <div className={styles.box1item1}>Owner's Name</div>
                    <div className={styles.box1item2}>
                      <Form.Item name="owerName" rules={[{ required: true, min: 2, max: 30 }]}>
                        <Input disabled={!editFlag} placeholder="Ower Name" />
                      </Form.Item>
                    </div>
                  </div>
                  {DataSave.enable == 1 ? (
                    <>
                      <div className={styles.box4}>
                        <div className={styles.box4item0}>Contact Details</div>
                        <div className={styles.box4item1}>
                          <Form.Item name="owerPhone" rules={[{ validator: checkData }]}>
                            <Input
                              disabled={!editFlag}
                              placeholder="Phone Number"
                              style={{ width: 174 }}
                            />
                          </Form.Item>
                        </div>
                        <div className={styles.box4item2}>
                          <Form.Item name="owerEmail" rules={[{ required: true, type: 'email' }]}>
                            <Input
                              disabled={!editFlag}
                              placeholder="Email"
                              style={{ width: 174 }}
                            />
                          </Form.Item>
                        </div>
                      </div>
                    </>
                  ) : null}

                  <Line />
                  <div style={{ textAlign: 'center' }}>
                    <Spin spinning={DataSaveLoading} tip="Loading Detial">
                      {DataSaveDetail ? (
                        <>
                          {DataSaveDetail.rows[0].owner.deleted !== 1 ? (
                            <>
                              <TableShow
                                data={DataSaveDetail}
                                onSubmit={tableShowCallback}
                                onChange={deleteUnit}
                                deleteDisable={editFlag}
                              />
                            </>
                          ) : null}
                          {editFlag && DataSaveDetail.rows[0].owner.deleted !== 1 ? (
                            <>
                              <Line />
                              <Form.Item>
                                <Button type="primary" htmlType="submit">
                                  Submit
                                </Button>
                              </Form.Item>
                            </>
                          ) : null}
                        </>
                      ) : null}
                    </Spin>
                  </div>
                </Form>
              </>
            ) : null}
          </>
        ) : (
          <>
            <Spin spinning={loadding}>
              <div>
                <TitleBack
                  title={'Family/Tenant Details'}
                  url="none"
                  titleBack={titleBackCallBack}
                ></TitleBack>
                <Row>
                  <Col span={4}>User Type：</Col>
                  <Col span={4}>
                    {memberData.owner_relationship != null
                      ? user_status[memberData.owner_relationship - 1][1]
                      : null}
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col span={4}>User Name：</Col>
                  <Col span={4}>{memberData.owner_family_name}</Col>
                </Row>
                <Row gutter={16}>
                  <Col span={4}>Contact Number：</Col>
                  <Col span={4}>{memberData.owner_family_phone}</Col>
                  <Col span={4}>{memberData.owner_family_email}</Col>
                </Row>
                <Line></Line>

                <Button danger onClick={DeleteMember.bind(this, memberData)}>
                  Delete
                </Button>
              </div>
            </Spin>
          </>
        )}
      </Spin>
    </div>
  );
};

function mapStateToProps(state: any) {
  const { DataSave, DataSaveDetail, Result, returnValue, memberResult } = state.User;
  return {
    DataSave,
    DataSaveDetail,
    Result,
    returnValue,
    memberResult,
  };
}
export default connect(mapStateToProps)(UsersDetail);
