import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Form, Input, Button, Icon, Select, message, Table, InputNumber, Divider, Tag, DatePicker, Pagination, Modal, Breadcrumb } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import styles from './style.less';
import { fetch, apis } from '../../../utils/request';
import request from '../../../utils/request';
import AuthButton from '@/components/AuthButton';

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

function header(props) {

    const [taContractList, setTaContractList] = useState([])
    const [data, setData] = useState({})
    const [checkData, setCheckData] = useState()
    const [visible, setVisible] = useState()
    const [price, setPrice] = useState()

    useEffect(() => {
        setVisible(false)
        setCheckData(0)
        getList({ pageNum: 1, pageSize: 10 });
    }, [])
    // 查询列表

    const getList = params => {

        request({ ...apis.signedContract.get, params: { ...params } }).then(data => {
            setData(data)
        })

    }


    const handleSubmit = (e, props) => {
        e.preventDefault();
        props.form.validateFields((err, values) => {
            if (!err) {
                let { signatoryTime, settlementTime, ...submitValue } = values
                if (null != signatoryTime && signatoryTime.length > 0) {
                    const [signatoryStartTime, signatoryEndTime] = signatoryTime
                    submitValue.signatoryStartTime = moment(signatoryStartTime).format('YYYY-MM-DD');
                    submitValue.signatoryEndTime = moment(signatoryEndTime).format('YYYY-MM-DD');
                } 

                if (null != settlementTime && settlementTime.length > 0) {
                    const [settlementStartTime, settlementEndTime] = settlementTime
                    submitValue.settlementStartTime = moment(settlementStartTime).format('YYYY-MM-DD');
                    submitValue.settlementEndTime = moment(settlementEndTime).format('YYYY-MM-DD');
                }

                getList({ pageNum: 1, pageSize: 10, ...submitValue });
            }
        });

    }

    function handleReset() {
        props.form.resetFields();
        getList({ pageNum: 1, pageSize: 10 });
    }

    const changePageNum = pageNumber => {

        props.form.validateFields((err, values) => {
            if (!err) {
                let { signatoryTime, settlementTime, ...submitValue } = values
                if (null != signatoryTime && signatoryTime.length > 0) {
                    const [signatoryStartTime, signatoryEndTime] = signatoryTime
                    submitValue.signatoryStartTime = moment(signatoryStartTime).format('YYYY-MM-DD');
                    submitValue.signatoryEndTime = moment(signatoryEndTime).format('YYYY-MM-DD');
                } 
                if (null != settlementTime && settlementTime.length > 0) {
                    const [settlementStartTime, settlementEndTime] = settlementTime
                    submitValue.settlementStartTime = moment(settlementStartTime).format('YYYY-MM-DD');
                    submitValue.settlementEndTime = moment(settlementEndTime).format('YYYY-MM-DD');
                } 
                getList({ pageNum: pageNumber, pageSize: 10, ...submitValue });
            }
        });
    }


    const { getFieldDecorator } = props.form

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

    const onChange = (value) => {
        console.log(value, 'value')
        setPrice(value)
    }



    const columns = [
        {
            title: '企业名称',
            dataIndex: 'companyName',
            key: 'companyName',
            align: 'center',

        },
        {
            title: '企业编号',
            dataIndex: 'companyCode',
            key: 'companyCode',
            align: 'center',

        },
        {
            title: '代理商名称',
            dataIndex: 'channelProxyName',
            key: 'channelProxyName',
            align: 'center',

        },
        {
            title: '组织名称',
            dataIndex: 'orgName',
            key: 'orgName',
            align: 'center',
        },
        {
            title: '小程序名称',
            dataIndex: 'miniAppName',
            key: 'miniAppName',
            align: 'center',

        },
        {
            title: '合同标题',
            dataIndex: 'contractName',
            key: 'contractName',
            align: 'center',

        },
        {
            title: '甲方签署时间',
            dataIndex: 'signatoryTime',
            key: 'signatoryTime',
            align: 'center',
            render: (x, row) => <><span>{row.signatoryTime ? `${moment(row.signatoryTime).format('YYYY-MM-DD HH:mm:ss')}` : ''}</span></>,
        },
        {
            title: '是否结算',
            dataIndex: 'settlement',
            key: 'settlement',
            align: 'center',
            render: (x, row) => <><span>{row.settlement ? '是' : '否'}</span></>
        },
        {
            title: '结算时间',
            dataIndex: 'settlementTime',
            key: 'settlementTime',
            align: 'center',
            render: (x, row) => <><span>{row.settlementTime ? `${moment(row.settlementTime).format('YYYY-MM-DD HH:mm:ss')}` : ''}</span></>,
        },
        {
            title: '结算单价',
            dataIndex: 'settlementPrice',
            key: 'settlementPrice',
            render: (x, row) => <><span>{row.settlementPrice ? `￥ ${row.settlementPrice / 100}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : row.settlementPrice === 0 ? 0 : ''}</span></>
        },
    ];

    const handleShowModel = val => {

        if (taContractList.length < 1) {
            message.error('请至少选择一条数据')
            return
        }
        let count = 0
        taContractList.map((x) => {

            if (x.settlement) {
                count++
            }
        })
        setCheckData(count)

        setVisible(true);

    }

    const handleCancel = val => {
        setVisible(false);
    }

    const handleOk = val => {
        request({ ...apis.signedContract.put, data: { price: price || 0, taContractList: taContractList } }).then(data => {
            message.info("操作成功")
            setVisible(false);
            getList({ pageNum: 1, pageSize: 10 })

        })

    }


    return (

        <>
            <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
                <Form.Item>
                    {getFieldDecorator('companyName')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="企业名称 "
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('companyCode')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="企业编号 "
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('channelProxyName')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="代理商名称 "
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('orgName')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="组织名称 "
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('miniAppName')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="小程序名称 "
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('contractId')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="合同编号 "
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('contractName')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="合同标题 "
                        />,
                    )}
                </Form.Item>

                <Form.Item>
                    <span style={{ marginRight: '10px' }}>甲方签署时间：</span>
                    {getFieldDecorator('signatoryTime')(
                        <RangePicker placeholder={['开始时间', '结束时间']} />
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('settlement')(
                        <Select style={{ width: '180px' }} placeholder="是否结算">
                            <Select.Option value={true}>是</Select.Option>
                            <Select.Option value={false}>否</Select.Option>
                        </Select>,
                    )}
                </Form.Item>
                <Form.Item>
                    <span style={{ marginRight: '10px' }}>结算时间</span>
                    {getFieldDecorator('settlementTime')(
                        <RangePicker placeholder={['开始时间', '结束时间']} />
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className={styles.searchBtn}>搜索</Button>
                    <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
                </Form.Item>
            </Form>
            <Button type="primary" className={styles.addBtn} onClick={e => handleShowModel()} style={{ marginLeft: '30px' }} >批量结算</Button>
            <Table id='noticeTable' rowSelection={rowSelection} rowKey={r => r.contractId} dataSource={data.records} columns={columns} pagination={false} />
            {/*  */}
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
                <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={e => changePageNum(e)} current={data.current} />
            </div>
            <Modal
                title="批量结算"
                visible={visible}
                onOk={handleOk}

                onCancel={handleCancel}
            // footer={null} 
            >
                <p>确认结算所选{taContractList.length}份合同手续费？其中{checkData}份已结算过，若不想再结算，请取消勾选。</p>
                <div style={{ marginTop: '50px', textAlign: 'center' }}>结算单价:<InputNumber max={99} style={{ marginLeft: '10px', width: '150px' }} formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} defaultValue={0} precision={2} onChange={onChange} />元/份</div>
                <div style={{color:'#999', textAlign: 'center'}}>结算金额为0代表免费，整数位最多2位，小数位最多2位。</div>            


            </Modal>

        </>
    )
}

const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader