import React, { useState, useEffect } from 'react';
import { Input, Button, Radio, message, Card } from 'antd';
import apis from '../../../services/apis';
import router from 'umi/router';
import BuildSelect from '../../../components/SelectButton/BuildSelect2'
import NewsTypeSelect from '../../../components/SelectButton/NewTypeSelect'
import  { FieldTypes, createForm } from '../../../components/XForm';
import Wangedit from '../../../components/Wangedit/Wangedit'
import request from '../../../utils/request'
import ImageUploader from '../../../components/XForm/ImageUpload';
import logo from '../../../assets/logo.svg';
import yinhao from '../../../assets/yinhao.png'
import touxiang from '../../../assets/touxiang.jpg';
import poster1 from '../../../assets/poster1.png';
import poster2 from '../../../assets/poster2.png';
import xiaochengxu from '../../../assets/xiaochengxu.png'


const { TextArea } = Input;

let detailVisible = false;
let urlVisible = false;

const setExtraData = (data) => {
  detailVisible = data.newsDetailType == '1'
  urlVisible = data.newsDetailType == '0'
}

const handleFormValueChange = (props, changedValues, allValues) => {
    setExtraData(allValues)
}

const XForm = createForm({ onValuesChange: handleFormValueChange })

const cancelPage = () =>{
  router.push({
    pathname: '/news/list/NewsList',
  });
}

const Basic = (props) => {
  const { data: dynamicData } = props
  const [ changeBuildingId, setChangeBuildingIdData ] = useState('')

  const handleBuildingChange = (e) => {
    console.log(e)
    setChangeBuildingIdData(e)
  }

  const fields = [
    {
      label: '意向项目',
      name: 'buildingId',
      render: <BuildSelect onChange={(e => handleBuildingChange(e))}/>,
      value: dynamicData.buildingId,
      rules: [
        {required: true, message: '请选择所属项目'},
      ]
    },
    {
      label: '资讯列表图',
      name: 'newsImg',
      type: FieldTypes.ImageUploader,
      value: dynamicData.newsImg,
      help: '建议图片尺寸：320*240px，比例5:4,格式：jpg，用于资讯列表',
      rules: [
        {required: true, message: '请选择资讯列表'},
      ]
    },
    {
      label: '资讯标题',
      name: 'newsName',
      type: FieldTypes.Text,
      value: dynamicData.newsName,
      rules: [
        {required: true, message: '请输入资讯标题'},
      ]
    },
    {
      label: '资讯类型',
      name: 'newsTypeId',
      render: <NewsTypeSelect buildingId={changeBuildingId || dynamicData.buildingId}/>,
      value: dynamicData.newsTypeId,
      rules: [
        {required: true, message: '请选择资讯类型'},
      ]
    },
    {
      label: '资讯详情',
      name: 'newsDetailType',
      render: <Radio.Group> 
              <Radio value={1}>自定义</Radio>
              <Radio value={0}>公众号链接</Radio>
              </Radio.Group>,
      value: dynamicData.newsDetailType - 0,
      rules: [
        {required: true, message: '请选择资讯类型'},
      ]
    },
    {
      label: '详情内容',
      name: 'newsDetail',
      render: <Wangedit />,
      hidden: () => !detailVisible,
      value: dynamicData.newsDetail,
      rules: [
        {required: true, message: '请输入详情内容'},
      ]
    },
    {
      label: '公众号链接',
      name: 'newsDetail',
      type: FieldTypes.Text,
      hidden: () => !urlVisible,
      value: dynamicData.newsDetail,
      help: "只能填写同一主体公众号的文章链接",
      rules: [
        {required: true, message: '请输入公众号链接'},
      ]
    },
  ]

  const handleSubmit = val => { 
    console.log(dynamicData,'12312345')
    let {...submitValue} = val
    
    if(dynamicData.newsId){
      submitValue.newsId = dynamicData.newsId
      request({ ...apis.news.put, urlData: {id: dynamicData.newsId}, data: { ...submitValue },}).then((data) => {
        // cancelPage();
        message.info("保存成功")
        console.log(data,'data1')
      }).catch((err) => {
        message.info(err.msg || err.message)
      })
    }else{
      request({ ...apis.news.post, data: { ...submitValue },}).then((data) => {
        // cancelPage();
        message.info("保存成功")
        router.push({
          pathname: '/news/list/editNewsList',
          query: {
            newsId:data.newsId
          },
        });
        console.log(data,'data2')
      }).catch((err) => {
        message.info(err.msg || err.message)
      })
    }
  }

  const cancelPage = () =>{
    router.go(-1);
  }
  
  return <XForm onSubmit={handleSubmit} onCancel={cancelPage}  fields={fields}></XForm>
}

