import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { LeftOutlined, EditOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Form,
  Input,
  Image,
  Button,
  TimePicker,
  Checkbox,
  Upload,
  message,
  Spin,
  Modal,
  Pagination,
} from 'antd';
// 样式
import './celllist.less';
import { RA } from '@/utils/method';
import { history } from 'umi';
import { village } from '@/utils/tip';

import moment from 'moment';
import { getNumber } from '@/utils/string'; // 正则

import FileViewer from 'react-file-viewer';
import PDF from 'react-pdf-js';

const { RangePicker } = TimePicker;

const Adds = (props: any) => {
  const module = 'CellList';

  const { Data, dispatch, loading, imgUrl } = props;

  const [form] = Form.useForm();

  const [PropertyFee, setPropertyFee] = useState(['1']); // 表单物业费提交值

  const [loubaUpload, setLouba] = useState([] as any); // 楼巴上传列表
  const [guideUpload, setGuide] = useState([] as any); // 物业办事指南列表
  const [periodUpload, setPeriod] = useState([] as any); // 保质期服务列表

  // 监听用户填写小区名   以及后续禁止输入  提示信息
  const [codename, setCodeName] = useState('');
  const [codeStrat, setcodeStrat] = useState(false);
  const [tipMain, setTipMain] = useState('');

  const [previewVisible, setpreviewVisible] = useState(false); // 预览弹窗显示隐藏
  const [previewImage, setpreviewImage] = useState({} as any); // 预览图片信息

  //pdf 页码内容
  const [numPages, setNumPages] = useState(1 as any); // 总页码数
  const [pageNumber, setPageNumber] = useState(1); // 当前页码数

  const [imgLoad, setimgLoad] = useState(false); //图片上传 load状态

  // 赋值
  useEffect(() => {
    // 如果是添加传来没有值的时候 就清空  否则  赋值给表单
    if (Data) {
      // 返回列表
      form.setFieldsValue({
        // 必填的
        des: {
          residentialZipCode: Data.residentialZipCode.substring(
            Data.residentialZipCode.length - 6,
            Data.residentialZipCode.length,
          ),
          residentialAddress: Data.residentialAddress,
          residentialName: Data.residentialName,
        },

        workingHours: [
          moment(Data.residentialStartWorking, 'HH:mm'),
          moment(Data.residentialEndWorking, 'HH:mm'),
        ],
        info: {
          tel: Data.residentialPhone,
          email: Data.residentialEmail,
        },
        residentialManagerUserName: Data.residentialManagerUserName,
        help: {
          residentialHotlineName: Data.residentialHotlineName,
          residentialHotline: Data.residentialHotline,
          time: [
            moment(Data.residentialHotlineServieStartTime, 'HH:mm'),
            moment(Data.residentialHotlineServieEndTime, 'HH:mm'),
          ],
        },
      });
      // 上传
      setLouba(Data.balouscheduleUrl ? [backUpload(Data.balouscheduleUrl, Data.id)] : []);
      setGuide(Data.serviceGuideUrl ? [backUpload(Data.serviceGuideUrl, Data.id)] : []);
      setPeriod(Data.lifeServiceUrl ? [backUpload(Data.lifeServiceUrl, Data.id)] : []);
      // 小区名 -- 上传需要
      setCodeName(Data.residentialName);
      setcodeStrat(true);
      setTipMain('Binding Content Already Exists, Cannot Be Modified！');
    } else {
      // console.log('新建');
    }
  }, [Data]);

  // 监听编辑预览是否获取到地址以及发生改变
  useEffect(() => {
    if (imgUrl != null) {
      let info = {
        uid: '1',
        name: imgUrl.name,
        status: 'done',
        type: imgUrl.name.match(/\.([^\.]+)$/)[1].toLowerCase(),
        url: imgUrl.url,
      };
      setpreviewImage(info);
      setpreviewVisible(true);
      // openDows(imgUrl.url, imgUrl.name);
    }
  }, [imgUrl]);

  // 编辑  返回上传格式 和 地址
  function backUpload(str: any, index: number, url?: any) {
    let a = {
      uid: str + index,
      name: str,
      status: 'done',
      type: str.match(/\.([^\.]+)$/)[1].toLowerCase(),
      url: 'Transfer', // 需要调取接口
    };
    return a;
  }

  // 上传设置
  const uploads = {
    name: 'file',
    accept: '.jpg,.png,.pdf',
    action: '/tos/image/upload',
    data: { imageType: 'tosCreateCommunity', extends: codename },
  };

  // 文件上传判断
  function beforeUpload(file: any) {
    // 文件大小判断
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('File must be less than or equal to 2MB!');
    }
    return isLt2M;
  }

  // 上传返回格式
  function BackFormat(name: any, url: any) {
    let imgs = [
      {
        uid: '-1',
        name: name,
        status: 'done',
        type: name.match(/\.([^\.]+)$/)[1].toLowerCase(),
        url: url,
      },
    ];
    return imgs;
  }

  // 楼巴上传
  const upload1 = {
    onChange({ file }: any) {
      file.status === 'uploading' ? setimgLoad(true) : setimgLoad(false);
      if (file.status === 'done') {
        setLouba(BackFormat(file.name, file.response.data));
        setcodeStrat(true);
        setTipMain('Binding Content Already Exists, Cannot Be Modified！');
      }
      // 结果
      uploadMsg(file);
    },
  };

  // 指南上传
  const upload2 = {
    onChange({ file, fileList }: any) {
      file.status === 'uploading' ? setimgLoad(true) : setimgLoad(false);
      if (file.status === 'done') {
        setGuide(BackFormat(file.name, file.response.data));
        setcodeStrat(true);
        setTipMain('Binding Content Already Exists, Cannot Be Modified！');
      }
      // 结果
      uploadMsg(file);
    },
  };

  // 保质期上传
  const upload3 = {
    onChange({ file }: any) {
      file.status === 'uploading' ? setimgLoad(true) : setimgLoad(false);
      if (file.status === 'done') {
        setPeriod(BackFormat(file.name, file.response.data));
        setcodeStrat(true);
        setTipMain('Binding Content Already Exists, Cannot Be Modified！');
      }
      // 结果
      uploadMsg(file);
    },
  };

  // 上传提示
  function uploadMsg(file: any) {
    if (file.status === 'done') {
      message.success(`${file.name} File Uploaded Successfully`);
    } else if (file.status === 'error') {
      message.error(`${file.name} File Upload Failed.`);
    }
  }

  // 多选选择改变值
  function onChange(checkedValues: any) {
    // 修改选择值
    setPropertyFee(checkedValues);
  }

  // undefind 验证
  function undeFi(e: any) {
    if (typeof e == 'undefined') {
      return null;
    } else {
      return e;
    }
  }

  // 表单验证
  const onFinish = (values: any) => {
    let { residentialZipCode } = values.des;
    let tel = values.info.tel;
    if (values.residentialManagerUserName.length < 2) {
      message.error('Please Enter 2-digit Administrator Name！');
    } else if (residentialZipCode.length < 6) {
      message.error('Please Enter The Correct Name！');
    } else if (tel.length != 8 && tel.length != 11) {
      message.error('Incorrect Contact Information！');
    } else {
      onUpDate(values);
    }
  };

  // 表单提交
  function onUpDate(values: any) {
    // 额外判断
    let obj: any = new Object();

    obj.propertyFee = PropertyFee;
    // 小区信息;
    let { residentialZipCode, residentialAddress, residentialName } = values.des;

    obj.residentialZipCode = `SINGAPORE ${residentialZipCode}`;
    obj.residentialAddress = residentialAddress;
    obj.residentialName = residentialName;

    // 小区时间与管理员
    obj.residentialManagerUserName = undeFi(values.residentialManagerUserName);
    obj.residentialStartWorking = values.workingHours[0].format('HH:mm');
    obj.residentialEndWorking = values.workingHours[1].format('HH:mm');
    obj.residentialPhone = values.info.tel;
    obj.residentialEmail = values.info.email;

    // 上传内容

    obj.balouscheduleUrl = undeFi(loubaUpload.map((item: any) => item.name)[0]);
    obj.serviceGuideUrl = undeFi(guideUpload.map((item: any) => item.name)[0]);
    obj.lifeServiceUrl = undeFi(periodUpload.map((item: any) => item.name)[0]);

    // 小区热线
    // 表单结构存在数据不存在情况， 所以要多判断一次
    if (values.help) {
      obj.residentialHotlineName = values.help.residentialHotlineName
        ? undeFi(values.help.residentialHotlineName)
        : 'Community Hotline';
      obj.residentialHotline = values.help.residentialHotline
        ? undeFi(values.help.residentialHotline)
        : values.info.tel;
      // 编辑的时候 为空 判断
      if (values.help.time) {
        obj.residentialHotlineServieStartTime = undeFi(values.help.time[0]).format('HH:mm');
        obj.residentialHotlineServieEndTime = undeFi(values.help.time[1]).format('HH:mm');
      } else {
        obj.residentialHotlineServieStartTime = values.workingHours[0].format('HH:mm');
        obj.residentialHotlineServieEndTime = values.workingHours[1].format('HH:mm');
      }
    } else {
      obj.residentialHotlineName = values.info.tel;
      obj.residentialHotline = values.info.tel;
      obj.residentialHotlineServieStartTime = values.workingHours[0].format('HH:mm');
      obj.residentialHotlineServieEndTime = values.workingHours[1].format('HH:mm');
    }

    if (Data) {
      obj.id = Data.id;
    }
    console.log(values);
    console.log(obj);
    // 上传
    RA(29, obj, 'CellList', dispatch);
  }

  // 返回
  const goToReturn = () => {
    history.go(-1);
  };

  // 小区名输入监听ant
  function insdInp(value: string) {
    setCodeName(value);
    return value;
  }

  // 正则手机号
  const keyup_tool = (value: any) => {
    return getNumber(value.replace(/[^\d^\.]+/g, ''));
  };

  // 手机号
  const keyup_communityManagerFee = (e: any) => {
    e.target.value = keyup_tool(e.target.value);
  };

  // 上传按钮
  const uploadButton = (
    <div>
      {imgLoad ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  // 文件预览
  const handlePreview = async (file: any) => {
    if (file.url == 'Transfer') {
      // 这是编辑的预览， 需要发送一个请求
      let msg = {
        // userToken: '',
        // type: ans.substr(ans.lastIndexOf('.') + 1),
        type: 'tosCommunityFileService',
        fileName: file.name,
        extends: Data.residentialName,
      };
      RA(47, msg, module, dispatch);
    } else {
      setpreviewImage(file);
      setpreviewVisible(true);
    }
  };

  // 点击移除图片
  const handRemove = (key: any) => {
    key == 1 ? setLouba([]) : key == 2 ? setGuide([]) : setPeriod([]);
  };

  // 点击遮罩回调
  const handleCancel = () => {
    setpreviewVisible(false);
    // 每次关闭预览都要清掉弹窗图片信息   -- 防止编辑打开页面直接弹出窗口
    setpreviewImage({});
    dispatch({ type: module + '/urlRemove' });
  };

  // pdf 总页数
  const onDocumentLoadSuccess = (pages: any) => {
    setNumPages(pages);
  };

  // 切换pdf 总数
  const onChangePage = (page: any) => {
    setPageNumber(page);
  };

  return (
    <>
      <Spin spinning={loading} tip="loading..." size="large">
        <div className="form">
          <h3 className="capi">
            <EditOutlined />
            &nbsp; {Data ? 'edit' : 'Create New'} community
            <div className="back">
              <Button onClick={goToReturn}>
                <LeftOutlined />
                Back
              </Button>
            </div>
          </h3>
          <Form
            name="basic"
            form={form}
            onFinish={onFinish}
            wrapperCol={{ span: 18 }}
            layout="horizontal"
            labelAlign="left"
            scrollToFirstError={true}
          >
            <Form.Item label="Community Name" name="des" rules={[{ required: false }]}>
              <Input.Group compact>
                <Form.Item name={['des', 'residentialZipCode']} noStyle rules={village[0] as any}>
                  <Input
                    style={{ marginRight: '10px', width: 120 }}
                    placeholder="6 Postcode"
                    maxLength={6}
                    onKeyUp={keyup_communityManagerFee}
                  />
                </Form.Item>

                <Form.Item name={['des', 'residentialAddress']} noStyle rules={village[1] as any}>
                  <Input
                    style={{ width: '360px' }}
                    placeholder="Please enter community adds"
                    disabled={codeStrat}
                  />
                </Form.Item>

                <div className="li">
                  <Form.Item
                    name={['des', 'residentialName']}
                    normalize={insdInp}
                    noStyle
                    rules={village[2] as any}
                  >
                    <Input
                      style={{ marginRight: '10px', width: '260px' }}
                      placeholder="Please enter community name"
                      disabled={codeStrat}
                    />
                  </Form.Item>
                  {/* 不可修改提示 */}
                  <span className="redFs">{tipMain}</span>
                </div>
              </Input.Group>
            </Form.Item>

            <Form.Item label="Working Hours" name="workingHours" rules={village[3] as any}>
              <RangePicker format="HH:mm" placeholder={['Start Time', 'End Time']} />
            </Form.Item>

            <Form.Item label="Community Telephone" name="info" rules={[{ required: false }]}>
              <Input.Group compact>
                <Form.Item name={['info', 'tel']} noStyle rules={village[4] as any}>
                  <Input
                    style={{ marginRight: '10px', width: '160px' }}
                    placeholder="Please enter phone"
                    maxLength={11}
                    onKeyUp={keyup_communityManagerFee}
                  />
                </Form.Item>
                <Button type="text">-</Button>
                <Form.Item name={['info', 'email']} noStyle rules={village[5] as any}>
                  <Input
                    style={{ marginLeft: '10px', width: '180px' }}
                    placeholder="Please enter email"
                  />
                </Form.Item>
              </Input.Group>
            </Form.Item>

            <Form.Item
              label="Administrator"
              name="residentialManagerUserName"
              rules={village[6] as any}
            >
              <Input style={{ width: '160px' }} placeholder="Name" maxLength={30} />
            </Form.Item>

            <Form.Item label="Property Fee" name="propertyFee" style={{ marginBottom: '0' }}>
              <Checkbox onChange={onChange} disabled>
                Online Payment
              </Checkbox>
              <Checkbox onChange={onChange} checked>
                Offline Payment
              </Checkbox>
            </Form.Item>

            <hr />
            {/*  上传部分 */}

            <Form.Item
              label="Shuttle Bus Timetable"
              name="balouscheduleFile"
              style={{ marginBottom: '0' }}
            >
              <Upload
                {...uploads}
                {...upload1}
                fileList={loubaUpload}
                beforeUpload={beforeUpload}
                listType="picture-card"
                disabled={codename == '' ? true : false}
                onPreview={() => handlePreview(loubaUpload[0])} // 预览
                onRemove={() => handRemove(1)} //移除
              >
                {loubaUpload.length >= 1 ? null : uploadButton}
              </Upload>
              <div className="tip">
                <span>Support Files：.jpg, .png, .pdf</span>
              </div>
            </Form.Item>

            {/*  上传部分 */}
            <Form.Item label="Property Guide" name="serviceGuideFile" style={{ marginBottom: '0' }}>
              <Upload
                {...uploads}
                {...upload2}
                fileList={guideUpload}
                beforeUpload={beforeUpload}
                listType="picture-card"
                disabled={codename == '' ? true : false}
                onPreview={() => handlePreview(guideUpload[0])} // 预览
                onRemove={() => handRemove(2)} //移除
              >
                {guideUpload.length >= 1 ? null : uploadButton}
              </Upload>
              <div className="tip">
                <span>Support Files：.jpg, .png, .pdf</span>
              </div>
            </Form.Item>

            {/*  上传部分 */}
            <Form.Item
              label="Warranty Period Service"
              name="lifeServiceFile"
              style={{ marginBottom: '0' }}
            >
              <Upload
                {...uploads}
                {...upload3}
                fileList={periodUpload}
                beforeUpload={beforeUpload}
                listType="picture-card"
                disabled={codename == '' ? true : false}
                onPreview={() => handlePreview(periodUpload[0])} // 预览
                onRemove={() => handRemove(3)} //移除
              >
                {periodUpload.length >= 1 ? null : uploadButton}
              </Upload>
              <div className="tip">
                <span>Support Files：.jpg, .png, .pdf</span>
              </div>
            </Form.Item>

            <hr />

            {/* 帮助中心 */}
            <Form.Item label="Help Center" name="help">
              <Input.Group compact>
                <Form.Item name={['help', 'residentialHotlineName']} noStyle>
                  <Input
                    style={{ marginRight: '10px', width: '160px' }}
                    placeholder="Name Of Hotline"
                  />
                </Form.Item>

                <Form.Item name={['help', 'residentialHotline']} noStyle>
                  <Input style={{ marginRight: '10px', width: '180px' }} placeholder="Hotline" />
                </Form.Item>

                <Form.Item name={['help', 'time']} noStyle>
                  <RangePicker format="HH:mm" placeholder={['Start Time', 'End Time']} />
                </Form.Item>
              </Input.Group>
            </Form.Item>

            <hr />
            {/* 提交 */}
            <Form.Item label="" colon={false}>
              <Button type="primary" htmlType="submit" loading={loading}>
                Submit
              </Button>
            </Form.Item>
          </Form>
        </div>

        {/* 附件预览 */}
        <Modal
          title={previewImage != null ? previewImage.name : 'File Preview'}
          visible={previewVisible}
          width={800}
          onCancel={handleCancel}
          style={{ textAlign: 'center' }}
          footer={null}
        >
          {previewImage != null ? (
            previewImage.type == 'pdf' ? (
              // pdf 换一种
              <>
                <PDF
                  file={previewImage.url}
                  page={pageNumber}
                  scale={1.25}
                  onDocumentComplete={onDocumentLoadSuccess}
                />
                <Pagination
                  style={{ textAlign: 'center', marginTop: 10, display: 'block' }}
                  simple
                  defaultCurrent={pageNumber}
                  total={numPages * 10}
                  onChange={onChangePage}
                />
              </>
            ) : previewImage.type == 'jpg' || previewImage.type == 'png' ? (
              // 图片用指定格式

              <Image
                src={previewImage.url}
                preview={false}
                style={{ margin: '0 auto', textAlign: 'center' }}
              />
            ) : (
              <FileViewer fileType={previewImage.type} filePath={previewImage.url} />
            )
          ) : (
            ''
          )}
        </Modal>
      </Spin>
    </>
  );
};

// export default Adds;
function map(state: any) {
  const Data = state.CellList.DataSave;
  const { imgUrl } = state.CellList;
  const loading = state.loading.models.CellList ? state.loading.models.CellList : false;
  const { Result } = state.CellList;
  return { Data, loading, Result, imgUrl };
}
export default connect(map)(Adds);
