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

import moment from 'moment';

const { RangePicker } = TimePicker;

// 接口申明
interface objc {}

const Adds = (props: any) => {
  const { Data, dispatch, loading, Result } = props;

  console.log(loading);

  const [form] = Form.useForm();

  //物业费选择
  const plainOptions = [
    { label: 'Online Payment', value: '0', disabled: true },
    { label: 'Offline Payment', value: '1' },
  ];

  // 表单物业费提交值
  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('');

  // 监听提交
  // useEffect(() => {
  //   console.log(Result);
  //   if (Result != null) {
  //     console.log('页面结果');
  //     console.log(Result);
  //     if (Result.error_code == undefined) {
  //       console.log('服务器有问题');
  //       message.error('服务器有问题，请求失败', 5);
  //     }
  //     if (Result.error_code == '0000') {
  //       message.success(`Community Saved Successfully`);
  //       ResultClear(module, dispatch);
  //       history.go(-1);
  //     }
  //   }
  // }, [Result]);

  // 赋值
  useEffect(() => {
    // 如果是添加传来没有值的时候 就清空  否则  赋值给表单
    if (Data) {
      // 返回列表
      form.setFieldsValue({
        // 必填的
        des: {
          residentialZipCode: Data.residentialZipCode,
          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('新建');
    }
  }, [1]);

  // 返回上传格式 和 地址
  function backUpload(str: string, index: number) {
    let a = {
      uid: str + index,
      name: str,
      url: 'http://',
    };
    return a;
  }

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

  // 楼巴上传
  const upload1 = {
    onChange(info: any) {
      if (codename !== '') {
        let po = new Array();
        po.push(info.fileList[info.fileList.length - 1]);
        // 给楼巴上传列表值
        console.log(po);
        setLouba(po);
        setcodeStrat(true);
        setTipMain('Binding Content Already Exists, Cannot Be Modified！');
        // 结果
        uploadMsg(info);
      } else {
        message.warning('Please Fill In The Community Name');
      }
    },
  };
  // 指南上传
  const upload2 = {
    onChange(info: any) {
      if (codename !== '') {
        let po = new Array();
        po.push(info.fileList[info.fileList.length - 1]);
        // 给楼巴上传列表值
        setGuide(po);
        setcodeStrat(true);
        setTipMain('Binding Content Already Exists, Cannot Be Modified！');
        // 结果
        uploadMsg(info);
      } else {
        message.warning('Please Fill In The Community Name');
      }
    },
  };
  // 保质期上传
  const upload3 = {
    onChange(info: any) {
      if (codename !== '') {
        let po = new Array();
        po.push(info.fileList[info.fileList.length - 1]);
        // 给楼巴上传列表值  以及禁止修改小区名
        setPeriod(po);
        setcodeStrat(true);
        setTipMain('Binding Content Already Exists, Cannot Be Modified！');
        // 结果
        uploadMsg(info);
      } else {
        message.warning('Please Fill In The Community Name');
      }
    },
  };

  // 上传提示
  function uploadMsg(info: any) {
    if (info.file.status === 'done') {
      message.success(`${info.file.name} File Uploaded Successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.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, residentialAddress, residentialName } = values.des;
    if (residentialZipCode.length < 6) {
      message.error('Please Enter 6-digit Zip Code！');
    } else {
      onUpDate(values);
    }
  };

  // 表单提交
  function onUpDate(values: any) {
    console.log(values.help);
    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)
        : values.info.tel;
      obj.residentialHotline = values.help.residentialHotlineName
        ? 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');
    }
    console.log('Success:', obj);

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

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

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

  return (
    <>
      <Spin spinning={loading} tip="信息提交中..." size="large">
        <div className="form">
          <h3 className="capi">
            <EditOutlined />
            &nbsp; {Data ? 'edit' : 'establish'} 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"
          >
            <Form.Item label="Community Name" name="des" rules={village[4] as any}>
              <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}
                  />
                </Form.Item>

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

                <div className="li">
                  <Form.Item
                    name={['des', 'residentialName']}
                    normalize={insdInp}
                    noStyle
                    rules={village[0] 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[1] as any}>
              <RangePicker format="HH:mm" placeholder={['Start Time', 'End Time']} />
            </Form.Item>

            <Form.Item label="Community Telephone" name="info" rules={village[3] as any}>
              <Input.Group compact>
                <Form.Item name={['info', 'tel']} noStyle rules={village[0] as any}>
                  <Input
                    style={{ marginRight: '10px', width: '160px' }}
                    placeholder="Please enter phone"
                  />
                </Form.Item>
                <Button type="text">—</Button>
                <Form.Item name={['info', 'email']} noStyle rules={village[0] as any}>
                  <Input
                    style={{ marginLeft: '10px', width: '180px' }}
                    placeholder="Please enter Email"
                  />
                </Form.Item>
              </Input.Group>
            </Form.Item>

            <Form.Item
              label="Administrators"
              name="residentialManagerUserName"
              rules={village[2] as any}
            >
              <Input style={{ width: '160px' }} placeholder="Contacts" />
              {/* <Button type="text">
            <PlusCircleOutlined style={{ fontSize: '18px', color: '#08c' }} />
          </Button> */}
            </Form.Item>

            <Form.Item label="Property Fee" name="propertyFee" style={{ marginBottom: '0' }}>
              <Checkbox.Group options={plainOptions} defaultValue={['1']} onChange={onChange} />

              <div className="tip capi">
                <span>*</span>There will be a service charge for online payment
              </div>
            </Form.Item>

            <hr />
            {/*  上传部分 */}
            <Form.Item
              label="Louba Timetable"
              name="balouscheduleFile"
              style={{ marginBottom: '0' }}
            >
              <Upload {...uploads} {...upload1} fileList={loubaUpload} showUploadList={false}>
                <Button icon={<UploadOutlined />}>Click to Upload</Button>
              </Upload>
              <div className="tip">
                <p className={loubaUpload.length > 0 ? 'show' : ''}>
                  <LinkOutlined color="#409EFF" />
                  {loubaUpload.length > 0 ? loubaUpload[0].name : ''}
                </p>
                <span className="capi">Support Files：.doc,.docx,.jpg,.png,.pdf</span>
              </div>
            </Form.Item>

            <Form.Item label="Property Guide" name="serviceGuideFile" style={{ marginBottom: '0' }}>
              <Upload {...uploads} {...upload2} fileList={guideUpload} showUploadList={false}>
                <Button icon={<UploadOutlined />}>Click to Upload</Button>
              </Upload>
              <div className="tip">
                <p className={guideUpload.length > 0 ? 'show' : ''}>
                  <LinkOutlined color="#409EFF" />
                  {guideUpload.length > 0 ? guideUpload[0].name : ''}
                </p>
                <span className="capi">Support Files：.doc,.docx,.jpg,.png,.pdf</span>
              </div>
            </Form.Item>

            <Form.Item
              label="Period Of Service"
              name="lifeServiceFile"
              style={{ marginBottom: '0' }}
            >
              <Upload {...uploads} {...upload3} fileList={periodUpload} showUploadList={false}>
                <Button icon={<UploadOutlined />}>Click to Upload</Button>
              </Upload>
              <div className="tip">
                <p className={periodUpload.length > 0 ? 'show' : ''}>
                  <LinkOutlined color="#409EFF" />
                  {periodUpload.length > 0 ? periodUpload[0].name : ''}
                </p>
                <span className="capi">Support Files：.doc,.docx,.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>
      </Spin>
    </>
  );
};

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