import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, Tabs, Radio, DatePicker, message, Upload } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import styles from '../../style/GoodsList.less';
import apis from '../../../services/apis';
import moment from 'moment';
import router from 'umi/router';
import BuildSelect from '../../../components/SelectButton/BuildSelect2'
import XForm, { FieldTypes } from '../../../components/XForm';
import Wangedit from '../../../components/Wangedit/Wangedit'
import request from '../../../utils/request'
import yinhao from '../../../assets/yinhao.png'
import ImageUploader from '../../../components/XForm/ImageUpload';
import logo from '../../../assets/logo.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'
import Prompt from 'umi/prompt';

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const { TextArea } = Input;

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


const Basic = props => {
  const { dynamicData, disable, activityStatus, scoreData, groupActivityId } = props;

  const fields = [
    {
      label: '选择项目',
      name: 'buildingId',
      render: <BuildSelect disabled={disable} />,
      value: dynamicData.buildingId,
      rules: [
        { required: true, message: '请选择项目' },
      ],
    },
    {
      label: '活动标题',
      name: 'activityName',
      type: FieldTypes.Text,
      value: dynamicData.activityName,
      rules: [
        { required: true, message: '请输入活动标题' },
      ]
    },
    {
      label: '拼团详情主图',
      name: 'mainImg',
      type: FieldTypes.ImageUploader,
      value: dynamicData.mainImg,
      rules: [
        { required: true, message: '请输入拼团详情主图' },
      ],
      help: '建议图片尺寸：750*600px，比例5:4,格式：jpg，用于：拼团活动详情',
    },
    {
      label: '拼团封面图1',
      name: 'listImg',
      type: FieldTypes.ImageUploader,
      value: dynamicData.listImg,
      rules: [
        { required: true, message: '请输入拼团封面图1' },
      ],
      help: '建议图片尺寸：750*420px，比例16:9,格式：jpg，用于：活动列表/首页推荐',
    },
    {
      label: '拼团封面图2',
      name: 'bannerListImg',
      type: FieldTypes.ImageUploader,
      value: dynamicData.bannerListImg,
      rules: [
        { required: true, message: '请输入拼团封面图2' },
      ],
      help: '建议图片尺寸：750*250px，比例3:1,格式：jpg，用于：项目详情页',
    },
    {
      label: '活动时间',
      name: 'activityTime',
      type: FieldTypes.RangePicker,
      value: dynamicData.startTime != null ? [moment(dynamicData.startTime, 'YYYY-MM-DD HH:mm'), moment(dynamicData.endTime, 'YYYY-MM-DD HH:mm')] : null,
      props: { showTime: { format: 'HH:mm' } },
      rules: [
        { required: true, message: '请选择活动时间' },
      ],
    },
    {
      label: '成团人数',
      name: 'groupBuyPeople',
      type: FieldTypes.Text,
      value: dynamicData.groupBuyPeople,
      props: { disabled: activityStatus === 0 },
      help: '注：成团所需人数',
      rules: [
        { required: true, message: '请输入成团人数' },
      ]
    },
    {
      label: '所需积分',
      name: 'integral',
      type: FieldTypes.Text,
      value: dynamicData.integral,
      props: { disabled: activityStatus === 0 },
      help: `注：用户平均积分${scoreData.averageScore}`,
      rules: [
        { required: true, message: '请输入所需积分' },
      ]
    },
    {
      label: '活动说明',
      name: 'descImg',
      type: FieldTypes.ImageUploader,
      value: dynamicData.descImg,
      rules: [
        { required: true, message: '请输入活动说明' },
      ],
      help: '建议宽度：750px，高度不限，格式：jpg，用于活动详情',
    },
    {
      label: '权重',
      name: 'heavy',
      type: FieldTypes.Number,
      render: <Input type="number" style={{ width: 80 }} />,
      value: dynamicData.heavy,
      rules: [
        { required: true, message: '请输入权重' },
      ],
      help: '数字越大越靠前',
    },
  ]

  function compareDate(dateTime1, dateTime2) {
    return new Date(dateTime1) > new Date(dateTime2);
  }

  const handleSubmit = val => {
    const { activityTime, signupTime, ...submitValue } = val

    const [startTime, endTime] = activityTime
    submitValue.startTime = moment(startTime).format('YYYY-MM-DD HH:mm');
    submitValue.endTime = moment(endTime).format('YYYY-MM-DD HH:mm');

    if (groupActivityId) {
      const nowDate = new Date()
      if (!compareDate(nowDate, startTime)) {
        message.info('修改后的开始时间不得大于当前时间（会存在已经成功助力或者发起助力的用户）')
        return
      }
      submitValue.groupActivityId = groupActivityId
      request({ ...apis.groupActivity.update, data: submitValue }).then(data => {
        message.info('保存成功')
        // cancelPage()
      }).catch(() => {
        // message.info(err.msg || err.message)
      })
    } else {
      request({ ...apis.groupActivity.add, data: submitValue }).then(data => {
        router.push({
          pathname: '/activity/groupActivity/editGroupActivity',
          query: {
            groupActivityId: data,
          },
        });
        message.info("保存成功")
        // cancelPage()
      }).catch(() => {
        // message.info(err.msg || err.message)
      })
    }
  }

  return <XForm onSubmit={handleSubmit} onCancel={cancelPage} fields={fields}></XForm>
}