/**
 *
 *
 * @param {*} props
 * @returns
 */
 const Edit = (props) => {
  const [ tab, changeTab ] = useState('basic')
  const newsId = props.location.query.newsId
  const [ dynamicData, setDynamicData ] = useState({})

    useEffect(() => {
      if(newsId){
        getDynamicData(newsId);
      }
    },[newsId])

  // 查询列表
  const getDynamicData = (newsId) => {
    request({ ...apis.news.get, urlData: { id: newsId },}).then((data) => {
      setDynamicData(data)
      setExtraData(data)
      // detailVisible = data.newsDetailType == '1'
      // urlVisible = data.newsDetailType == '0'
    }).catch((err) => {
      console.log(err)
      message.info(err.msg || err.message)
    })
    }

  const Poster = (props) => {
    const [inputValue, changeInput] = useState('')
    const [textAreaValue, changeTextArea] = useState('')
    const [imgValue, changeImg] = useState('')
    const [posterId, setPosterId] = useState('')

    if(newsId){
      useEffect(() => {
        request({ ...apis.activity.poster, params: {targetId: newsId,targetType: 'news'} }).then((data) => {
          console.log(data,"2222")
          if(data.length > 0){
            setPosterId(data[0].posterId)
            changeImg(data[0].posterImg)
            changeTextArea(data[0].posterDescription)
            changeInput(data[0].posterTitle)
          }
        }).catch((err) => {
          message.info(err.msg || err.message)
        })
        getMiniappName()
      }, [])
    }else{
      getMiniappName()
    }

    // 获取小程序名称
  const [miniappName, setMiniappName] = useState('')
  function getMiniappName() {

    request({ ...apis.building.getMiniappName }).then(res => {
    
      setMiniappName(res)
     
    })
  }
    const submitPoster  = () => {
       if(newsId){
        if(posterId){
          request({ ...apis.activity.updatePoster, urlData: {id: posterId}, data: {targetId: newsId,targetType: 'news',posterImg: imgValue,posterTitle: inputValue,posterDescription: textAreaValue},}).then((data) => {
            message.info("保存成功")
          }).catch((err) => {
            message.info(err.msg || err.message)
          })
         }else{
          request({ ...apis.activity.addPoster, data: {targetId: newsId,targetType: 'news',posterImg: imgValue,posterTitle: inputValue,posterDescription: textAreaValue},}).then((data) => {
            setPosterId(data.posterId)
            message.info("保存成功")
          }).catch((err) => {
            message.info(err.msg || err.message)
          })
         }
       }else{
        message.warn("请先保存基本信息数据")
       }
    }

    return <div>
      <div style={{ display: 'flex' }}>
        <div style={{ width: '420px', height: '900px', display: 'inline-block', marginTop: '30px' }}>
          <div style={{ width: '375px', height: '700px', backgroundColor: '#fff', boxShadow: '0px 0px 16px 6px rgba(0,0,0,0.15)', position: 'relative', margin: '0 auto' }}>
            <img style={{ width: '100%', height: '300px' }} src={imgValue ? imgValue : poster1} alt="" />
            <div style={{ display: 'flex', alignItems: 'center', marginTop: '-24px' }}>
              <img style={{ width: '70px', height: '70px', border: '4px solid #fff', borderRadius: '35px', marginLeft: '16px' }} src={touxiang} alt="" />
              <span style={{ color: '#222', fontWeight: '600', margin: '24px 10px 0 14px', fontSize: '17px' }}>喵喵</span>
              <span style={{ color: '#999', marginTop: '25px', fontSize: '17px' }}>邀您阅读</span>
              <span style={{ color: '#999', margin: '25px 0 0 60px', fontSize: '17px' }}>2019.09.21</span>
            </div>
            <p style={{
              margin: '10px 20px', fontSize: '20px', color: '#222', fontWeight: '600',
              display: '-webkit-box', lineClamp: '3', height: '60px',
              WebkitLineClamp: '2',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis'
            }}>{inputValue ? inputValue : '海报标题'}</p>

            <img src={yinhao} style={{ width: '30px', marginLeft: '20px' }} alt="" />
            <p style={{
              margin: '16px 20px 28px 20px', fontSize: '17px', color: '#999',
              display: '-webkit-box', lineClamp: '3', height: '72px',
              WebkitLineClamp: '3',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis'
            }}>{textAreaValue ? textAreaValue : '海报描述'}</p>
               <div style={{ backgroundColor: '#f1f1f1', padding: '22px 30px', boxShadow: '0px 6px 12px -4px #dcdcdc',position:'relative' }}>
            <p style={{margin:'0',fontSize:'18px',color:'#888'}}>长按识别小程序码</p>
            <p style={{margin:'0',fontSize:'18px',color:'#888'}}>进入资讯查看详情</p>
            <img style={{ width: '80px',position: 'absolute',right:'30px',top:'10px' }} src={xiaochengxu} alt="" />
          </div>
      
          </div>
          <p style={{ textAlign: 'center', fontSize: '19px', color: '#666', marginTop: '30px' }}>海报模板</p>
        </div>

        <div >
          <div style={{ display: 'flex', width: '100%', margin: '60px 0' }}>
            <p style={{ minWidth: '200px', color: '#222', textAlign: 'right', margin: '0 30px 0 0' }}>资讯海报图</p>
            <ImageUploader value={imgValue} onChange={e => changeImg(e)} />
          </div>
          <p style={{ fontSize: '0.5vw', color: '#A9A9A9', marginLeft: '230px', marginBottom: '30px'}}>建议图片尺寸：640*670px，比例64:67,格式：jpg，用于资讯海报</p>
          <div style={{ display: 'flex', alignItems: 'center', width: '100%', marginBottom: '60px' }}>
            <p style={{ minWidth: '200px', color: '#222', textAlign: 'right', margin: '0 30px 0 0' }}>海报标题</p>
            <Input style={{ width: '20vw' }} value={inputValue} placeholder="请输入海报标题" onChange={e => changeInput(e.target.value)} />
          </div>
          <div style={{ display: 'flex', margin: '10px 0 40px 0', width: '100%' }}>
            <p style={{ minWidth: '200px', color: '#222', textAlign: 'right', margin: '0 30px 0 0' }}>海报描述</p>
            <TextArea rows={5} maxLength={1024} value={textAreaValue} onChange={e => changeTextArea(e.target.value)} />
          </div>

        </div>
      </div>
      <Button type="primary" onClick={submitPoster} style={{ margin: '40px 40px 40px 30vw' }}> 确定</Button>
      <Button onClick={cancelPage}>取消</Button>
    </div>

  }
 
  const Share = (props) => {
    const [inputValue, changeInput] = useState('')
    const [imgValue, changeImg] = useState('')
    const [shareContentId, setShareContentId] = useState('')
    
    if(newsId){
      useEffect(() => {
        request({ ...apis.activity.shareContent, params: {targetId: newsId,targetType: 'news'},}).then((data) => {
          console.log(data,"2222")
          if(data.length > 0){
            setShareContentId(data[0].shareContentId)
            changeImg(data[0].shareContentImg)
            changeInput(data[0].shareContentTitle)
          }
        }).catch((err) => {
          message.info(err.msg || err.message)
        })
      }, [])
    }

    const submitShare = () => {
      if(newsId){
        if(shareContentId){
          request({ ...apis.activity.updateShareContent, urlData: {id: shareContentId},data: {targetId: newsId,shareContentType: 'news',shareContentImg: imgValue,shareContentTitle: inputValue},}).then((data) => {
            message.info("保存成功")
          }).catch((err) => {
            message.info(err.msg || err.message)
          })
         }else{
          request({ ...apis.activity.addShareContent, data: {targetId: newsId,shareContentType: 'news',shareContentImg: imgValue,shareContentTitle: inputValue},}).then((data) => {
            setShareContentId(data.shareContentId)
            message.info("保存成功")
          }).catch((err) => {
            message.info(err.msg || err.message)
          })
         }
       }else{
        message.warn("请先保存基本信息数据")
       }
    }

    return <div style={{ padding: '20px' }}>
      <div style={{ display: 'flex', margin: '10px 0 40px 0', width: '100%' }}>
        <p style={{ minWidth: '200px', color: '#222', textAlign: 'right', margin: '0 30px 0 0' }}>分享模板</p>
        <div>
          <p style={{ display: 'flex', alignItems: 'center', fontSize: '14px', color: '#999', margin: '0', lineHeight: '0' }}><img src={logo} style={{ width: '22px', marginRight: '10px' }} />橙蕉互动</p>
          <p style={{ fontSize: '16px', color: '#222', fontWeight: '600', margin: '0' }}>{inputValue ? inputValue : '置业V客厅 精准获客平台'}</p>
          <img style={{ width: '200px', height: '160px' }} src={imgValue ? imgValue : poster2} alt="" />
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
        <p style={{ minWidth: '200px', color: '#222', textAlign: 'right', margin: '0 30px 0 0' }}>分享标题</p>
        <Input placeholder="请输入分享标题" value={inputValue} onChange={e => changeInput(e.target.value)} />
      </div>
      <div style={{ display: 'flex', width: '100%', marginTop: '40px' }}>
        <p style={{ minWidth: '200px', color: '#222', textAlign: 'right', margin: '0 30px 0 0' }}>资讯分享好友图</p>
        <ImageUploader value={imgValue} onChange={e => changeImg(e)} />
      </div>
      <p style={{ fontSize: '0.5vw', color: '#A9A9A9', marginLeft: '230px', marginTop: '20px' }}>建议图片尺寸：750*600px，比例5:4,格式：jpg，用于资讯分享好友</p>
      <Button type="primary" htmlType="submit" onClick={submitShare} style={{ margin: '40px 40px 40px 220px' }}> 确定</Button>
      <Button onClick={cancelPage}>取消</Button>
    </div>
  }

  return (
    <Card>
      <div>
        <Radio.Group value={tab} buttonStyle="solid" onChange={e => changeTab(e.target.value)}>
          <Radio.Button value="basic">基本信息</Radio.Button>
          <Radio.Button value="poster">海报图片</Radio.Button>
          <Radio.Button value="share">分享设置</Radio.Button>
        </Radio.Group>
      </div>
      <div>
        { tab === 'basic' && <Basic data={dynamicData} /> }
        { tab === 'poster' && <Poster /> }
        { tab === 'share' && <Share /> }
      </div>
  
    </Card>
  );
 }



export default Edit
