import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Radio, Tag, Tooltip, Tabs, Table, notification, Modal, message } from 'antd';
import moment from 'moment';
import request from '../../../../../utils/request';
import apis from '../../../../../services/apis';
import Styles from './style.less';
import { router } from 'umi';
import BlockSelect from '../../../../../components/HouseSelect/BlockSelect'
import UnitSelect from '../../../../../components/HouseSelect/UnitSelect'
import FloorSelect from '../../../../../components/HouseSelect/FloorSelect'
import RoomSelect from '../../../../../components/HouseSelect/RoomSelect'
import ApartmentSelect from '../../../../../components/HouseSelect/ApartmentSelect';
import AuthButton from '@/components/AuthButton';
import UserInfo from './UserInfo';
import HouseInfo from './HouseInfo';
import BatchInvalid from './BatchRaise/BatchInvalid';
import BatchDel from './BatchRaise/BatchDel';
import BatchPay from './BatchRaise/BatchPay';
import BatchRefund from './BatchRaise/BatchRefund';
import Refund from './BatchRaise/Refund';

/**
 *图片设置
 *
 * @param {*} props
 * @returns
 */
function PreselectionRecord(props) {
  const [data, setData] = useState([])
  const [userInfo, setUserInfo] = useState({visable:false, raiseId:'', raiseRecord: {}})
  const [houseInfo, setHouseInfo] = useState({visable:false, raiseRecordId:''})
  const [invalid, setInvalid] = useState({visable:false,houseIds:''})
  const [batchDel, setBatchDel] = useState({visable:false,houseIds:''})
  const [pay, setPay] = useState({visable:false,houseIds:''})
  const [refund, setRefund] = useState({visable:false,houseIds:''})
  const [taRaiseRecords, setTaRaiseRecords] = useState([])
  const [singleRefund, setSingleRefund] = useState({visable:false, raiseRecordId:''})
  const raiseId = props.raiseId.raiseId
  const salesBatchId = props.salesBatchId
  const buildingId = props.buildingId
  const raiseRecordId = props.raiseRecordId
  const houseId = props.houseId

  useEffect(() => {
    console.log('houseIdhouseIdhouseIdhouseId', houseId)
    getList({houseId:houseId.toString()})
  }, [])

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

  function getList(params) {
    // 网路请求

    request({ ...apis.house.houseRaiseRecord, params: { ...params, salesBatchId: salesBatchId, raiseId: raiseId } }).then(res => {
      console.log(params,'params')
      setData(res)
    }).catch(err => {
      openNotificationWithIcon('error', err.message)
    })
  }

    // 重置搜索
    function handleReset () {
      props.form.resetFields();
      getList({ pageNumber: 1, pageSize: 10 })
    }

  // 分页
  const changePageNum = (pageNumber) => {
    getList({ pageNumber: pageNumber, pageSize: 10, salesBatchId : salesBatchId, raiseId: raiseId, ...props.form.getFieldsValue() })
  }

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

  // 提交事件
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        let {liveTime, ...submitValue} = values
        if (submitValue.startTime != null){
          submitValue.startTime = moment(submitValue.startTime).format('YYYY-MM-DD HH:mm:ss')
        }
        if (submitValue.endTime != null){
          submitValue.endTime = moment(submitValue.endTime).format('YYYY-MM-DD HH:mm:ss')
        }
        console.log('提交数据: ', values)
        getList({ pageNumber: 1, pageSize: 10, ...submitValue })
      }
    });
  }

  function hideHouseInfo(e){
    setHouseInfo(e);
    getList();
  }

  function showInvalid(e){
      if (taRaiseRecords.length <= 0){
        message.info("请选择数据");
        return;
      }
      setInvalid(e);
      getList();
  }

  function showBatchDel(e){
    if (taRaiseRecords.length <= 0){
      message.info("请选择数据");
      return;
    }
    setBatchDel(e);
    getList();
  }
  
  function showPay(e){
    if (taRaiseRecords.length <= 0){
      message.info("请选择数据");
      return;
    }
    setPay(e);
    getList();
  }

  function showRefund(e){
    if (taRaiseRecords.length <= 0){
      message.info("请选择数据");
      return;
    }
    setRefund(e)
    getList();
  }

  function raiseRefund(e){
    console.log('页面刷新')
    setSingleRefund(e);
    getList();
  }

  function toDelBatch(){
    console.log(taRaiseRecords, 'houseIdListhouseIdList')
    if(taRaiseRecords.length < 1){
      openNotificationWithIcon('error', '请先选择需要删除的认筹单')
      return
    }

    Modal.confirm({
      title: '警告：1.删除功能建议仅用于删除测试数据，正常业务数据使用作废功能。1.删除前请确认缴退费业务是否全部处理完成。2.若认筹单中含认筹人锁定的房源，删除认筹单后会解锁此房源。3.请优先使用作废操作。删除数据可能会导致关联业务异常。',
      okText: '确定',
      cancelText: '取消',
      onOk () {
        console.log(taRaiseRecords,'houseIdListhouseIdList');
        request({ ...apis.house.batchDeleteRaiseRecord, data: taRaiseRecords, }).then((data) => {
          console.log('123145')
          message.info("操作成功")
          getList({ pageNum: 1, pageSize: 10 });
        }).catch((err) => {
          // message.info(err.msg)
        })
      },
    });
  }

  function showUserInfo(e){
    setUserInfo(e);
  }

  function showHouseInfo(e){
    setHouseInfo(e)
  }

  const columns = [
    {
      title: '认筹单编号',
      dataIndex: 'raiseRecordId',
      key: 'raiseRecordId',
    },
    {
      title: '房源数',
      dataIndex: 'houseNum',
      key: 'houseNum',
      render: (text, record) => (
        <a style={{ color: '#66B3FF' }} onClick={() => showHouseInfo({visable:true,raiseRecordId:record.raiseRecordId, salesBatchId:salesBatchId,buildingId:buildingId })} >{record.houseNum}</a>
        ),
    },
    {
      title: '认筹锁定状态',
      dataIndex: 'houseLockingStatus',
      key: 'houseLockingStatus',
      render: (text, record) => (<><span>{record.houseLockingStatus == 'unlocked' ? '未锁定':'已锁定'}</span></>),
    },
    {
      title: '认筹人姓名',
      dataIndex: 'name',
      key: 'name',
      // render: unitName => <><span>{unitName}单元</span></>,
    },
    {
      title: '认筹手机号',
      dataIndex: 'tel',
      key: 'tel',
      render: (text, record) => (
      <a style={{ color: '#66B3FF' }} onClick={() => showUserInfo({visable:true, raiseId:raiseId, raiseRecord:record  })} >{record.tel}</a>
      ),
    },
    {
      title: '置业顾问',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '是否作废',
      dataIndex: 'status',
      key: 'status',
      render: (text, record) => (<><span>{record.status == 0 ? '是':'否'}</span></>),
    },
    {
      title: '作废原因',
      dataIndex: 'invalidReason',
      key: 'invalidReason',
    },
    {
      title: '缴费状态',
      // dataIndex: 'payStatus1',
      // key: 'payStatus1',
      render: (text, record) => (<><span>{record.payStatus === 'paid' ? '已缴费':record.payStatus === 'unpaid'?'未缴费':record.payStatus === 'refunded'?'已退费':'正在支付'}</span></>),
    },
    {
      title: '缴费方式',
      dataIndex: 'payType',
      key: 'payType',
      render: (text, record) => (<><span>{record.payType == 'onLine' ? '线上缴费': record.payType == 'offLine' ? '线下缴费' : '线上缴费，线下缴费'}</span></>),
    },
    // {
    //   title: '缴费结果',
    //   // dataIndex: 'payStatus2',
    //   // key: 'payStatus2',
    //   render: (text, record) => (<><span>{record.payStatus === 'paid' ? '已缴费':record.payStatus === 'unpaid'?'未缴费':record.payStatus === 'refunded'?'已退费':'正在支付'}</span></>),
    // },
    // {
    //   title: '退费状态',
    //   // dataIndex: 'payStatus3',
    //   // key: 'payStatus3',
    //   render: (text, record) => (<><span>{record.payStatus === 'refunded' ? '已退费':'未退费'}</span></>),
    // },
    {
        title: '退费原因',
        dataIndex: 'refundReason',
        key: 'refundReason',
    },
    // {
    //     title: '退费结果',
    //     // dataIndex: 'payStatus4',
    //     // key: 'payStatus4',
    //     render: (text, record) => (<><span>{record.payStatus === 'refunded' ? '已退费':'未退费'}</span></>),
    // },
    {
        title: '认筹单提交时间',
        dataIndex: 'createDate',
        key: 'createDate',
        render: (x, row) => <><span>{row.createDate != null ? `${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}` : ''}</span></>,
    },
    {
        title: '最后修改时间',
        dataIndex: 'updateDate',
        key: 'updateDate',
        render: (x, row) => <><span>{row.updateDate != null ? `${moment(row.updateDate).format('YYYY-MM-DD HH:mm:ss')}`:''}</span></>,
    },
    {
        title: '最后修改人',
        dataIndex: 'updateUserName',
        key: 'updateUserName',
    },
    {
      title: '操作',
      dataIndex: '',
      key: '',
      align: 'center',
      render: (text, record) => (
        <AuthButton name="admin.salesBatch.detail.get" noRight={null}>
          <a style={{ color: '#66B3FF' }} onClick={() => raiseRefund({visable:true, raiseRecordId: record.raiseRecordId})} ><span>{record.payStatus === 'paid' && record.payType == 'onLine' ? '退费':''}</span></a>
        </AuthButton>
      ),
    },
  ]
  const { getFieldDecorator } = props.form
  return (
    <>
    <Form layout="inline" onSubmit={e => handleSubmit(e)}>
        <Form.Item>
          {getFieldDecorator('raiseRecordId')(
            <Input placeholder="认筹单编号"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('termName')(
            <Input placeholder="期/区"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('blockName')(
            <Input placeholder="楼栋"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('unitName')(
            <Input placeholder="单元"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('floorName')(
            <Input placeholder="层"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('roomName')(
            <Input placeholder="房号"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('lockingStatus')(
             <Select placeholder="锁定房源状态" style={{width: '120px'}}>
             <Option value="unlocked">未锁定</Option>
             <Option value="locked">已锁定</Option>
           </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('personName')(
            <Input placeholder="认筹人姓名"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('personTel')(
            <Input placeholder="认筹手机号"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('status')(
             <Select placeholder="是否作废" style={{width: '120px'}}>
             <Option value="0">是</Option>
             <Option value="1">否</Option>
           </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('payStatus')(
             <Select placeholder="缴费状态" style={{width: '120px'}}>
             <Option value="unpaid">未缴费</Option>
             <Option value="paid">已缴费</Option>
             <Option value="paying">正在支付</Option>
             <Option value="refunded">已退费</Option>
           </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('payType')(
             <Select placeholder="缴费方式" style={{width: '120px'}}>
             <Option value="onLine,offLine">不限</Option>
             <Option value="onLine">线上缴费</Option>
             <Option value="offLine">线下缴费</Option>
           </Select>,
          )}
        </Form.Item>
        {/* <Form.Item>
          {getFieldDecorator('payStatus')(
             <Select placeholder="缴费结果" style={{width: '120px'}}>
             <Option value="0">不限</Option>
             <Option value="1">成功</Option>
             <Option value="2">失败</Option>
           </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('payStatus')(
             <Select placeholder="退费状态" style={{width: '120px'}}>
             <Option value="0">不限</Option>
             <Option value="1">未退费</Option>
             <Option value="2">已发起</Option>
             <Option value="2">已退费</Option>
           </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('payStatus')(
             <Select placeholder="退费结果" style={{width: '120px'}}>
             <Option value="0">不限</Option>
             <Option value="1">成功</Option>
             <Option value="2">失败</Option>
           </Select>,
          )}
        </Form.Item>    */}
        <Form.Item>
          {getFieldDecorator('startTime')(
            <DatePicker showTime={{ format: 'HH:mm:ss' }} placeholder="认筹提交时间从"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('endTime')(
            <DatePicker showTime={{ format: 'HH:mm:ss' }} placeholder="认筹提交时间到"/>,
          )}
        </Form.Item>  
        <Form.Item>
          <Button type="primary" htmlType="submit" >
            搜索
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
      <Button type="primary" onClick={() => showInvalid({visable:true, houseIds: taRaiseRecords})} style={{ marginTop: '20px', marginRight:'20px'}}>批量作废</Button>
      <Button type="primary" onClick={() => showBatchDel({visable:true, houseIds: taRaiseRecords})} style={{ marginTop: '20px', marginRight:'20px'}}>批量删除</Button>
      <Button type="primary" onClick={() => showPay({visable:true, houseIds: taRaiseRecords})} style={{ marginTop: '20px', marginRight:'20px'}}>批量线下缴费</Button>
      <Button type="primary" onClick={() => showRefund({visable:true, houseIds: taRaiseRecords})} style={{ marginTop: '20px', marginRight:'20px'}}>批量线下退费</Button>
      <UserInfo visible={userInfo.visable} raiseId={userInfo.raiseId} raiseRecordId={userInfo.raiseRecord} onCancel={e => setUserInfo(e)} />
      <HouseInfo visible={houseInfo.visable} salesBatchId={houseInfo.salesBatchId} raiseRecordId={houseInfo.raiseRecordId} raiseId={raiseId} buildingId={houseInfo.buildingId} onCancel={(e) => hideHouseInfo({visable:false, raiseRecordId:''})} />
      <BatchInvalid visible={invalid.visable} houseIds={invalid.houseIds} onCancel={() => showInvalid({visable:false, houseIds: taRaiseRecords})} onSuccess={() => showInvalid({visable:false, taRaiseRecords:[]})}/>
      <BatchDel visible={batchDel.visable} houseIds={batchDel.houseIds} onCancel={() => showBatchDel({visable:false, houseIds: taRaiseRecords})} onSuccess={() => showBatchDel({visable:false, houseIds:'' })}/>
      <BatchPay visible={pay.visable} houseIds={pay.houseIds} onCancel={() => showPay(false)} onSuccess={() => showPay(false)} />
      <BatchRefund visible={refund.visable} houseIds={refund.houseIds} onCancel={() => setRefund(false)} onSuccess={() => showRefund(false)}/>
      <Refund visible={singleRefund.visable} raiseId={raiseId} raiseRecordId={singleRefund.raiseRecordId} onCancel={() => raiseRefund({visable:false, raiseRecordId:''})} onSuccess={(e) => raiseRefund(e)}></Refund>
      <div style={{marginTop:'20px', marginBottom:'20px'}}><span>共筛选出{data.total}条数据</span></div>
      <Table rowSelection={rowSelection} dataSource={data.records} columns={columns} pagination={false} rowKey="carouseFigureList"/>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} current={data.current}/>
      </div>      
    </>
  )
}
const WrappedHeader = Form.create({ name: 'PreselectionRecord' })(PreselectionRecord);
export default WrappedHeader
