import React, { useState, useEffect } from 'react';
import { Input, DatePicker, Pagination, Search, Modal, Menu, Dropdown, Button, Icon, message, Table, Divider, Tag, Select, Form, Alert } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import XForm, { FieldTypes, createForm } from '../../../components/XForm';
// import XForm, { FieldTypes } from '../../../components/XForm';
import styles from './style.less';
import router from 'umi/router';
import apis from '../../../services/apis';
import request from '../../../utils/request';
import moment from 'moment';



const header = props => {

    const noticeId = props.location.query.id

    const [data, setData] = useState({})
    const [sample, setsample] = useState({})

    const [visible, setVisible] = useState()
    const [formsdate, setFormsDate] = useState({})
    const [time, setTime] = useState()
    //   const [page, changePage] = useState({})
    useEffect(() => {

        setVisible(false)
        setsample({
            sampleNme: ''
        })
        if (noticeId) {
            console.log(noticeId, 'noticeId')
            getNewsData(noticeId)
        }
    }, [])

    const getNewsData = (noticeId) => {
        request({
            ...apis.openScreen.get,
            urlData: { id: noticeId }
        }).then((data) => {
            console.log(data, 'data')
            setData(data)
            setTime(data.invalidTime)
            setsample({
                sampleId: data.targetId,
                sampleName: data.targetName
            })
        }).catch((err) => {
            message.error(err.msg || err.message)
        })

    }

    const ModalData = props => {
        // console.log('data', data.targetId)
        // const targetId = data.targetType


        const [h5data, setH5data] = useState({})
        const [name, setName] = useState()
        
   

        useEffect(() => {


            // console.log(targetType, 'targetType')
            getH5data({ pageNum: 1, pageSize: 10 })

        }, [])
        // const getList = params => {
        //     request({ ...apis.openScreen.list, params: { ...params } }).then(data => {
        //         setData(data)
        //     })
        // }
        const getH5data = params => {
            request({
                ...apis.openScreen.getSample, params: { ...params }
            }).then((data) => {
                setH5data(data)
              
               
            }).catch((err) => {
                message.error(err.msg || err.message)
            })

        }


        const toChoice = (value) => {

            Modal.confirm({
                title: '是否关联此业务',
                okText: '确定',
                cancelText: '取消',
                onOk() {
                    setsample({
                        sampleId: value.sampleId,
                        sampleName: value.sampleName
                    })
                    message.info("操作成功")
                    setVisible(false)
                },
            });

            console.log(value, 'value')


        }

        const changePageNum = pageNumber => {

            getH5data({ pageNum: pageNumber, pageSize: 10, })
        }



        const columns = [
            {
                title: '样例名',
                dataIndex: 'sampleName',
                key: 'sampleName',
                align: 'center',

            },
            {
                title: '权重',
                dataIndex: 'orderNo',
                key: 'orderNo',
                align: 'center',

            },
            {
                title: '新增人',
                dataIndex: 'addUserName',
                key: 'addUserName',
                align: 'center',
            },
            {
                title: '新增时间',
                dataIndex: 'createDate',
                key: 'createDate',
                align: 'center',
                render: (x, row) => <><span>{row.createDate ? `${moment(row.createDate).format('YYYY-MM-DD H:mm:ss')}` : ''}</span></>,
            },
            // {
            //     title: '修改人',
            //     dataIndex: 'updateUserName',
            //     key: 'updateUserName',
            //     align: 'center',
            //     // render: (status) => <><span>{status == 1 ? '是' : '否'}</span></>
            // },
            // {
            //     title: '修改时间',
            //     dataIndex: 'updateDate',
            //     key: 'updateDate',
            //     align: 'center',
            //     render: (x, row) => <><span>{row.updateDate ? `${moment(row.updateDate).format('YYYY-MM-DD H:mm:ss')}` : ''}</span></>,
            // },

            {
                title: '操作',
                dataIndex: 'handle',
                key: 'handle',
                align: 'center',
                render: (x, row) => (
                    <>


                        <span style={{ color: '#FF925C', cursor: 'pointer' }} onClick={e => toChoice(row)}>
                            选择<Icon type="form" />
                        </span>
                        {/* className={styles.edit} */}
                    </>
                ),
            },
        ];

        const getname = value => {
            console.log(value.value, '44')
            setName(value)
            // setH5data({ pageNum: 1, pageSize: 10,sampleName:value })
        }


        const handleSubmitName = (e, props) => {
            e.preventDefault();
            getH5data({ pageNum: 1, pageSize: 10, ...props.form.getFieldsValue() });
        }

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

        const { getFieldDecorator } = props.form
        return (
            <>
                <div>
                    <Form layout="inline" onSubmit={e => handleSubmitName(e, props)}>
                        <Form.Item>
                            {getFieldDecorator('sampleName')(
                                <Input
                                    prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                    placeholder="样例名"
                                />,
                            )}
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className={styles.searchBtn}>
                                搜索
                            </Button>
                            {/*  */}
                            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                                重置
                              </Button>
                        </Form.Item>
                    </Form>
                    <Table rowKey="H5List" dataSource={h5data.records || []} columns={columns} pagination={false} />
                    <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
                        <Pagination showQuickJumper defaultCurrent={1} total={h5data.total} onChange={e => changePageNum(e)} current={h5data.current} />
                    </div>
                </div>
            </>
        )
    }
    const ModalDatas = Form.create({ name: 'ModalData' })(ModalData);
    const onSelectBusiness = (e) => {
        console.log('11111')

    }

    // function onChange(value, dateString) {
    //     console.log('Selected Time: ', value);
    //     console.log('Formatted Selected Time: ', dateString);
    //   }

    //   function onOk(value) {
    //     console.log('onOk: ', value);
    //   }

    const handleChange = (value) => { }

    function range(start, end) {
        const result = [];
        for (let i = start; i < end; i++) {
            result.push(i);
        }
        return result;
    }

    function disabledDate(current) {
        
        return current && current < moment().startOf('day');
    }

    // function disabledDateTime() {
    //     return {
    //         disabledHours: () => range(0, moment().hour()),
    //         disabledMinutes: () => range(0, moment().minute() + 1),
    //         disabledSeconds: () => [],
    //     };
    // }
    // range(moment().second(), moment().second())


    const fields = [
        {
            label: '通知标题',
            name: 'title',
            type: FieldTypes.Text,
            value: data.title,
            rules: [
                { required: true, message: '请输入通知标题' },
                { max: 20, message: '通知标题名称不超过20个字符' }
            ]
        },
        {
            label: '通知图',
            name: 'noticeImg',
            type: FieldTypes.ImageUploader,
            value: data.noticeImg,
            rules: [
                { required: true, message: '请选择通知图' },
            ],
            help: '建议尺寸：835*556 px，比例：3:2，格式：jpg，大小：不超过300KB，用于开屏通知主图',
        },
        {
            label: '关联业务类型',
            name: 'targetType',
            type: FieldTypes.Select,
            dict: [{
                name: "H5样例",
                value: "H5"
            },
            ],
            value: data.targetType ? data.targetType : "H5",
        },
        {
            label: '关联业务',
            name: 'sampleName',
            // value: data.targetId,
            //   type: FieldTypes.Text,
            render: <div style={{ color: 'blue' }} onClick={e => handleShowModel(data.targetId)}>{sample.sampleName || '选择关联业务'}{console.log(sample, '13')}</div>,
        },
        {
            label: '发布状态',
            type: FieldTypes.Select,
            name: 'status',
            dict: [
                // {
                //     name: "删除",
                //     value: "-1"
                // },
                {
                    name: "是",
                    value: "1"
                },
                {
                    name: "否",
                    value: "0"
                },],

                // row.status === 1 &&moment(row.invalidTime) > moment() ? '是' :'否'
            value: data.status === undefined || data.status === null? null : data.status === 1 && moment(time) > moment() ? "1" : "0" ,

            rules: [
                { required: true, message: '请选择有效发布状态' },
            ],

        },
        {
            label: '自动下架时间',
            name: 'invalidTime',
            render: (text, record) =>
                // <div>
                /* <DatePicker showTime onChange={onChange} onOk={onOk} />
               <br /><DatePicker disabledDate={disabledDate}></DatePicker>,
               <RangePicker
                 showTime={{ format: 'HH:mm' }}
                 format="YYYY-MM-DD HH:mm"
                 onChange={onChange}
                 onOk={onOk}
               />
               </div>, */

                // <div>
                //   <DatePicker showTime = {data.invalidTime}  disabledDate={disabledDate} onChange={onChange} onOk={onOk} />

                // </div>, 
                // <DatePicker disabledDate={disabledDate} onChange={ontime}></DatePicker>,showTime={{ format: 'HH:mm' }}
                <DatePicker
                
               
                    showToday = {false}
                    disabledDate={disabledDate}
                    // disabledTime={disabledDateTime}
                    showTime={{ format: 'YYYY-MM-DD HH:mm:ss' }}

                />,
            //         < DatePicker
            //             format = "YYYY-MM-DD HH:mm:ss"
            //             disabledDate = { disabledDate }
            //             disabledTime = { disabledDateTime }
            //             showTime
            // // onChange={onChange}
            // ></DatePicker >,


            // type: FieldTypes.DatePicker,
            value: data.invalidTime != null ? moment(data.invalidTime, 'YYYY-MM-DD HH:mm:ss') : null,

            help: '下架时间仅支持未来时间，到达未来时间后系统自动将开屏通知发布状态修改为否'

        },
        {
            label: '权重',
            name: 'orderNo',
            type: FieldTypes.Number,
            value: data.orderNo,

            help: '用于列表排序，越大越靠前'
        },
    ]

    const handleSubmit = (values) => {

        values.targetId = sample.sampleId
        values.targetName = sample.sampleName

       
        if (noticeId) {
            values.noticeId = noticeId
            if (values.invalidTime != null){
                values.invalidTime =  moment(values.invalidTime).format('YYYY-MM-DD HH:mm:ss');
            }
            console.log('3333333', values)
            request({ ...apis.openScreen.put, urlData: { id: noticeId }, data: { ...values } }).then((data) => {
                message.info('提交成功！')
                cancelPage();
            }).catch((err) => {
                message.error(err.msg || err.message)
            })
        } else {
            if (values.invalidTime != null){
                values.invalidTime =  moment(values.invalidTime).format('YYYY-MM-DD HH:mm:ss');
            }
            request({ ...apis.openScreen.post, data: { ...values } }).then((data) => {
                console.log('提交成功！')
                cancelPage();
            }).catch((err) => {
                message.error(err.msg || err.message)
            })
        }


    }
    //model
    const handleShowModel = val => {
        setVisible(true);
    }

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

    const cancelPage = () => {
        router.push({
            pathname: '/resource/openScreen',
        });
    }

    return (
        <>
            <div>
                <XForm onSubmit={handleSubmit} onCancel={cancelPage} fields={fields}></XForm>
                <Modal
                    title="选择关联业务"
                    visible={visible}
                    //  onOk={handleOk}

                    onCancel={handleCancel}
                    footer={null}
                >
                    <ModalDatas></ModalDatas>

                </Modal>
            </div>
        </>
    )
}

const WrappedNormalLoginForm = Form.create({ name: 'header' })(header);
export default WrappedNormalLoginForm