import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, Breadcrumb,Radio } 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';
import Navigate from '@/components/Navigate';
import ModelForm from './components/ModelForm';

function header(props) {
    
    const [taNoticeList, setTaNoticeList] = useState([])
    const [ data, setData ] = useState({})
    const [visible, setVisible] = useState(false);
    const [currentData, setCurrentData] = useState(false);

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

    const getList = params => {
        request({ ...apis.promote.list, params: { ...params } }).then(data => {
            setData(data)
        })
    }

    const toEditResource = (id) => () => {
        router.push({
            pathname: '/officenews/edit',
              query: {
                id
              },
        });
    }

    const openModel = (row) => () => {
        setVisible(true)
        setCurrentData(row)
    }

    const topNew = (row) => () => {
        row.weight = row.weight === 1 ? 0 : 1
        editNewsById(row)
    }

    const deleteRow = (row) => () =>{
        row.status = -1
        editNewsById(row)
    }

    //编辑资讯
    const editNewsById = values => {
        request({ ...apis.officenews.update, urlData: { id: values.newsId }, data: { ...values }}).then((data) => {
            getList({ pageNum: 1, pageSize: 10 });
          }).catch((err) => {
            message.error(err.msg || err.message)
          })
    }

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

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

    const toDelBatch = rowData => () => {
        console.log(taNoticeList, 'taNoticeList')
        if (taNoticeList.length < 1) {
            message.error('请至少选择一条数据')
            return
        }

        Modal.confirm({
            title: '确认将所选数据删除？',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                request({ ...apis.openScreen.delete, data: taNoticeList, }).then((data) => {
                  message.info("操作成功")
                  getList({ pageNum: 1, pageSize: 10 });
                  setTaNoticeList([])
                }).catch((err) => {
                })
            },
        });
    }

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

    const deleteContact =(row) => () => {
        Modal.confirm({
            title: '确认将所选数据删除？',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                request({ ...apis.promote.update, urlData: { id: row.serialNo }, data: { status: -1} }).then((data) => {
                    message.info("操作成功")
                    getList({ pageNum: 1, pageSize: 10 });
                })
            },
        });
    }


    const columns = [
        {
            title: '表单编号',
            dataIndex: 'serialNo',
            key: 'serialNo',
            align: 'center',
            render:  (x, row) => <Navigate to={`/promote/detail?id=${row.serialNo}`}>{row.serialNo}</Navigate>,
        },
        {
            title: '公司名称',
            dataIndex: 'company',
            key: 'company',
            align: 'center',
        },
        {
            title: '联系人',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
            align: 'center',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            align: 'center',
        },
        {
            title: '提交时间',
            dataIndex: 'createDate',
            key: 'createDate',
            align: 'center',
            render: (x, row) => <><span>{row.createDate?`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`:''}</span></>,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (x, row) => <><span>{row.status === 1 ? '有效' : row.status === 2 ? "待跟进" : '无效'}</span></>
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            align: 'center',
            render: (x, row) => (
                <>
                    <span style={{ color: '#FF925C', cursor: 'pointer' }} onClick={openModel(row)}>
                        {row.status === 2 ? "立即跟进" : '添加备注'}<Icon type="form" className={styles.edit} />
                    </span>
                    <span style={{ color: '#FF925C', cursor: 'pointer', marginLeft: '20px'  }} onClick={deleteContact(row)}>
                        {row.status === 0 ? <span>删除<Icon type="form" className={styles.edit} /></span> : ''}
                    </span>
                </>
            ),
        },
    ];

    const { getFieldDecorator } = props.form

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


      const modelCancel = (state) => {
            setVisible(false)
            if(state === "success"){
                getList({ pageNum: 1, pageSize: 10 });
            }
      }
 
    return (

        <>
            <div>
                <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
                    <Form.Item>
                        {getFieldDecorator('company')(
                            <Input
                                prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="公司名称"
                            />,
                        )}
                    </Form.Item>
                    <Form.Item>
                        {getFieldDecorator('name')(
                            <Input
                                prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="联系人"
                            />,
                        )}
                    </Form.Item>
                    <Form.Item>
                        {getFieldDecorator('phone')(
                            <Input
                                prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="手机号"
                            />,
                        )}
                    </Form.Item>
                    <Form.Item>
                        {getFieldDecorator('status')(

                            <Select style={{ width: '180px' }} placeholder="表单状态">
                                <Option value="">全部</Option>
                                <Option value="2">待跟进</Option>
                                <Option value="1">有效</Option>
                                <Option value="0">无效</Option>
                            </Select>,

                        )}
                    </Form.Item>
                    <Form.Item>

                        <Button type="primary" htmlType="submit" className={styles.searchBtn}>
                            搜索
              </Button> 
                        {/*  */}
                        <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                            重置
            </Button>
                    </Form.Item>
                </Form>

                <Table id='noticeTable' rowKey={r => r.newsId} 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>
            </div>

            <ModelForm visible={visible} currentData={currentData} onCancel={(state) => modelCancel(state)}/>
        </>
    )
}

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

export default WrappedHeader