import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Pagination, Modal, DatePicker, notification } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import AuthButton from '@/components/AuthButton';
import Prompt from 'umi/prompt';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import styles from '../../../style/GoodsList.less';
import SelectCity from '../../../../components/SelectButton/CitySelect'
import BuildSelect from '../../../../components/SelectButton/BuildSelect'
import apis from '../../../../services/apis';
import request from '../../../../utils/request';
import Navigate from '@/components/Navigate';
// import SaleBatchListHelpDoc from '../edit/components/SalesBatchListHelpDoc';

const { Option } = Select;

const header = props => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [data, setData] = useState({ list: [], total: 0 })
  //   const [page, changePage] = useState({})
  const [liveIdList, setLiveIdList] = useState([])
  const [time, setTime] = useState('')
  const [showHelp, setShowHelp] = useState(false)

  // 查询列表
  const getList = params => {
    request({ ...apis.taliveActivity.taLiveActivity, params: { ...params } }).then(data => {
      console.log(data)
      setData(data)
    })
  }

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {

    if (localStorage.getItem("liveActivePageParams")) {
      props.form.setFieldsValue(JSON.parse(localStorage.getItem("liveActivePageParams")));
      // const { getFieldDecorator } = JSON.parse(localStorage.getItem("pageParams"))

      getList(JSON.parse(localStorage.getItem("liveActivePageParams")))
    } else {
      localStorage.setItem("liveActivePageParams", JSON.stringify({ pageNum: 1, pageSize: 10 }));
      getList({ pageNum: 1, pageSize: 10 });
    }
   
  }, [])

  // 跳转到编辑
  const toAddLive = rowData => () => {
    if(rowData) {
      router.push({
      pathname: '/activity/liveActivity/edit',
      query: {
        id: rowData.liveActivityId,
        buildingId: rowData.buildingId,
      },
    });
      return
    }
    router.push({
      pathname: '/activity/liveActivity/add',
    });
  }

  const toDataReacord = rowData => () => {
  
      router.push({
      pathname: '/activity/liveActivity/liveActivityRecord',
      query: {
        id: rowData.liveActivityId,
      },
    });
  }

  function openNotificationWithIcon(type, message) {
    notification[type]({
      message,
      description:
        '',
    });
  }

  
  const toDelLiveActivity = rowData => () =>{
    console.log(liveIdList, 'liveIdListliveIdList')
    if(liveIdList.length < 1){
      openNotificationWithIcon('error', '请先选择需要删除的直播活动')
      return
    }
    Modal.confirm({
      title: '删除后当前直播活动关联的小程序端开屏图、banner图等也会自动下架',
      okText: '确定',
      cancelText: '取消',
      onOk () {
        request({ ...apis.taliveActivity.deleteTaLiveActivity, data: liveIdList, }).then((data) => {
          message.info("操作成功")
          getList(JSON.parse(localStorage.getItem("liveActivePageParams")))
        }).catch((err) => {
          // message.info(err.msg)
        })
      },
    });

    
  }

  /**
   *
   *
   * @param {*} props
   * @returns
   */
  const columns = [
    {
      title: '直播活动标题',
      dataIndex: 'liveActivityTitle',
      key: 'liveActivityTitle',
      align: 'center',
      render:  (x, row) => <Navigate onClick={toAddLive(row)}>{row.liveActivityTitle}</Navigate>,
    },
    {
      title: '所属城市',
      dataIndex: 'cityName',
      key: 'cityName',
      align: 'center',
    },
    {
      title: '所属楼盘',
      dataIndex: 'buildingName',
      key: 'buildingName',
      align: 'center',
    },
    {
      title: '直播开始时间',
      dataIndex: 'liveStartDate',
      key: 'liveStartDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.liveStartDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '直播结束时间',
      dataIndex: 'liveEndDate',
      key: 'liveEndDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.liveEndDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '权重',
      dataIndex: 'weight',
      key: 'weight',
      align: 'center',
    },
    {
      title: '发布状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: status => <><span>{status == 0 ? '未发布' : '已发布'}</span></>,
    },
    {
      title: '新增人',
      dataIndex: 'createName',
      key: 'createName',
      align: 'center',
    },
    {
      title: '新增时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '修改人',
      dataIndex: 'updateName',
      key: 'updateName',
      align: 'center',
    },
    {
      title: '修改时间',
      dataIndex: 'updateDate',
      key: 'updateDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.updateDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '操作',
      align: 'center',
      width: 240,
      render: withActions((text, record) => [    
        <AuthButton name="admin.liveActivity.dataRecord" noRight={null}>
          <EditIcon type="record" text="数据记录" onClick={toDataReacord(record)} />
        </AuthButton>,
 
        <AuthButton name="admin.live.detail.get" noRight={null}>
          <EditIcon type="look" text="查看详情" onClick={toAddLive(record)} />
        </AuthButton>,
      ]),
    },
  ];
  const getSignList = dynamicId => {
    router.push({
      pathname: '/activity/SignList',
      query: {
        dynamicId,
      },
    });
  }

  const changePageNum = pageNumber => {
    localStorage.setItem("liveActivePageParams", JSON.stringify({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() }));
    getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
  }

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows: ', selectedRows);
      setLiveIdList(selectedRows)
    },
  };

  // 提交事件
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log('提交数据: ', values)
        if (time) {
          values.time = `${moment(time).format('YYYY-MM-DDT00:00:00.000')}Z`
        } else {
          values.time = null
        }
        localStorage.setItem("liveActivePageParams", JSON.stringify({ pageNum: 1, pageSize: 10, ...values }));
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

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

  // 时间回调
  function timeOnChange(date, dateString) {
    console.log(date, dateString)
    setTime(date)
  }


  const { getFieldDecorator } = props.form
  return (

    <>
      {/* style={{ display: 'none' }} */}
      <div id="qrcode"></div>
      <Form layout="inline" onSubmit={e => handleSubmit(e)}>
        <Form.Item>
          {getFieldDecorator('liveActivityTitle')(
             <Input
             prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
             placeholder="直播活动标题"
           />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('cityId')(
            <SelectCity />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('buildingId')(
            <BuildSelect />,
          )}
        </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.buildingDynamic.search" noRight={null}>
            <Button type="primary" htmlType="submit" className={styles.searchBtn}>
              搜索
            </Button>
          </AuthButton>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
      
      <AuthButton name="admin.live.add.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={toAddLive()}>新增</Button>
      </AuthButton>
      <AuthButton name="admin.live.del" noRight={null}>
        <Button type="primary" className={styles.addBtn} onClick={toDelLiveActivity()} style={{marginLeft:'30px'}}>删除</Button>
      </AuthButton><br/>
      <span>共筛选出{data.total}条记录</span>
      <Table rowSelection={rowSelection}
       dataSource={data.records} columns={columns} pagination={false} rowKey="activityList" />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={e => changePageNum(e)} current={data.current}/>
      </div>
      {/* <SaleBatchListHelpDoc visible={showHelp} onCancel={() => setShowHelp(false)} /> */}
      <Prompt message={location =>
        location.pathname.startsWith("/activity/liveActivity")
          ? true
          : localStorage.removeItem("liveActivePageParams")} />
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
