import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Radio, Tag, Tooltip, Tabs, InputNumber, notification } from 'antd';
import moment from 'moment';
import { router } from 'umi';
import request from '../../../../../utils/request';
import apis from '../../../../../services/apis';
import Styles from '../style.less';
import ImageUpload from '../../../../../components/XForm/ImageUpload'
import ImageListUpload from '../../../../../components/XForm/ImageListUpload'
import Wangedit from '../../../../../components/Wangedit/Wangedit'
import TagGroup from './tags'
import Amap from './amap'
import BudildingProjectType from './buildingProjectType'
import SelectCity from '../../../../../components/SelectButton/CitySelect'
import FileUpload from '@/components/XForm/FileUpload';
import { POI_TYPES_KETY, getAroundData, getPOIType, POI_TYPES } from './amapAroundData'
import { ifError } from 'assert';

const { Option } = Select
const { TabPane } = Tabs;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 2 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};


function openNotificationWithIcon(type, message) {
  notification[type]({
    message,
    description:
      '',
  });
}


function AddBuilding(props) {
  const { getFieldDecorator } = props.form;

  const [poi, setPoi] = useState([])

  // console.log('props.building: ', props.building)
  const { buildingId } = props.building
     // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
      if (buildingId && buildingId !== '') {
        getById(buildingId)
      }
  }, [buildingId])

   // 获取详情信息
   function getById(currentId) {
    request({ ...apis.building.buildingGetById, urlData: { id: currentId } }).then(res => {
      if (res.openingDate !== null) {
        res.openingDate = moment(res.openingDate)
      }
      if (res.receivedDate !== null) {
        res.receivedDate = moment(res.receivedDate)
      }
      if (res.buildingTag !== null) {
        res.tag = res.buildingTag.map((item, _) => item.tagName)
      }

      res.avatarImage = res.buildingImg.map(item => item.url)
      
      if (res.buildingListImg) {
        res.listImage = res.buildingListImg.map(item => item.url)
      }
      res.mapCoordinate = res.coordinate
      if (res.videoUrl) {
        res.videoUrl = [].concat(res.videoUrl)
      }
      if (res.videoImage) {
        res.videoImage = res.videoImage[0].url
      }
      // setPoi(res.mapJson || [])
      props.form.setFieldsValue(res)
      props.onSuccess(res)
    })
  }

  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        addBuilding(values)
      }
    });
  }

  function addBuilding(data) {
    // console.log('poi: ', poi)
    if (poi.length !== 0) {
      data.mapJson = poi
    }
    
    data.openingDate = moment(data.openingDate, 'yyyy-MM-dd HH:mm:ss')
    data.receivedDate = moment(data.receivedDate, 'yyyy-MM-dd HH:mm:ss')
    // 项目主图
    data.img = data.avatarImage && data.avatarImage.map((item, index) => ({ imgType: 'banner', url: item, orderNo: index + 1 }))
    // 列表图
    data.listImg = data.listImage && data.listImage.map((item, index) => ({ imgType: 'list', url: item, orderNo: index + 1 }))
    if (data.videoUrl) {
      // console.log(data.videoUrl[0])
      data.videoUrl = data.videoUrl[0]
    }
    
    if (data.tag) {
      data.tag = data.tag.map((item, _) => ({ tagName: item }))
    }

    if (data.videoImage) {
      data.videoImage = [{ imgType: 'videoImage', url: data.videoImage, orderNo: 1 }]
    }

    const api = data.buildingId === undefined ? apis.building.addBuilding : apis.building.updateBuilding
    request({ ...api, data: { ...data } }).then(res => {
      openNotificationWithIcon('success', '操作成功')
      // router.go(-1)
      getById(res.buildingId)
    }).catch(err => {
      // openNotificationWithIcon('error', err.message)
    })
  }

  // 视频文件上传前 回调
  function fileUploadBeforeUpload(file, fileList) {
    // console.log('视频文件上传前 回调: ', file, fileList)
    return new Promise((resolve, reject) => {
      if (file.type === 'video/mp4' || file.type === '.mp4') {
          resolve(file)
      } else {
        openNotificationWithIcon('error', '项目视频，仅支持MP4格式')
        reject()
      }
    })
  }

  // 周边设施 回调
  function getMapScope(e) {
    const coordinate = props.form.getFieldValue('coordinate').split(',')
    const poiData = [].concat(POI_TYPES)
    poiData.map(item => {
      getAroundData({ types: item.key, location: `${coordinate[1]},${coordinate[0]}`, radius: e }).then(res => {
        const { pois } = res
        setFormMapScopeValue(item.key, pois)
      }).catch(err => {
        console.log(err.message)
        openNotificationWithIcon('error', '周边数据获取失败')
      })
    })
  }

  function setFormMapScopeValue(key, pois) {
    const poiArray = pois.map(p => {
      return {
        address: p.address,
        adname: p.adname,
        cityname: p.cityname,
        distance: p.distance,
        id: p.id,
        location: p.location,
        name: p.name,
        pname: p.pname,
        shopinfo: p.shopinfo,
        type: p.type,
        typecode: p.typecode,
      }
    })
    
    // 设置表单值
    getFormMapScopeName(key, { data: poiArray })

    const poiData = [].concat(POI_TYPES)
    const newPoi = poiData.map(m => {
      if (m.key === key) {
        m.data = poiArray
      }
      return m
    })
    setPoi(newPoi)
  }

  function getFormMapScopeName(keyType, item) {
    switch (keyType) {
      case POI_TYPES_KETY.Transport:
        props.form.setFieldsValue({ buildingTransport: item.data.map(t => t.name).join(',') })
        return 'buildingTransport';
      case POI_TYPES_KETY.Bank:
        props.form.setFieldsValue({ buildingBank: item.data.map(t => t.name).join(',') })
        return 'buildingBank';
      case POI_TYPES_KETY.Edu:
        props.form.setFieldsValue({ buildingEdu: item.data.map(t => t.name).join(',') })
        return 'buildingEdu';
      case POI_TYPES_KETY.Hospital:
        props.form.setFieldsValue({ buildingHospital: item.data.map(t => t.name).join(',') })
        return 'buildingHospital';
      case POI_TYPES_KETY.Restaurant:
        props.form.setFieldsValue({ buildingRestaurant: item.data.map(t => t.name).join(',') })
        return 'buildingRestaurant';
      case POI_TYPES_KETY.Mall:
        props.form.setFieldsValue({ buildingMall: item.data.map(t => t.name).join(',') })
        return 'buildingMall';
      default:
    }
  }

  return (
        <Form {...formItemLayout} onSubmit={handleSubmit}>
          <Form.Item label="项目Id" style={{ display: 'none' }}>
            {getFieldDecorator('buildingId')(<Input disabled />)}
          </Form.Item>
          <Form.Item label="楼盘编号" >
            {getFieldDecorator('code', {
              rules: [{ required: true, message: '请输入楼盘编号' }],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="楼盘名称" >
            {getFieldDecorator('buildingName', {
              rules: [{ required: true, message: '请输入楼盘名' }],
            })(<Input />)}
          </Form.Item>
          {/* <Form.Item label="别名" >
            {getFieldDecorator('name')(<Input />)}
          </Form.Item> */}
          <Form.Item label="项目类型">
            {getFieldDecorator('buildingProjectType', {
              rules: [{ required: true, message: '请选择项目类型' }],
            })(<BudildingProjectType />)}
          </Form.Item>
          <Form.Item label="均价" >
            {getFieldDecorator('price')(<Input type="number" style={{ width: '210px' }}/>)}元/m²
          </Form.Item>
          <Form.Item label="开盘时间" >
            {getFieldDecorator('openingDate')(<DatePicker format="YYYY/MM/DD" />)}
          </Form.Item>
          <Form.Item label="电话" >
            {getFieldDecorator('tel', {
              initialValue: '',
              rules: [
                  {
                      pattern: new RegExp('^[0-9]*$'),
                      message: '请输入正确的电话号码',
                  },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="项目动态" >
            {getFieldDecorator('dynamic')(<Input />)}
          </Form.Item>
          <Form.Item label="物业类型" >
            {getFieldDecorator('propertyType')(
              // <Select mode="multiple" placeholder="物业类型" style={{ width: '1016px' }}>
              //   <Option value="未知">未知</Option>
              // </Select>,
              <Input />,
            )}
          </Form.Item>
          <Form.Item label="销售状态" >
            {getFieldDecorator('marketStatus', {
              rules: [{ required: true, message: '请选择销售状态' }],
            })(
              <Select placeholder="销售状态" style={{ width: '1016px' }}>
                <Option value="待定">待定</Option>
                <Option value="在售">在售</Option>
                <Option value="售完">售完</Option>
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="项目标签" >
            {getFieldDecorator('tag')(
              <Select mode="tags" placeholder="输入后选中" style={{ width: '1016px' }}>

              </Select>,
            )}
          </Form.Item>
          <Form.Item label="项目视频" help="视频仅支持mp4格式，建议尺寸：1920*1080，比例16:9">
            {getFieldDecorator('videoUrl')(
              // disabled={fileUploadDisabled}
              <FileUpload accept=".mp4" beforeUpload={fileUploadBeforeUpload} label="上传视频" size={1} />,
            )}
          </Form.Item>
          <Form.Item label="视频封面图" help="建议图片尺寸：750*600px，比例5:4,格式：jpg，用于视频封面" >
            {getFieldDecorator('videoImage', {
              rules: [{ required: true, message: '请选择视频封面图' }],
            })(
              <ImageUpload />,
            )}
          </Form.Item>
          <Form.Item label="楼盘主图" help="建议图片尺寸：750*600px，比例5:4,格式：jpg，用于楼盘详情">
            {getFieldDecorator('avatarImage', {
              rules: [{ required: true, message: '请选择项目主图' }],
            })(
              <ImageListUpload />,
            )}
          </Form.Item>
          <Form.Item label="楼盘封面图" help="建议图片尺寸：750*420px，比例16:9,格式：jpg，用于楼盘列表">
            {getFieldDecorator('listImage', {
              rules: [{ required: true, message: '请选择列表图' }],
            })(
              <ImageListUpload />,
            )}
          </Form.Item>
          {/* <Form.Item label="地址图片" help="建议图片尺寸：750px*455px">
            {getFieldDecorator('mapImg')(
              <ImageUpload />,
            )}
          </Form.Item> */}
          {/* <Form.Item label="海报底图" help="建议图片尺寸：640px*1136px" >
            {getFieldDecorator('poster')(
              <ImageUpload />,
            )}
          </Form.Item> */}
          <Form.Item label="排序" >
            {getFieldDecorator('orderNo')(<Input />)}
          </Form.Item>
          <Form.Item label="优惠信息" >
            {getFieldDecorator('discount')(<Input />)}
          </Form.Item>
          <Form.Item label="首页推荐" >
            {getFieldDecorator('isMain', {
              initialValue: 1,
            })(
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={2}>否</Radio>
            </Radio.Group>,
            )}
          </Form.Item>
          <Form.Item label="所在城市" >
            {getFieldDecorator('cityId', {
              rules: [{ required: true, message: '请选择城市' }],
            })(
              <SelectCity />,
            )}
          </Form.Item>
          <Form.Item label="楼盘区域" >
            {getFieldDecorator('buildingArea', {
              rules: [{ required: true, message: '请输入楼盘区域' }],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="项目地址" >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请输入项目地址' }],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="项目坐标" >
            {getFieldDecorator('coordinate', {
              rules: [{ required: true, message: '请输入项目坐标' }],
            })(<Input disabled />)}
          </Form.Item>
          <Form.Item label="地图位置" >
            {getFieldDecorator('mapCoordinate')(<Amap onChange={e => props.form.setFieldsValue({ coordinate: e })}/>)}
          </Form.Item>
          <Form.Item label="周边设施搜索范围" style={{ width: '2000px' }}>
            {getFieldDecorator('mapScope', {
              rules: [{ required: true, message: '请选择周边设施搜索范围' }],
            })(
              <Select placeholder="请选择周边设施搜索范围" style={{ width: '970px' }} onChange={e => getMapScope(e)}>
                <Option value={1000}>1公里</Option>
                <Option value={3000}>3公里</Option>
                <Option value={5000}>5公里</Option>
                <Option value={10000}>10公里</Option>
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="周边交通" >
            {getFieldDecorator('buildingTransport')(
              <TagGroup />,
            )}
          </Form.Item>
          <Form.Item label="周边商业" >
            {getFieldDecorator('buildingMall')(
              <TagGroup />,
            )}
          </Form.Item>
          <Form.Item label="周边学校" >
            {getFieldDecorator('buildingEdu')(
              <TagGroup />,
            )}
          </Form.Item>
          <Form.Item label="周边医院" >
            {getFieldDecorator('buildingHospital')(
              <TagGroup />,
            )}
          </Form.Item>
          <Form.Item label="周边银行" >
            {getFieldDecorator('buildingBank')(
              <TagGroup />,
            )}
          </Form.Item>
          <Form.Item label="周边餐饮" >
            {getFieldDecorator('buildingRestaurant')(
              <TagGroup />,
            )}
          </Form.Item>
          <Form.Item label="绿化率" >
            {getFieldDecorator('greeningRate')(<Input />)}
          </Form.Item>
          <Form.Item label="容积率" >
            {getFieldDecorator('volumeRate')(<Input />)}
          </Form.Item>
          <Form.Item label="车位比" >
            {getFieldDecorator('parkingRate')(<Input />)}
          </Form.Item>
          <Form.Item label="规划户数" >
            {getFieldDecorator('familyNum')(<InputNumber />)}
          </Form.Item>
          <Form.Item label="物业公司" >
            {getFieldDecorator('serviceCompany')(<Input />)}
          </Form.Item>
          <Form.Item label="物业费" >
            {getFieldDecorator('serviceFee')(<Input />)}
          </Form.Item>
          <Form.Item label="装修标准" >
            {getFieldDecorator('decoration')(<Input />)}
          </Form.Item>
          <Form.Item label="交房时间" >
            {getFieldDecorator('receivedDate')(<DatePicker />)}
          </Form.Item>
          <Form.Item label="产权年限" >
            {getFieldDecorator('rightsYear')(<InputNumber />)}
          </Form.Item>
          <Form.Item label="预售许可证" >
            {getFieldDecorator('preSalePermit')(
              <ImageUpload />,
            )}
          </Form.Item>
          <Form.Item label="项目备注" >
            {getFieldDecorator('remark')(
              <Wangedit />,
            )}
          </Form.Item>
          <Form.Item style={{ width: '400px', margin: 'auto', display: 'flex', justifyContent: 'space-between' }}>
            <Button type="primary" htmlType="submit">
                确定
            </Button>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <Button onClick={() => router.go(-1)}>
                取消
            </Button>
          </Form.Item>
        </Form>
  )
}

const WrappedAddBuildingForm = Form.create({ name: 'addBuilding' })(AddBuilding);

export default WrappedAddBuildingForm
