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

import {
  Input,
  Tabs,
  Modal,
  Space,
  Pagination,
  Tooltip,
  Button,
  Form,
  Row,
  Col,
  message,
  Spin,
} from 'antd';
const { confirm } = Modal;
const { TabPane } = Tabs;
import { ExclamationCircleOutlined } from '@ant-design/icons';

import { Link, useIntl, connect, Dispatch } from 'umi';
import styles from './UsersAdd.less';
import Line from '../../../components/Line/Line';
import TitleBack from '../../../components/TitleBack/TitleBack';
import SearchOptionsCommnity from '../../../components/SearchOptions/SearchOptionsCommnity';
import { checkParam } from '../../../utils/method';
import TableShow from '@/components/TableShow/TableShow';
import { values, fromPairs } from 'lodash';
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 [memberDetail, setMemberDetail] = useState(false);
  const [memberData, setMemberData] = useState(null);
  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);
  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 == '0001') {
        message.error(Result.error_msg, 3);
        ResultClear();
      }
    }
  }, [Result]);

  useEffect(() => {
    if (returnValue != null) {
      message.success('Delete Successfully!');
      RA(13, {
        id: DataSave.id,
        owerName: DataSave.owerName,
        enable: DataSave.enable,
      });
    }
  }, [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,
      });
    } else {
      history.go(-1);
    }
  }, [DataSave]);

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

  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) => {
    // console.log(values)

    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);
    RA(39, { id: values.id, ownerId: values.owner_id });
  };
  const titleBackCallBack = () => {
    setMemberDetail(false);
  };
  useEffect(() => {
    if (memberResult != null) {
      setMemberDetail(false);
      RA(13, {
        id: DataSave.id,
        owerName: DataSave.owerName,
        enable: DataSave.enable,
      });
      MemberResultClear();
    }
  }, [memberResult]);

  const checkData = (rule: any, value: any, callback: any) => {
    if (value) {
      if (/^\d{11}$/g.test(value)) {
        callback();
      } else {
        callback(new Error('Please enter the correct cell phone number!'));
      }
    }
    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 />
                  <Spin spinning={DataSaveLoading} tip="Loading Detial">
                    {DataSaveDetail != null ? (
                      <TableShow
                        data={DataSaveDetail}
                        onSubmit={tableShowCallback}
                        onChange={deleteUnit}
                        deleteDisable={editFlag}
                      />
                    ) : null}
                    {editFlag ? (
                      <>
                        <Line />
                        <Form.Item>
                          <Button type="primary" htmlType="submit">
                            Submit
                          </Button>
                        </Form.Item>
                      </>
                    ) : null}
                  </Spin>
                </Form>
              </>
            ) : null}
          </>
        ) : (
            <>
              <div>
                <TitleBack
                  title={'Member Detail'}
                  url="none"
                  titleBack={titleBackCallBack}
                ></TitleBack>
                <Row>
                  <Col span={4}>Customer 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.ower_name}</Col>
                </Row>
                <Row gutter={16}>
                  <Col span={4}>Contact Detail</Col>
                  <Col span={4}>{memberData.ower_phone}</Col>
                  <Col span={4}>{memberData.ower_email}</Col>
                </Row>
                <Line></Line>

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

              </div>
            </>
          )}
      </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);
// "owerName":"孟浩",
// "owerPhone":"18813787878",
// "owerEmail":"sale@huahuico.com",
// "communityName":"A7",
// "buildingNumber":"A1",
// "floorNumber":"11",
// "roomNumber":"388",
// "addressAndpostalCode":"工业大道3689561"

// address_and_postalCode: "工业大道3689561"
// building_number: "01"
// cdk_code: 295863
// cdk_status: 0
// enable: 0
// floor_number: "05"
// ower_email: "sale@huahuico.com"
// ower_name: "小小莎"
// ower_phone: "18813787871"
// room_number: "388"

// "ownerId":"770da9de6b6c43f6b61bc3d671fa2e89",
// "owerName":"jack-小雄",
// "communityName":"A7"

// http://47.74.233.180:8651/tos/life/community/account/member/del
// {
// "id":"c06286cfe7b843cb96fdfcb987231123",
// "ownerId":"6b359755a36b49c28241a4620fa6539b"
// }