const Poster = props => {
  const { groupActivityId } = props;
  const [inputValue, changeInput] = useState('')
  const [textAreaValue, changeTextArea] = useState('')
  const [imgValue, changeImg] = useState('')
  const [posterId, setPosterId] = useState('')
  // const [miniappName, setMiniappName] = useState('')

  useEffect(() => {
    if (groupActivityId) {
      request({ ...apis.activity.poster, params: { targetId: groupActivityId, targetType: 'groupActivity' } }).then(data => {
        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()
  }, [])

  // // 获取小程序名称
  // function getMiniappName() {
  //   request({ ...apis.building.getMiniappName }).then(res => {
  //     setMiniappName(res)
  //   })
  // }

  const submitPoster = () => {
    if (groupActivityId) {
      if (posterId) {
        request({ ...apis.activity.updatePoster, urlData: { id: posterId }, data: { targetId: groupActivityId, targetType: 'activity', 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: groupActivityId, targetType: 'groupActivity', 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 || 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 || '海报标题'}</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 || '海报描述'}</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' }}>建议图片尺寸：750*600，比例5:4,格式：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 => {
  console.log(props, 'props')
  const { groupActivityId } = props
  const [inputValue, changeInput] = useState('')
  const [imgValue, changeImg] = useState('')
  const [shareContentId, setShareContentId] = useState('')

  useEffect(() => {
    if (groupActivityId) {
      request({ ...apis.activity.shareContent, params: { targetId: groupActivityId, targetType: 'groupActivity' } }).then(data => {
        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 = () => {
    console.log(groupActivityId)
    if (groupActivityId) {
      if (shareContentId) {
        request({ ...apis.activity.updateShareContent, urlData: { id: shareContentId }, data: { targetId: groupActivityId, shareContentType: 'groupActivity', shareContentImg: imgValue, shareContentTitle: inputValue } }).then(data => {
          message.info('保存成功')
        }).catch(err => {
          message.info(err.msg || err.message)
        })
      } else {
        request({ ...apis.activity.addShareContent, data: { targetId: groupActivityId, shareContentType: 'groupActivity', 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 || ''}</p>
        <img style={{ width: '200px', height: '160px' }} src={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', marginBottom: '30px' }}>建议图片尺寸：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>
}


/**
 *
 *
 * @param {*} props
 * @returns
 */
const Edit = props => {
  const [tab, changeTab] = useState('basic')
  // 判断是否展示助力次数的输入框
  const { groupActivityId } = props.location.query
  const [dynamicData, setDynamicData] = useState({ isEnlist: 1 })
  const [scoreData, setScoreData] = useState({})
  const [activityStatus, setActivityStatus] = useState({})
  const [disable, setDisable] = useState(false)

  // 详情
  const getDynamicData = id => {
    request({ ...apis.groupActivity.details, urlData: { id } }).then(data => {
      setDynamicData(data)
      setActivityStatus(data.activityStatus)
      setDisable(data.activityStatus === 0)
    })
  }

  useEffect(() => {
    request(apis.groupActivity.avgScore).then(data => {
      setScoreData(data);
    })
  }, [])

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

  // const radioOnChange = e => {
  //   setDynamicData({ ...dynamicData, isEnlist: e.target.value })
  // }

  return (
    <div>
      <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 dynamicData={dynamicData} disable={disable} activityStatus={activityStatus} scoreData={scoreData} groupActivityId={groupActivityId} />}
        {tab === 'poster' && <Poster groupActivityId={groupActivityId} />}
        {tab === 'share' && <Share groupActivityId={groupActivityId} />}
      </div>
      <Prompt message={location =>
        (location.pathname.startsWith('/activity/groupActivity')
          ? true
          : localStorage.removeItem('groupActivePageParams'))} />
    </div>
  );
}
export default Edit
