import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Form, Pagination, Card, Button, Icon, Tooltip, message,   notification, Modal, Table, Select, Input, DatePicker } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import className from 'classnames';
import Cell from '../../../components/Cell';
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 [ data, setData ] = useState({})
  const [deleteList, setDeleteList] = useState([])

  useEffect(() => {
    getList({ pageNum: 1, pageSize: 10 });
  },[])

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

  
  // 提交事件
  const handleSubmit = (e, props) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

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

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


  // 跳转到编辑资讯
  const toEditCompany = (id) => () => {
    router.push({
      pathname: '/eContract/company/edit',
      query: {
        id
      },
    });
  }

  
  // 跳转到编辑资讯
  const toAddCompany = () => {
    router.push({
      pathname: '/eContract/company/add',
    });
  }

  
  const changeStatus = () => {
    if(deleteList.length < 1){
      message.error('请先选择要删除的数据！')
      return
    }
    const title = '确认将所选的' + deleteList.length + '条数据删除？认证通过的企业不会被删除'
    Modal.confirm({
      title: title,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        request({ ...apis.company.delete, data: { ids: deleteList.map(x => x.companyId) } }).then((data) => {
          const resultMessage = '操作成功，其中'+data.successNum+'条成功删除，'+data.failNum+'条已认证数据无法删除。'
          message.info(resultMessage)
          getList({ pageNum: 1, pageSize: 10 });
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      }
    });
  }
  /**
   *
   *
   * @param {*} props
   * @returns
   */
  const columns = [
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      align: 'center',
    },
    {
      title: '企业编号',
      dataIndex: 'companyCode',
      key: 'companyCode',
      align: 'center',
    },
    {
      title: '法大大客户编号',
      dataIndex: 'fadadaCode',
      key: 'fadadaCode',
      align: 'center',

    },
    {
      title: '实名认证状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (status) => <span>{status === 0 ? '未认证' : status === 1 ? "管理员资料已提交" : status === 2 ? "企业基本资料（没有申请表）已提交" : status === 3 ? "已提交待审核" : 
      status === 4 ? '审核通过' : status === 5 ? "审核不通过" : status === 6 ? "人工初审通过" : "" }</span>,
    },
    {
      title: '企业管理员身份',
      dataIndex: 'companyManagerType',
      key: 'companyManagerType',
      align: 'center',
      render: (companyManagerType) => <span>{companyManagerType === 'legal' ? '法人' : companyManagerType === 'agent' ? "代理人" : "" }</span>,
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: (x, row) => (
        <span style={{ color: '#FF925C', cursor: 'pointer' }} onClick={toEditCompany(row.companyId)}>
          查看详情<Icon type="form" className={styles.edit} />
        </span>
      ),
    },
  ];
  function handleReset() {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 10 })
  }

  const { getFieldDecorator } = props.form
  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('status')(
            <Select style={{ width: '180px' }} placeholder="实名认证状态">
              <Select.Option value="0">未认证</Select.Option>
              <Select.Option value="1">管理员资料已提交</Select.Option>
              <Select.Option value="2">企业基本资料（没有申请表）已提交</Select.Option>
              <Select.Option value="3">已提交待审核</Select.Option>
              <Select.Option value="4">审核通过</Select.Option>
              <Select.Option value="5">审核不通过</Select.Option>
              <Select.Option value="6">人工初审通过</Select.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>
      <AuthButton name="admin.taNewsType.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={toAddCompany}>新增</Button>
      </AuthButton>
      <AuthButton name="admin.taNewsType.post" noRight={null}>
        <Button type="danger" style={{ marginLeft: 15 }} onClick={changeStatus}>删除</Button>
      </AuthButton>
      <Table rowSelection={rowSelection} rowKey="newsType" dataSource={data.records} columns={columns} pagination={false} />
      <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: 'header' })(header);

export default WrappedHeader