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

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 [houseIdList, setHouseIdList] = useState([])
  const [time, setTime] = useState('')
  const [showHelp, setShowHelp] = useState(false)

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

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    getList({ pageNum: 1, pageSize: 10 });
  }, [])

  // 跳转到编辑
  const toAddHouse = rowData => () => {
    if(rowData) {
      router.push({
      pathname: '/house/raise/edit',
      query: {
        id: rowData.raiseId,
        buildingId: rowData.buildingId,
        salesBatchId: rowData.salesBatchId,
      },
    });
      return
    }
    router.push({
      pathname: '/house/raise/add',
    });
  }

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

  function toDecimal2 (x){
    var f = parseFloat(x);
    if (isNaN(f)) {
      return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
      rs = s.length;
      s += '.';
    }
    while (s.length <= rs + 2) {
      s += '0';
    }
    console.log(s)
    return s;
  }
  function regFenToYuan(fen){
    var num = fen;
    num = fen * 0.01;
    num += '';
    var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
    num = num.replace(reg, '$1');
    console.log(num, 'yuan')
    num = toDecimal2(num)
    return num
  }
  
  const toDelBatch = rowData => () =>{
    console.log(houseIdList, 'houseIdListhouseIdList')
    if(houseIdList.length < 1){
      openNotificationWithIcon('error', '请先选择需要删除的认筹单')
      return
    }

    Modal.confirm({
      title: '确定删除认筹单吗',
      okText: '确定',
      cancelText: '取消',
      onOk () {
        console.log(houseIdList,'houseIdListhouseIdList');
        request({ ...apis.house.batchDelRaise, data: houseIdList, }).then((data) => {
          message.info("操作成功")
          getList({ pageNum: 1, pageSize: 10 });
        }).catch((err) => {
          // message.info(err.msg)
        })
      },
    });
  }

  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();
  }

  /**
   *
   *
   * @param {*} props
   * @returns
   */
  const columns = [
    {
      title: '销售批次名',
      dataIndex: 'salesBatchName',
      key: 'salesBatchName',
      align: 'center',
      render:  (x, row) => <Navigate onClick={toAddHouse(row)}>{row.salesBatchName}</Navigate>,
    },
    {
      title: '楼盘名称',
      dataIndex: 'buildingName',
      key: 'buildingName',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
    },
    {
      title: '房源总数',
      dataIndex: 'salesNumber',
      key: 'salesNumber',
      align: 'center',
    },
    {
      title: '发布状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: status => <><span>{status == 0 ? '否' : '是'}</span></>,
    },
    {
      title: '认筹开始时间',
      dataIndex: 'raiseStartTime',
      key: 'raiseStartTime',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.raiseStartTime).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '认筹结束时间',
      dataIndex: 'raiseEndTime',
      key: 'raiseEndTime',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.raiseEndTime).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '锁房方式',
      dataIndex: 'houseLockingType',
      key: 'houseLockingType',
      align: 'center',
      render: (x, row) => <><span>{row.houseLockingType == 'auto' ? "自动锁房" : "手动锁房"}</span></>,
    },
    {
      title: '认筹金额',
      dataIndex: 'raisePrice',
      key: 'raisePrice',
      align: 'center',
      render: (x, row) => <span>{regFenToYuan(row.raisePrice)}</span>
    },
    {
      title: '缴费方式',
      dataIndex: 'payType',
      key: 'payType',
      align: 'center',
      render: (x, row) => <><span>{row.payType == 'offLine' ? "线下缴费" : row.payType == 'onLine' ? "线上缴费" : "线上缴费，线下缴费"}</span></>,
    },
    {
      title: '认筹单总数',
      dataIndex: 'raiseRealHeat',
      key: 'raiseRealHeat',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: '',
      key: '',
      align: 'center',
      render: withActions((text, record) => [
        <AuthButton name="admin.raise.detail.get" noRight={null}>
          <EditIcon type="look" text="查看详情" onClick={toAddHouse(record)} />
        </AuthButton>,
      ]),
    },
  ];
  const getSignList = dynamicId => {
    router.push({
      pathname: '/activity/SignList',
      query: {
        dynamicId,
      },
    });
  }

  const changePageNum = pageNumber => {
    getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
  }

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows: ', selectedRows);
      setHouseIdList(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
        }
        
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

  // 重置搜索
  function handleReset () {
    props.form.resetFields();
    setTime('')
    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('salesBatchName')(
             <Input
             prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
             placeholder="销售批次名"
           />,
          )}
        </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.raise.add.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={toAddHouse()}>新增</Button>
      </AuthButton>
      <AuthButton name="admin.raise.del" noRight={null}>
        <Button type="primary" className={styles.addBtn} onClick={toDelBatch()} style={{marginLeft:'30px'}}>删除</Button>
      </AuthButton>
      <Icon type="question-circle" theme="filled" style={{ fontSize: '25px', color: '#F00', marginLeft:'30px'}} onClick={() => setShowHelp(true)} />
      <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>
      <RaiseHelpDoc visible={showHelp} onCancel={() => setShowHelp(false)} />
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
