import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, Card, Radio, DatePicker, message, Upload } from 'antd';

import apis from '@/services/apis';
import moment from 'moment';
import router from 'umi/router';
import BuildSelect from '@/components/SelectButton/BuildSelect';
import request from '@/utils/request';
import yinhao from '@/assets/yinhao.png';
import logo from '@/assets/logo.svg';
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 AuthButton from '@/components/AuthButton';
import { getImgURL } from '@/utils/image';
import Share from '@/components/Share';
import Poster from '@/components/Poster';

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

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const cancelPage = () => {
  router.go('-1');
};

const getSignList = dynamicId => {
  router.push({
    pathname: '/activity/lookHouseActivity/registrationRecord',
    query: {
      dynamicId,
    },
  });
};

const newQrcode = row => {
  const x = new XMLHttpRequest();
  const resourceUrl = row.qrCode;
  x.open('GET', resourceUrl, true);
  x.responseType = 'blob';
  x.onload = function(e) {
    const url = window.URL.createObjectURL(x.response);
    const a = document.createElement('a');
    a.href = url;
    a.style.display = 'none';
    a.download = '活动二维码.png';
    a.click();
  };
  x.send();
};

const BasicForm = props => {
  const detailData = props.detailData || {};

  const radioOnChange = e => {
    // setIsEnlist(e.target.value)
  };

  const { dynamicId } = props;
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        const { activityTime, signupTime } = values;
        const [startDate, endDate] = activityTime;
        values.startDate = moment(startDate).format('YYYY-MM-DD HH:mm');
        values.endDate = moment(endDate).format('YYYY-MM-DD HH:mm');
        if (signupTime) {
          const [enlistStart, enlistEnd] = signupTime;
          values.enlistStart = moment(enlistStart).format('YYYY-MM-DD HH:mm');
          values.enlistEnd = moment(enlistEnd).format('YYYY-MM-DD HH:mm');
        }
        console.log('submit data --->', values);
        if (dynamicId) {
          values.dynamicId = dynamicId;
          request({ ...apis.activity.update, data: values })
            .then(data => {
              message.info('保存成功');
              // router.go(-1)
            })
            .catch(err => {
              message.info(err.msg || err.message);
            });
        } else {
          request({ ...apis.activity.add, data: { ...values } })
            .then(data => {
              message.info('保存成功');
              router.push({
                pathname: '/activity/editActivity',
                query: {
                  dynamicId: data.dynamicId,
                },
              });
              // router.go(-1)
            })
            .catch(err => {
              message.info(err.msg || err.message);
            });
        }
      }
    });
  };

  const { getFieldDecorator } = props.form;
  return (
    <>
      <Form {...formItemLayout} onSubmit={handleSubmit}>
        <Form.Item label="所属项目">
          {getFieldDecorator('buildingId', {
            initialValue: detailData.buildingId,
            rules: [
              {
                required: true,
                message: '请选择所属项目',
              },
            ],
          })(<BuildSelect disabled />)}
        </Form.Item>
        <Form.Item label="活动详情主图">
          <img src={getImgURL(detailData.imgUrl)} height="300px" width="375px" />
        </Form.Item>
        <Form.Item label="活动标题">
          <span>{detailData.title}</span>
        </Form.Item>
        {/* <Form.Item label="副标题">
          <span>{detailData.halfTitle}</span>
        </Form.Item> */}
        <Form.Item label="活动时间">
          <span>{`${moment(detailData.startDate).format('YYYY-MM-DD HH:mm')} —— ${moment(
            detailData.endDate,
          ).format('YYYY-MM-DD HH:mm')}`}</span>
        </Form.Item>
        <Form.Item label="活动地点">
          <span>{detailData.address}</span>
        </Form.Item>
        <Form.Item label="活动人数">
          <span>{detailData.personNum}</span>
        </Form.Item>
        {/* <Form.Item label="阅读量">
          <span>{detailData.pvNum}</span>
        </Form.Item>
        <Form.Item label="转发量">
          <span>{detailData.shareNum}</span>
        </Form.Item>
        <Form.Item label="收藏数">
          <span>{detailData.saveNum}</span>
        </Form.Item>
        <Form.Item label="最大报名人数">
          <span>{detailData.maxEnlistByPerson}</span>
        </Form.Item> */}
        <Form.Item label="活动详情">
          <div
            style={{ maxHeight: '500px', overflowY: 'auto' }}
            dangerouslySetInnerHTML={{ __html: detailData.desc }}
          ></div>
        </Form.Item>
        <Form.Item label="报名时间">
          <span>{`${moment(detailData.enlistStart).format('YYYY-MM-DD HH:mm')} —— ${moment(
            detailData.enlistEnd,
          ).format('YYYY-MM-DD HH:mm')}`}</span>
        </Form.Item>
        <Form.Item label="权重">
          <span>{detailData.heavy}</span>
        </Form.Item>
      </Form>
      <div style={{ textAlign: 'center' }}>
        <AuthButton name="admin.SignList.get" noRight={null}>
          {(detailData.activityStatus === 0 || detailData.activityStatus === 2) && (
            <span
              style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }}
              onClick={getSignList.bind(this, detailData.dynamicId)}
            >
              <Button>报名记录</Button>
            </span>
          )}
        </AuthButton>
        <AuthButton name="admin.dymic.qrcode" noRight={null}>
          {(detailData.activityStatus === 0 || detailData.activityStatus === 2) && (
            <span
              style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }}
              onClick={newQrcode.bind(this, detailData)}
            >
              {<Button>下载二维码</Button>}
            </span>
          )}
        </AuthButton>
        <Button onClick={() => cancelPage()}>取消</Button>
      </div>
    </>
  );
};

const Basic = Form.create({ name: 'BasicForm' })(BasicForm);

/**
 *
 *
 * @param {*} props
 * @returns
 */
const Edit = props => {
  const [tab, changeTab] = useState('basic');
  const { dynamicId } = props.location.query;
  const [detailData, setDetailData] = useState(false);

  const getDynamicData = dynamicId => {
    request({ ...apis.activity.details, params: { dynamicId } }).then(data => {
      console.log(data);
      data.activityTime = [moment(data.startDate), moment(data.endDate)];
      data.signupTime = [moment(data.enlistStart), moment(data.enlistEnd)];

      setDetailData(data);
    });
  };

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

  const target = { id: dynamicId, type: 'activity' };
  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 dynamicId={dynamicId} detailData={detailData} />}

        {tab === 'poster' && <Poster target={target} />}
        {tab === 'share' && <Share target={target} />}
      </div>
      {/* <div style={{ textAlign: 'center' }}>
        <AuthButton name="admin.SignList.get" noRight={null}>
          {(detailData.activityStatus === 0 || detailData.activityStatus === 2) && (
            <span
              style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }}
              onClick={getSignList.bind(this, detailData.dynamicId)}
            >
              <Button>报名记录</Button>
            </span>
          )}
        </AuthButton>
        <AuthButton name="admin.dymic.qrcode" noRight={null}>
          {(detailData.activityStatus === 0 || detailData.activityStatus === 2) && (
            <span
              style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }}
              onClick={newQrcode.bind(this, detailData)}
            >
              {<Button>下载二维码</Button>}
            </span>
          )}
        </AuthButton>
        <Button onClick={() => cancelPage()}>取消</Button>
      </div> */}
    </Card>
  );
};

export default Edit;
