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 { ifError } from 'assert';
import request from '../../../../../utils/request';
import apis from '../../../../../services/apis';
import Styles from '../style.less';
import ImageUpload from '../../../../../components/XForm/ImageUpload'
import NewImageUpload from '../../../../../components/uploadImage/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 DragableUploadImageList from '@/components/DragableUploadImageList'
import SelectCity from '../../../../../components/SelectButton/CitySelect'
import AreaSelect from '../../../../../components/SelectButton/AreaSelect'
import FileUpload from '@/components/XForm/FileUpload';
import { POI_TYPES_KETY, getAroundData, getPOIType, POI_TYPES } from './amapAroundData'

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([])
  const [videoImage, setVideoImage] = useState(false)
  const [typeState, setTypeState] = useState("rich")
  const [cityId, setCityId] = useState("")

  // 存放所以 buildingData 基础信息
  const [buildingData, setBuildingData] = 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])

  useEffect(() => {
    setPoiTagValue()
  }, [poi])


  // 把地图设置在的数据设置在 tag控件上 上
  function setPoiTagValue() {
    if (poi) {
      console.log('poi: ', poi)


      poi.map(x => {
        const ty = Object.prototype.toString
        // console.log('x.data: ', JSON.parse(x.data))
        // console.log('x.data: ', typeof x.data, x.data instanceof String, ty.call(x.data))
        if (ty.call(x.data) === '[object String]') {
          setFormMapScopeTagValue(x.key, { data: JSON.parse(x.data) })
        }
      })
    }
  }

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

      if (res.buildingListImg) {
        // res.listImage = res.buildingListImg.map(item => item.url)
        res.listImage = res.buildingListImg.map(item => item.url)[0]
      }
      res.mapCoordinate = res.coordinate
      if (res.videoUrl) {
        res.videoUrl = [].concat(res.videoUrl)
        setVideoImage(true)
      }
      if (res.videoImage) {
        res.videoImage = res.videoImage[0].url
      }

      res.buildingTransport = stringHandleTag(res.buildingTransport)
      res.buildingMall = stringHandleTag(res.buildingMall)
      res.buildingEdu = stringHandleTag(res.buildingEdu)
      res.buildingHospital = stringHandleTag(res.buildingHospital)
      res.buildingBank = stringHandleTag(res.buildingBank)
      res.buildingRestaurant = stringHandleTag(res.buildingRestaurant)

      setBuildingData(res)

      props.form.setFieldsValue(res)
      // console.log('mapJson: ', JSON.parse(res.mapJson))
      setPoi((res.mapJson && JSON.parse(res.mapJson)) || [])
      props.onSuccess(res)
    })
  }

  /**
   * 把 xxx,xxx,xxx  这样的格式转换成 [{ tagName: xxx, delete: true, automatic: false }, { tagName: xxx, delete: true, automatic: false }]
   * @param {*} str
   * @return 如果返回 str 为空 或者 非 string，则返回 str 本身，否则返回转换成功的数组
   */
  function stringHandleTag(str) {
    if (typeof str === 'string' && str !== '') {
      const arr = str.split(',')
      return arrayTransition(arr)
    }

    return str
  }

  /**
   * 把 [xxx,xxx,xxx]  这样的格式转换成 [{ tagName: xxx, delete: true, automatic: false }, { tagName: xxx, delete: true, automatic: false }]
   * @param {*} arr
   */
  function arrayTransition(arr) {
    return arr.map(x => ({ tagName: x, delete: true, automatic: false }))
  }

  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 && [{ imgType: 'list', url: data.listImage, orderNo: 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 }]
    }

    if (data.buildingTransport) {
      data.buildingTransport = tagFilter(data.buildingTransport, 'Transport')
    }
    if (data.buildingMall) {
      
      data.buildingMall = tagFilter(data.buildingMall, 'Mall')
    }
    if (data.buildingEdu) {
      data.buildingEdu = tagFilter(data.buildingEdu, 'Edu')
    }
    if (data.buildingHospital) {
      data.buildingHospital = tagFilter(data.buildingHospital, 'Hospital')
    }
    if (data.buildingBank) {
      data.buildingBank = tagFilter(data.buildingBank, 'Bank')
    }
    if (data.buildingRestaurant) {
      data.buildingRestaurant = tagFilter(data.buildingRestaurant, 'Restaurant')
    }
  
    // if(typeof(data.highlights) != "undefined" && (typeof(data.highlightsCover) == "undefined" || data.highlightsCover == null)){
    //   openNotificationWithIcon('error', '请上传项目亮点封面')
    //   return;
    // }
    console.log(data,"datadataddata")
    if(typeof(data.highlights) == "undefined"){
      data.highlights = null;
    }
    
    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)
    })
  }

  /**
   * 过滤 tag
   * @param {*} tags 
   */
  function tagFilter(tags, keyType) {
    
    console.log(tags)
    if (!tags) {
      return null
    }

    // 过滤 tag 更新 useState()

    // 获取地图周边
    const automaticTag = tags.filter(f => f.automatic === true).map(x => x.tagName)
    const determineTag = poi.map(p => {
      if (p.key === keyType) {
        if (typeof p.data === 'string') {
          p.data = JSON.parse(p.data).filter(f => automaticTag.includes(f.name))
        } else {
          p.data = p.data.filter(f => automaticTag.includes(f.name))
        }
      }
      return p
    })

    setPoi(determineTag)

    
    return tags.filter(f => f.automatic === false).map(x => x.tagName).join(',')
  }

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

  // 周边设施 回调
  function getMapScope(e) {
    const coordinateValue = props.form.getFieldValue('coordinate')
    if (!coordinateValue) {
      openNotificationWithIcon('error', '请先选择项目坐标位置')
      return
    }
    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 highlightsTypeChange(e) {
    console.log(e.target.value,"ee")
    setTypeState(e.target.value)
  }

  function setFormMapScopeValue(key, pois) {
    const poiArray = pois.map(p => ({
        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,
      }))

    // 设置表单值
    setFormMapScopeTagValue(key, { data: poiArray })

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

    setPoi(newPoi)
    return newPoi
  }

  function cityChange(e) {
    setCityId(e)
    if(buildingData.cityId === e){
      setTimeout(()=>{
        props.form.setFieldsValue({
            'buildingArea': buildingData.buildingArea
        })
    },0)
    }
  }

  function setFormMapScopeTagValue(keyType, item) {
    const tag = item.data.map(t => ({ tagName: t.name, delete: true, automatic: true }))
    switch (keyType) {
      case POI_TYPES_KETY.Transport:
        const buildingTransportValue = (stringHandleTag(buildingData.buildingTransport) || [])
        props.form.setFieldsValue({ buildingTransport: tag.concat(buildingTransportValue) })
        return 'buildingTransport';
      case POI_TYPES_KETY.Bank:
        const buildingBankValue = (stringHandleTag(buildingData.buildingBank) || [])
        props.form.setFieldsValue({ buildingBank: tag.concat(buildingBankValue) })
        return 'buildingBank';
      case POI_TYPES_KETY.Edu:
        const buildingEduValue = (stringHandleTag(buildingData.buildingEdu) || [])
        props.form.setFieldsValue({ buildingEdu: tag.concat(buildingEduValue) })
        return 'buildingEdu';
      case POI_TYPES_KETY.Hospital:
        const buildingHospitalValue = (stringHandleTag(buildingData.buildingHospital) || [])
        props.form.setFieldsValue({ buildingHospital: tag.concat(buildingHospitalValue) })
        return 'buildingHospital';
      case POI_TYPES_KETY.Restaurant:
        const buildingRestaurantValue = (stringHandleTag(buildingData.buildingRestaurant) || [])
        props.form.setFieldsValue({ buildingRestaurant: tag.concat(buildingRestaurantValue) })
        return 'buildingRestaurant';
      case POI_TYPES_KETY.Mall:
        const buildingMallValue = (stringHandleTag(buildingData.buildingMall) || [])
        props.form.setFieldsValue({ buildingMall: tag.concat(buildingMallValue) })
        return 'buildingMall';
      default:
        return ''
    }
  }

  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="列表展示均价" help="项目列表展示价格，示例：约10000元/㎡、约1000万元/套起">
            {/* {getFieldDecorator('price')(<Input type="number" style={{ width: '210px' }}/>)}元/m² */}
            {getFieldDecorator('price')(<Input />)}
          </Form.Item>
          <Form.Item label="开盘时间" >
            {getFieldDecorator('openingDate')(<Input placeholder="预计xxxx年xx月开盘" maxLength = "15"/>)}
          </Form.Item>
          <Form.Item label="电话" >
            {getFieldDecorator('tel', {
              initialValue: '',
              rules: [
                  {
                      pattern: new RegExp('^[0-9]*$'),
                      message: '请输入正确的电话号码',
                  },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="项目说明" >
            {getFieldDecorator('dynamic')(<Input placeholder="项目动态等，不超过30个字" maxLength = "30"/>)}
          </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> */}
                <Option value="在线选房">在线选房</Option>
                <Option value="待售">待售</Option>
                <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格式，建议尺寸：750*600，比例5:4，用于楼盘详情">
            {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: videoImage, message: '请选择视频封面图' }],
            })(
              <ImageUpload />,
            )}
          </Form.Item>
          <Form.Item label="楼盘主图" help="建议图片尺寸：750*600px，比例5:4,格式：jpg，用于楼盘详情">
            {getFieldDecorator('avatarImage', {
              rules: [{ required: true, message: '请选择项目主图' }],
            })(
              <DragableUploadImageList multiple={true} />,
            )}
          </Form.Item>
          <Form.Item label="楼盘封面图" help="建议图片尺寸：750*420px，比例16:9,格式：jpg，用于楼盘列表">
            {getFieldDecorator('listImage', {
              rules: [{ required: true, message: '请选择列表图' }],
            })(
              <ImageUpload />,
            )}
          </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="排序" help="数值越大，楼盘在小程序列表页中展示越靠前">
            {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 onChange={(e) => cityChange(e)}/>,
            )}
          </Form.Item>
          <Form.Item label="楼盘区域" >
            {getFieldDecorator('buildingArea', {
              rules: [{ required: true, message: '请输入楼盘区域' }],
            })(<AreaSelect cityId={cityId}/>)}
          </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 placeholder="不超过30个字" maxLength = "30"/>)}
          </Form.Item>
          <Form.Item label="物业费" >
            {getFieldDecorator('serviceFee')(<Input placeholder="不超过30个字" maxLength = "30"/>)}
          </Form.Item>
          <Form.Item label="装修标准" >
            {getFieldDecorator('decoration')(<Input />)}
          </Form.Item>
          <Form.Item label="开发商" >
            {getFieldDecorator('propertyDeveloper')(<Input placeholder="不超过30个字" maxLength = "30"/>)}
          </Form.Item>
          <Form.Item label="备案名" >
            {getFieldDecorator('recordName')(<Input placeholder="不超过30个字" maxLength = "30"/>)}
          </Form.Item>
          <Form.Item label="楼栋总数" >
            {getFieldDecorator('buildingNum')(<Input min={0} type="number" style={{ width: 80}}/>)}
          </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="亮点封面" help="建议尺寸：比例3:1 690*230px，用于项目详情-项目亮点封面图">
            {getFieldDecorator('highlightsCover')(
              <NewImageUpload onChange={e => console.log(e,"66")}/>,
            )}
          </Form.Item>
          <Form.Item label="亮点类型" help="说明：项目亮点必须上传封面图才会在小程序端展示">
            {getFieldDecorator('highlightsType',{
              initialValue: "rich",
            })(
            <Radio.Group onChange={e => highlightsTypeChange(e)}>
              <Radio value="rich">自定义</Radio>
              <Radio value="link">公众号链接</Radio>
            </Radio.Group>,
            )}
          </Form.Item>
          {typeState === 'link' && <Form.Item label="公众号链接" help="只能填写同一主体公众号的文章链接">
            {getFieldDecorator('highlightsLink')(<Input placeholder="请输入公众号链接" />)}
          </Form.Item>}
          {typeState === 'rich' && <Form.Item label="亮点内容" >
            {getFieldDecorator('highlights')(
              <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
