import React, { useState, useRef, useEffect, useMemo } from 'react';
import { history } from 'umi';
import { Form, Input, Popconfirm, Select, Button, Modal, InputNumber, message, Col, Row, DatePicker } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import locale from 'antd/es/date-picker/locale/zh_CN';
import PageTable from '@/components/PageTable';
import { saveInvoiceFill, updateInvoiceFill, getInvoiceFillDetail } from '@/services/invoiceFill'
import { saveInvoiceItemTpl, getInvoiceItemTplList, deleteInvoiceItemTpl } from '@/services/invoiceItemTpl'
import QRCode from './QRCode'


const FormItem = Form.Item;
const { Option } = Select;
const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
const goBack = () => {
  history.goBack();
};
export default (props) => {
  const { invoiceId } = props
  const [form] = Form.useForm();
  const dateFormat = "YYYY-MM-DD HH:mm";
  const [loading, setLoading] = useState(false);
  const [formModel] = Form.useForm();
  const [formData, setFormData] = useState()
  const [editModal, setEditModal] = useState(false);
  const [modelLoading, setModelLoading] = useState(false);
  const actionRef = useRef();


  const qrcodeText = useMemo(() =>
    H5_URL + '#/?invoiceId=' +
    invoiceId,
    [invoiceId]
  )


  //保存班次
  const onSubmit = (data) => {
    var newData = { ...data, endDate: moment(data.endDate).format('YYYY-MM-DD HH:mm:ss') };
    setLoading(true);
    if (invoiceId) {
      updateInvoiceFill(invoiceId, newData)
        .then(() => {
          setLoading(false);
          message.success('数据更新成功');
          goBack();
        })
        .catch((err) => {
          setLoading(false);
          message.error(err.message || err);
        });
    } else {
      saveInvoiceFill(newData)
        .then((res) => {
          setLoading(false);
          message.success('数据保存成功');
          history.replace(`./edit.jsx?id=${res.invoiceId}`);
        })
        .catch((err) => {
          setLoading(false);
          message.error(err.message || err);
        });
    }
  };

  //开票项目弹窗保存
  const Submit = (val) => {
    setModelLoading(true);
    saveInvoiceItemTpl(val, invoiceId).then(res => {
      message.success('添加成功')
      setModelLoading(false)
      actionRef.current.reload()
      onCancel();
    }).catch((err) => {
      setModelLoading(false);
      message.error(err.message || err);
    });
  }
  // 弹窗关闭
  const onCancel = () => {
    setEditModal(false);
    formModel.resetFields()
  }
  //弹起弹窗
  const showModel = () => {
    setEditModal(true);
  }
  //删除开票项目
  const handleDelete = (invoiceItemTplId) => {
    deleteInvoiceItemTpl(invoiceItemTplId).then(res => {
      message.success('删除成功')
      actionRef.current.reload()
    }).catch((err) => {
      message.error(err.message || err);
    });
  }

  const actions = () => [
    <Button key="add" type="primary" icon={<PlusOutlined />} onClick={showModel}>
      新增开票项目
    </Button>,
  ];
  useEffect(() => {
    if (invoiceId) {
      getInvoiceFillDetail(invoiceId).then((res) => {
        form.setFieldsValue({ ...res, endDate: moment(res.endDate) })
        setFormData({ ...res, endDate: moment(res.endDate) })
      }).catch((err) => {
        message.error(err.message || err);
      });
    }
  }, [invoiceId])
  const columns = [
    {
      title: '开票项目名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '开票金额',
      dataIndex: 'charge',
      key: 'charge',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <Popconfirm
          key={2}
          title="您是否确认删除 ?"
          onConfirm={() => handleDelete(record.invoiceItemTplId)}
          okText="确定"
          cancelText="取消"
        >
          <Button style={{ padding: 0 }} type="link">
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <>
      <Row>
        <Col span={12}>
          <Form {...formItemLayout} onFinish={onSubmit} form={form}>
            <FormItem label="班次名称" name="name" rules={[{ required: true, message: '请输入班次名称' }]}>
              <Input placeholder="请输入班次名称" style={{ width: '350px' }} />
            </FormItem>
            <FormItem label="截止时间" name="endDate" rules={[{ required: true, message: '请选择班次截止时间' }]}>
              <DatePicker locale={locale} showTime style={{ width: '350px' }} format={dateFormat} />
            </FormItem>
            <FormItem label="状态" name="status" rules={[{ required: true, message: '请选择' }]}>
              <Select placeholder="请选择发布状态" style={{ width: '350px' }}>
                <Option value={1}>进行中</Option>
                <Option value={0}>未发布</Option>
                <Option value={2}>已截止</Option>
              </Select>
            </FormItem>
            {
              invoiceId &&
              <FormItem label='申报二维码' >
                <QRCode text={qrcodeText} title={formData?.name} />
              </FormItem>
            }
            <FormItem label=" " colon={false}>
              <Button type="default" onClick={goBack}>
                返回
              </Button>
              <Button type="primary" loading={loading} htmlType="submit" style={{ marginLeft: '4em' }}>
                保存
              </Button>
            </FormItem>
          </Form>
        </Col>
        {
          invoiceId &&
          <Col span={12}>
            开票项目
            <PageTable
              request={getInvoiceItemTplList}
              toolBarRender={actions}
              actionRef={actionRef}
              columns={columns}
              rowKey="invoiceItemTplId"
              options={false}
              search={false}
              params={{ invoiceId }}
            />
          </Col>
        }
      </Row>

      <Modal
        forceRender
        title='开票项目新增'
        visible={editModal}
        onCancel={onCancel}
        keyboard={false}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <Form {...formItemLayout} onFinish={Submit} form={formModel}>
          <FormItem label="开票项目名称" name="name" rules={[{ required: true, message: '请输入' }]}>
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem label="开票金额" name="charge" rules={[{ required: true, message: '请输入' }]}>
            <InputNumber min={0} placeholder="请输入" style={{ width: '100%' }} />
          </FormItem>
          <FormItem label=" " colon={false}>
            <Button type="default" onClick={onCancel}>
              取消
            </Button>
            <Button
              type="primary"
              loading={modelLoading}
              htmlType="Submit"
              style={{ marginLeft: '4em' }}
            >
              确认
            </Button>
          </FormItem>
        </Form>
      </Modal>
    </>
  )
}