import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Radio, Tag, Tooltip, Tabs, Table, notification, Modal, Layout } from 'antd';
import ImageListUpload from '../../../../../components/XForm/ImageListUpload';
import moment from 'moment';
import request from '../../../../../utils/request';
import apis from '../../../../../services/apis';
import router from 'umi/router';
import DragableUploadImageList from '@/components/DragableUploadImageList'

const { Header, Footer, Sider, Content } = Layout;

const modalEdiFormItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const openNotificationWithIcon = (type, message) => {
  notification[type]({
    message,
    description:
      '',
  });
};

/**
 * 弹框
 */
function ModalEdi(props) {
  const { apartment, buildingId, apartmentId } = props.visibleData
  const [visibleData, setVisibleData] = useState({ visible: false, buildingId: '', apartmentId: '', apartment: '' })

  if (!props.visibleData) {
    console.error('缺少visibleData参数!')
  }

  useEffect(() => {
    setVisibleData(props.visibleData)
    props.form.setFieldsValue({ apartmentId, apartmentName: apartment !== '' ? apartment.apartmentName : '' })
  }, [props.visibleData.visible])

  function handleOk(e) {
    // console.log(e);
    props.onCancel();
    props.form.resetFields();
  }

  function handleCancel(e) {
    // console.log(e);
    props.onCancel();
    props.form.resetFields();
  }

  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        submitData(values)
      }
    });
  }

  function submitData(data) {
    if (buildingId === '' || buildingId === undefined) {
      return
    }
    if (data.img) {
        // 如果是 名称 和 图片一起编辑，就穿最新的图片
      data.img = data.img.map((item, index) => ({ imgType: 'aparment', url: item, orderNo: index }))
    } else {
        // 如果是 名称 和 图片一起编辑，就穿最新的图片
      data.img = visibleData.apartment.buildingImgList
    }
    data.buildingId = buildingId;
    data.apartmentType = 'photo'
    const api = (data.apartmentId !== undefined && data.apartmentId !== '') ? apis.building.buildingApartmentUpdate : apis.building.buildingApartmentAdd;

    // 网路请求
    request({ ...api, data: { ...data } }).then(() => {
      // eslint-disable-next-line no-unused-expressions
      openNotificationWithIcon('success', '操作成功')
      handleCancel()
      props.onSuccess()
      // this.setState({ visibleData: { visible: false, apartmentId: '', buildingId: '' } }, () => console.log('回调：', this.state.visibleData))
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      openNotificationWithIcon('error', err)
    })
  }

  const { getFieldDecorator } = props.form;
  return (
    <>
      <Modal
          title="编辑"
          visible={visibleData.visible}
          onOk={handleOk}
          onCancel={handleCancel}
          width={700}
          footer={null}
        >
         <Form {...modalEdiFormItemLayout} onSubmit={handleSubmit}>
          <Form.Item label="编号" style={{ display: 'none' }}>
              {getFieldDecorator('apartmentId')(<Input />)}
          </Form.Item>
          <Form.Item label="相册名称">
            {getFieldDecorator('apartmentName', {
              rules: [
                {
                  required: true,
                  message: '请输入相册名称',
                },
                {
                  max: 10,
                  message: '不超过10个字符',
                },
              ],
            })(<Input />)}
          </Form.Item>
          {
            !props.noImage && <Form.Item label="选择图片" help="建议图片尺寸750px*562px，比例4:3,格式：jpg">
            {getFieldDecorator('img', {
              rules: [
                {
                  required: true,
                  message: '请选择图片',
                },
              ],
            })(<ImageListUpload />)}
          </Form.Item>
          }
          <Form.Item style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <Button onClick={() => handleCancel()}>
              取消
            </Button>
          </Form.Item>
         </Form>
        </Modal>
    </>
  )
}

const WrappedModalEdiForm = Form.create({ name: 'ModalEdi' })(ModalEdi);

/**
 * 模块
 */
