import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, DatePicker, notification } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import router from 'umi/router';
import moment from 'moment';
import styles from '../../style/GoodsList.less';
import SelectCity from '../../../components/SelectButton/CitySelect'
import BuildSelect from '../../../components/SelectButton/BuildSelect'
import apis from '../../../services/apis';
import request from '../../../utils/request';
import AuthButton from '@/components/AuthButton';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import Navigate from '@/components/Navigate';
// import RaiseHelpDoc from '../edit/components/RaiseHelpDoc';

const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
 
const header = props => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [data, setData] = useState({ list: [], total: 0 })
  //   const [page, changePage] = useState({})
  const [contractList, setContractList] = useState([])
  const [time, setTime] = useState('')
  const [showHelp, setShowHelp] = useState(false)

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

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    getList({ pageNum: 1, pageSize: 10 });
  }, [])

  const toAdd = rowData => () => {
    router.push({
      pathname: '/eContract/template/add',
    });
  }

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

  const toDel = rowData => () =>{
    if(contractList.length < 1){
      openNotificationWithIcon('error', '请先选择需要删除的合同模板')
      return
    }

    Modal.confirm({
      title: '确定将所选的'+ contractList.length +'条合同模板删除?',
      okText: '确定',
      cancelText: '取消',
      onOk () {
        console.log(contractList,'contractList');
        request({ ...apis.taEcontract.batchDeleteContractTemplate, data: contractList, }).then((data) => {
          message.info("操作成功")
          getList({ pageNum: 1, pageSize: 10 });
        }).catch((err) => {
          // message.info(err.msg)
        })
      },
    });
  }

  const toDetail = (record) => () => {
    router.push({
        pathname: '/eContract/template/detail',
        query: {
          id: record.contractTemplateId
        },
    });
}

  /**
   *
   *
   * @param {*} props
   * @returns
   */
  const columns = [
    {
      title: '合同标题',
      dataIndex: 'contractTemplateName',
      key: 'contractTemplateName',
      align: 'center',
      render:  (x, row) => <Navigate onClick={toDetail(row)}>{row.contractTemplateName}</Navigate>,
    },
    {
      title: '新增时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '操作',
      dataIndex: '',
      key: '',
      align: 'center',
      render: withActions((text, record) => [(
          <AuthButton name="admin.eContractTemplate.detail.get" noRight={null}>
            <EditIcon type="look" text="查看详情" onClick={toDetail(record)}></EditIcon>
          </AuthButton>
      ),])
    },
  ];
  const getSignList = dynamicId => {
    router.push({
      pathname: '/activity/SignList',
      query: {
        dynamicId,
      },
    });
  }

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

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

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

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

  const { getFieldDecorator } = props.form
  return (

    <>
      {/* style={{ display: 'none' }} */}
      <div id="qrcode"></div>
      <Form layout="inline" onSubmit={e => handleSubmit(e)}>
        <Form.Item>
          {getFieldDecorator('contractTemplateName')(
             <Input
             prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
             placeholder="合同标题"
           />,
          )}
        </Form.Item>
        <Form.Item>
          <AuthButton name="admin.buildingDynamic.search" noRight={null}>
            <Button type="primary" htmlType="submit" className={styles.searchBtn}>
              搜索
            </Button>
          </AuthButton>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
      <AuthButton name="admin.eContractTemplate.add.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={toAdd()}>新增</Button>
      </AuthButton>
      <AuthButton name="admin.eContractTemplate.del" noRight={null}>
        <Button type="primary" className={styles.addBtn} onClick={toDel()} style={{marginLeft:'30px'}}>删除</Button>
      </AuthButton>
      <Table rowSelection={rowSelection}
       dataSource={data.records} columns={columns} pagination={false} rowKey={r => r.contractTemplateId} />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={e => changePageNum(e)} current={data.current}/>
      </div>
      {/* <RaiseHelpDoc visible={showHelp} onCancel={() => setShowHelp(false)} /> */}
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
