import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Select, message, Table, Pagination, Typography, Modal, DatePicker, Radio } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import Prompt from 'umi/prompt';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import Navigate from '@/components/Navigate';
import styles from '../../style/GoodsList.less';
import apis from '../../../services/apis';
import request from '../../../utils/request';
import AuthButton from '../../../components/AuthButton';
import ImageUploader from '../../../components/XForm/ImageUpload';
import BuildSelect from '../../../components/SelectButton/BuildSelect2'

const toEditList = row => () => {
  router.push({
    pathname: '/activity/drainage/Detail',
    query: {
      drainageId: row.drainageId,
      name: row.name,
    },
  });
}

const toDataReacord = row => () => {
  router.push({
    pathname: '/activity/drainage/drainageRecord',
    query: {
      id: row.drainageId,
    },
  });
}
const header = props => {
  // const [data, setData] = useState({ data: [] })
  const [datas, setDatas] = useState([])//表格数据
  const [date, setDate] = useState({})
  const [formsdate, setFormsDate] = useState({})
  //   const [page, changePage] = useState({})
  useEffect(() => {
    if (localStorage.getItem('drainageActivePageParams')) {
      props.form.setFieldsValue(JSON.parse(localStorage.getItem('drainageActivePageParams')));
      // const { getFieldDecorator } = JSON.parse(localStorage.getItem("pageParams"))

      gettaDrainage(JSON.parse(localStorage.getItem('drainageActivePageParams')))
    } else {
      localStorage.setItem('drainageActivePageParams', JSON.stringify({ pageNum: 1, pageSize: 10 }));
      gettaDrainage({ pageNum: 1, pageSize: 10 });
    }


    setDate({
      ModalText: 'Content of the modal',
      visible: false,
      confirmLoading: false,
    })

  }, [])

  function gettaDrainage(params) {
    request({ ...apis.activity.taDrainage, params }).then(data => {
      setDatas(data)
      console.log(data.records, '_213_')
    }).catch(err => {
      console.log(err)
      message.info(err.msg || err.message)
    })
  }

  const deleteDrainage = (drainageIid) => () => {
    Modal.confirm({
      title: '确认删除该引流？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        request({ ...apis.activity.deletetaDrainage, urlData: { id: drainageIid }, }).then((data) => {
          message.info('操作成功！')
          gettaDrainage(JSON.parse(localStorage.getItem("drainageActivePageParams")))
        }).catch((err) => {
          console.log('111111', err)
          // message.info(err.msg || err.message)
        })
      }
    });
  }

  const toDrainageDetail = (drainageId) => () => {
    router.push({
      pathname: '/activity/drainage/DetailDrainage',
      query: {
        drainageId
      },
    });
  }

  const newQrcode = row => {
    const x = new XMLHttpRequest();
    const resourceUrl = row.qrCode
    console.log(resourceUrl);
    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 = 'H5二维码.png';
      a.click();
    }
    x.send();
  }

  const exchangeDrainage = drainage => () => {
    if (drainage.status === 1) {
      if (drainage.isMiniapp) {
        Modal.confirm({
          title: '下架后当前H5活动关联的小程序端开屏图、banner图等也会自动下架。',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            request({ ...apis.activity.exchangeDrainage, urlData: { id: drainage.drainageId }, data: drainage }).then((data) => {
              message.info('操作成功！')
              gettaDrainage(JSON.parse(localStorage.getItem("drainageActivePageParams")))
            }).catch((err) => {
              console.log(err)
              message.info(err.msg || err.message)
            })
          }
        });
      } else {
        request({ ...apis.activity.exchangeDrainage, urlData: { id: drainage.drainageId }, data: drainage }).then((data) => {
          message.info('H5活动已下架！')
          gettaDrainage(JSON.parse(localStorage.getItem("drainageActivePageParams")))
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      }

    } else {
      request({ ...apis.activity.exchangeDrainage, urlData: { id: drainage.drainageId }, data: drainage }).then((data) => {
        message.info('H5活动已上架！')
        gettaDrainage(JSON.parse(localStorage.getItem("drainageActivePageParams")))
      }).catch((err) => {
        console.log(err)
        message.info(err.msg || err.message)
      })
    }

  }

  const columns = [
    {
      title: 'H5项目编号',
      dataIndex: 'drainageId',
      key: 'drainageId',
      align: 'center',
    },
    {
      title: '是否投放小程序',
      dataIndex: 'isMiniapp',
      key: 'isMiniapp',
      align: 'cenxter',
      render: (isMiniapp) => <span>{isMiniapp ? '是' : '否'}</span>,
    },
    {
      title: 'H5项目名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      render: (text, datas) => <Navigate onClick={toDrainageDetail(datas.drainageId)}><Typography.Text ellipsis>{datas.name}</Typography.Text></Navigate>,
    },
    {
      title: '链接地址',
      dataIndex: 'h5Address',
      key: 'h5Address',
      align: 'center',
      // render: (text, datas) => <div style={ { color: '#66B3FF' } } onClick= {() => addshowModal(datas)} >{ datas.name }</div>, 
    },
    {
      title: '上架状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (status) => <span>{status === 1 ? '已上架' : '已下架'}</span>,
    },
    {
      title: '新建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: (x, row) => (
        <>
          <span>{row.createDate && moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}</span>
        </>
      ),
    },
    {
      title: '自动下架时间',
      dataIndex: 'endDate',
      key: 'endDate',
      align: 'center',
      render: (x, row) => (
        <>
          <span>{row.endDate && moment(row.endDate).format('YYYY-MM-DD HH:mm:ss')}</span>
        </>
      ),
    },
    // {
    //   title: '参与数',
    //   dataIndex: 'enlistNum',
    //   key: 'enlistNum',
    //   align: 'center',
    //   // render:
    // },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 300,
      render: withActions((text, datas) => [
        <AuthButton name="admin.taDrainage.put" noRight={null}>
          <EditIcon type="edit" text="编辑" onClick={() => addshowModal(datas)} />
        </AuthButton>,

        <EditIcon type="look" text="查看详情" onClick={toDrainageDetail(datas.drainageId)} />,

        <AuthButton name="admin.taDrainage.id.delete" noRight={null}>
          <EditIcon type="delete" text="删除" onClick={deleteDrainage(datas.drainageId)} />
        </AuthButton >,

        <AuthButton name="admin.taDrainage.publish" noRight={null}>
          <EditIcon type={datas.status === 1 ? 'down' : 'up'} text={datas.status === 1 ? '下架' : '上架'} onClick={exchangeDrainage(datas)} />
        </AuthButton>,

        <AuthButton name="admin.taDrainage.data" noRight={null}>
          <EditIcon text="数据" type="data" onClick={toEditList(datas)} />
        </AuthButton>,

        <AuthButton name="admin.drainageActivity.dataRecord" noRight={null}>
          <EditIcon type="record" text="数据记录" onClick={toDataReacord(datas)} />
        </AuthButton>,

        <AuthButton name="admin.taDrainage.id.delete" noRight={null}>
          <EditIcon text="下载二维码" type="download" onClick={newQrcode.bind(this, datas)} />
        </AuthButton >,
      ]),
    },
  ];
  const Forms = props => {
    const { formsDate } = props
    // useEffect(() => {
    //   if (formsDate) {
    //     props.form.setFieldsValue({ ...formsDate, endDate: formsdate.endDate ? moment(formsdate.endDate, 'YYYY-MM-DD HH:mm') : null })
    //   }
    // }, [formsDate])

    const [hiddenStatus, setHiddenStatus] = useState(formsdate.isMiniapp)

    const handleSubmit = e => {
      e.preventDefault();
      props.form.validateFields((err, values) => {
        if (!err) {
          values.endDate = moment(values.endDate._d).format('YYYY-MM-DD HH:mm:ss')
          if (formsDate.drainageId) {
            // { ...apis.activity.deletetaDrainage,urlData: { id: drainageIid }, }
            request({ ...apis.activity.updatetaDrainage, urlData: { id: formsDate.drainageId }, data: values }).then(data => {
              message.info('操作成功！')
              gettaDrainage(JSON.parse(localStorage.getItem('drainageActivePageParams')))
              setDate({
                visible: false,
              });
            }).catch(err => {
              console.log('111111', err)
              message.info(err.msg || err.message)
            })
          } else {
            request({ ...apis.activity.addtaDrainage, data: values }).then(data => {
              message.info('操作成功')
              gettaDrainage(JSON.parse(localStorage.getItem('drainageActivePageParams')))
              setDate({
                visible: false,
              });
            }).catch(err => {
              message.error(err.msg || err.message)
            })
          }
        }
      });
    }

    const handleCancel = val => {
      setDate({
        visible: false,
      });
    }

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };

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

    const changeMiniapp = e => {
      if (e.target.value == 1) {
        setHiddenStatus(true)
      } else {
        setHiddenStatus(false)
      }
    }

    const { getFieldDecorator } = props.form;
    {/* <XForm onSubmit={handleSubmit} onCancel={handleCancel} fields={fields} ></XForm> */ }

    return <Form {...formItemLayout} onSubmit={handleSubmit}>
      <span style={{ color: '#ef273a' }}>发布后请到资源位管理中关联资源位图，否则客户看不到</span>
      <Form.Item label="是否投放小程序端" help='选择是后,该活动可投放至小程序的轮播位以及开屏广告'>
        {getFieldDecorator('isMiniapp', {
          initialValue: formsDate.isMiniapp ? 1 : 0,
          rules: [
            { required: true, message: '请选择是否投放小程序' },
          ],
        })(
          <Radio.Group onChange={changeMiniapp} disabled={!!formsDate.activityId}>
            <Radio value={1}>是</Radio>
            <Radio value={0}>否</Radio>
          </Radio.Group>
        )}
      </Form.Item>
      <Form.Item label="H5项目名称">
        {getFieldDecorator('name', {
          initialValue: formsDate.name,
          rules: [
            { required: true, message: '请输入H5项目名称' },
          ],
        })(
          <Input
            placeholder="请输入H5项目名称"
          />,
        )}
      </Form.Item>
      {hiddenStatus && (<Form.Item label="选择项目">
        {getFieldDecorator('buildingId', { initialValue: formsDate.buildingId })(
          <BuildSelect />,
        )}
      </Form.Item>)}
      <Form.Item label="下架时间">
        {getFieldDecorator('endDate', {
          initialValue: formsdate.endDate ? moment(formsdate.endDate, 'YYYY-MM-DD HH:mm:ss') : null,
          rules: [
            { required: true, message: '请输入下架时间' },
          ]
        })(
          <DatePicker
            showTime={{ format: 'HH:mm:ss' }}
          />,
        )}
      </Form.Item>
      {hiddenStatus && (<Form.Item label="活动链接地址">
        {getFieldDecorator('h5Address', {
          initialValue: formsDate.h5Address,
          rules: [
            { required: true, message: '请输入H5活动链接地址' },
          ]
        })(
          <Input
            placeholder="请输入H5活动链接地址"
            disabled={formsDate.isMiniapp}
          />,
        )}
      </Form.Item>)}
      {hiddenStatus && (<Form.Item label="分享设置" help="建议图片尺寸：750*600px，比例5:4,格式：jpg">
        {getFieldDecorator('shareImg', {
          initialValue: formsDate.shareImg,
          rules: [
            { required: true, message: '请选择分享图片' },
          ]
        })(<ImageUploader />)}
      </Form.Item>)}
      {hiddenStatus && (<Form.Item label="活动分享语" help="可使用{name}代表用户昵称。">
        {getFieldDecorator('shareTitle', {
          initialValue: formsDate.shareTitle,
          rules: [
            { required: true, message: '请输入活动分享语' },
          ]
        })(
          <Input
            placeholder="分享语，不超过15个字"
            maxLength="15"
          />,
        )}
      </Form.Item>)}
      {hiddenStatus && (<Form.Item label="中间页飞机图" help="建议图片尺寸：750*1667px，比例9:20,格式：jpg。图片底部不要放置关键信息。">
        {getFieldDecorator('middleImg', {
          initialValue: formsDate.middleImg,
          rules: [
            { required: true, message: '请选择中间页飞机图' },
          ]
        })(<ImageUploader />)}
      </Form.Item>)}
      <Form.Item {...tailFormItemLayout}>
        <AuthButton name="admin.taDrainage.id.put" noRight={null}>
          <Button type="primary" htmlType="submit" className={styles.searchBtn} onClick>
            确定
    </Button>
        </AuthButton>
        <Button style={{ marginLeft: 8 }} onClick={handleCancel}>
          取消
      </Button>
      </Form.Item>
    </Form>

  }
  const Formss = Form.create({ name: 'Forms' })(Forms);



  //重置搜索
  function handleReset() {
    props.form.resetFields();
    localStorage.setItem("drainageActivePageParams", JSON.stringify({ pageNum: 1, pageSize: 10 }));
    gettaDrainage({ pageNum: 1, pageSize: 10 })
  }



  function addshowModal(datas) {

    // alert(datas.drainageId)
    setFormsDate(datas)
    setDate({
      visible: true,
      title: "修改H5项目"
    });
  };

  function showModal() {
    setFormsDate({
      drainageId: '',
      name: '',
      endDate: '',
    })
    setDate({
      visible: true,
      title: '新建H5项目'
    });
  };
  const changePageNum = pageNumber => {
    props.form.validateFields((err, values) => {
      if (!err) {
        localStorage.setItem("drainageActivePageParams", JSON.stringify({ pageNum: pageNumber, pageSize: 10, ...values }));
        gettaDrainage({ pageNum: pageNumber, pageSize: 10, ...values })
      }
    });
  }

  function handleOk() {


    setDate({
      ModalText: 'The modal will be closed after two seconds',
      confirmLoading: true,
    });
    function setTimeout() {
      setDate({
        visible: false,
        confirmLoading: false,
      });
    };
  };

  function handleCancel() {
    console.log('Clicked cancel button');
    setDate({
      visible: false,
    });
  };
  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      console.log('values', values)
      if (!err) {
        console.log('values', values)
        localStorage.setItem("drainageActivePageParams", JSON.stringify({ pageNum: 1, pageSize: 10, ...values }));
        gettaDrainage({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

  //打开新页面
  const openIndexImg = () => {
    const newWin = window.open('about:blank');
    newWin.location.href = "http://njcj.oss-cn-shanghai.aliyuncs.com/%E6%A1%88%E4%BE%8B.png"
  }

  const { getFieldDecorator } = props.form;
  const { visible, confirmLoading, ModalText, title } = date;
  return (
    <>
      <div>
        <Form layout="inline" onSubmit={handleSubmit}>
          <Form.Item>
            {getFieldDecorator('drainageId')(
              <Input
                // prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder="H5项目编号"
              />,
              // {getFieldDecorator('name', {
              // })(<Input/>)}
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('name')(
              <Input
                // prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder="H5项目名称"
              />,
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('isMiniapp')(
              <Select style={{ width: '180px' }} placeholder="是否投放小程序">
                <Option value="1">是</Option>
                <Option value="0">否</Option>
              </Select>,
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('status')(
              <Select style={{ width: '180px' }} placeholder="上架状态">
                <Option value="1">已上架</Option>
                <Option value="0">已下架</Option>
              </Select>,
            )}
          </Form.Item>
          <Form.Item >
            <AuthButton name="admin.taDrainage.search" noRight={null}>
              <Button type="primary" htmlType="submit" className={styles.searchBtn} onClick>
                搜索
          </Button>
            </AuthButton>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
        <AuthButton name="admin.taDrainage.add.post" noRight={null}>
          <Button type="danger" className={styles.addBtn} onClick={showModal}>新增</Button>
        </AuthButton>
        <span style={{ color: '#66B3FF', cursor: 'pointer', margin: '20px', display: 'inline-block' }} onClick={openIndexImg}>优质案例</span>
        <Modal
          title={title}

          visible={visible}
          //  onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
          footer={null}
        >
          <Formss formsDate={formsdate} />
        </Modal>
        <Table
          // onRow={record => {
          //   return {
          //     onClick: toDrainageDetail(record.drainageId),
          //   };
          // }}
          columns={columns} dataSource={datas.records} pagination={false} rowKey="drainageList" />
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
          <Pagination showQuickJumper defaultCurrent={1} total={datas.total} onChange={(e) => changePageNum(e)} current={datas.current} />
        </div>
      </div>
      <Prompt message={location =>
        location.pathname.startsWith("/activity/drainage")
          ? true
          : localStorage.removeItem("drainageActivePageParams")} />
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