function BuildingImageModel(props) {
  const [imageList, setImageList] = useState([])
  const [visibleData, setVisibleData] = useState({ visible: false, buildingId: '', apartmentId: '', apartment: '' })

  useEffect(() => {
    setImageList(getImgUrl())
  }, [props.apartment.apartmentId])

  function getImgUrl() {
    return ((props.apartment.buildingImgList || [])).map(item => item.url)
  }

  function submitData(data) {
    const { apartmentId } = props.apartment
    if (apartmentId === '' || apartmentId === undefined) {
      return
    }

    data.buildingId = props.apartment.buildingId;
    data.apartmentType = 'photo'
    const api = data.apartmentId !== undefined ? apis.building.buildingApartmentUpdate : apis.building.buildingApartmentAdd;

    // 网路请求
    request({ ...api, data: { ...data } }).then(() => {
      // eslint-disable-next-line no-unused-expressions
      openNotificationWithIcon('success', '操作成功')
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      // openNotificationWithIcon('error', err)
    })
  }

  function onImageChange(e) {
    setImageList(e)
       
    // 新增加图片后，更新后端数据
    const img = e.map((item, index) => ({ imgType: 'aparment', url: item, orderNo: index }))
    submitData({ ...props.apartment, img })
  }

  function edi() {
    setVisibleData({ visible: true, buildingId: props.apartment.buildingId, apartmentId: props.apartment.apartmentId, apartment: props.apartment })
  }

  function onCancel(e) {
    setVisibleData({ visible: false, buildingId: '', apartmentId: '', apartment: '' })
  }

  function deletePhoto() {
    Modal.confirm({
      title: '确认删除当前相册',
      // content: 'Bla bla ...',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        request({ ...apis.building.buildingApartmentDelete, urlData: { id: props.apartment.apartmentId } }).then(() => {
          openNotificationWithIcon('success', '操作成功')
          props.onSuccess()
        }).catch(err => {
    
        })
      },
    });
    
  }

  return (
    <>
      <Button style={{ marginLeft: '18px', float: 'right' }} onClick={() => router.go(-1)}>返回</Button>
      <span style={{ marginTop: '10px', marginBottom: '10px' }}>{props.apartment.apartmentName}({imageList.length})</span>
      <Button type="link" style={{ color: 'blue' }} onClick={() => edi()}>重命名</Button>
      <Button type="link" style={{ color: 'blue' }} onClick={() => deletePhoto()}>删除相册</Button>
      <DragableUploadImageList value={imageList} onChange={onImageChange} unlimited/>
      {/* <ImageListUpload value={imageList} onChange={onImageChange} unlimited/> */}

       {/* 编辑页 */}
       <WrappedModalEdiForm visibleData={visibleData} onCancel={e => onCancel(e)} onSuccess={() => props.onSuccess()} noImage/>
       <hr />
    </>
  )
}

/**
 * 主体
 */
function buildingImage(props) {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [visibleData, setVisibleData] = useState({ visible: false, buildingId: '', apartmentId: '', apartment: '' })
  const [imageList, setImageList] = useState([])

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    getList()
  }, [props.building.buildingId])
 

  function edi() {
    setVisibleData({ visible: true, buildingId: props.building.buildingId, apartmentId: '', apartment: '' })
  }

  function onCancel(e) {
    setVisibleData({ visible: false, buildingId: '', apartmentId: '', apartment: '' })
  }

  function onSuccess(e) {
    getList()
  }

  function getList(params) {
    // 网路请求
    request({ ...apis.building.buildingApartment, urlData: { id: props.building.buildingId }, params: { ...params, apartmentType: 'photo' } }).then(res => {
      setImageList(res)
    }).catch(err => {
      openNotificationWithIcon('error', err.message)
    })
  }

  return (
    <>
      <Button type="primary" onClick={() => edi()}>新增</Button>
      <Layout style={{ background: '#fff' }}>
        {
          imageList.map(item => <Content><BuildingImageModel apartment={item} key={item.apartmentId} onSuccess={e => onSuccess(e)}/></Content>)
        }
      </Layout>

      {/* 编辑页 */}
      <WrappedModalEdiForm visibleData={visibleData} onCancel={e => onCancel(e)} onSuccess={e => onSuccess(e)}/>
    </>
  )
}

export default buildingImage
