import React, { useState, useRef, useEffect } from 'react';
import { Form, Input, Popconfirm, Select, Button, Modal, InputNumber, message, Col, Row, Card } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { saveInvoiceFill, updateInvoiceFill, getInvoiceFillDetail } from '@/services/invoiceFill'
import { saveInvoiceItemTpl, updateInvoiceItemTpl, getInvoiceItemTplDetail,getInvoiceItemTplList,deleteInvoiceItemTpl } from '@/services/invoiceItemTpl'
import { history } from 'umi';
import PageTable from '@/components/PageTable';

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 [loading, setLoading] = useState(false);
  const [formModel] = Form.useForm();
  const [editModal, setEditModal] = useState(false);
  const [modelLoading, setModelLoading] = useState(false);
  const [regionId, setRegionId] = useState();
  const [invoiceItem, setinvoiceItem] = useState();
  const actionRef = useRef();

  //保存班级
  const onSubmit = (data) => {
    var newData = { ...data };
    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);
    if (invoiceItem) {
      updateInvoiceItemTpl(invoiceItem.itemId,{...invoiceItem,...val,invoiceId:invoiceId}).then((res)=>{
        message.success('修改成功')
        setModelLoading(false)
        actionRef.current.reload()
        onCancel()
      }).catch((err) => {
        setModelLoading(false);
        message.error(err.message || err);
      });
    } else{
      saveInvoiceItemTpl({...val,invoiceId:invoiceId}).then(res=>{
        message.success('添加成功')
        setModelLoading(false)
        actionRef.current.reload()
        onCancel();
      }).catch((err) => {
        setModelLoading(false);
        message.error(err.message || err);
      });
    }
  }
  // 弹窗关闭
  const onCancel = () => {
    setEditModal(false);
    setinvoiceItem()
  }
  //弹起弹窗
  const showModel = (id) => {
    if (id) {
      getInvoiceItemTplDetail(id).then((res) => {
        formModel.setFieldsValue(res)
        setinvoiceItem(res)
        setEditModal(true);
      }).catch((err) => {
        message.error(err.message || err);
      });
    } else {
      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)
      }).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) => [
        <Button
          style={{ padding: 0 }}
          type="link"
          key={1}
          onClick={() => showModel(record.invoiceItemTplId)}
        >
          编辑
        </Button>,
        <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="status" rules={[{ required: true, message: '请选择' }]}>
              <Select placeholder="请选择发布状态" style={{ width: '350px' }}>
                <Option value={1}>发布</Option>
                <Option value={0}>未发布</Option>
              </Select>
            </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>
        <Col span={12}>
          报销项目
          <PageTable
            request={getInvoiceItemTplList}
            toolBarRender={actions}
            actionRef={actionRef}
            columns={columns}
            rowKey="ItemId"
            options={false}
            search={false}
            params={{invoiceId}}
          />
        </Col>
      </Row>
      <Modal
        forceRender
        title={invoiceItem ? '报销项目编辑' : '报销项目新增'}
        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>
    </>
  )
}