import React from 'react';
import dayjs from 'dayjs';
import { EditOutlined } from '@ant-design/icons';
import { Card, Tabs, Button, Form, Input, DatePicker } from 'antd';
import { ModalForm } from '@ant-design/pro-components';
import { postTaCheck, putTaCheck } from '@/service/tacheck';
import { useNavigate } from "react-router-dom";

export default (props) => {
  const navigate = useNavigate();
  const { checkInfo, onChange, onTabChange } = props;

  const [open, setOpen] = React.useState(false);
  const [form] = Form.useForm();

  const onEdit = () => {
    setOpen(true);
  }

  const title = checkInfo ? checkInfo.title : <div onClick={onEdit}>点击编辑创建</div>;
  const dateStr = checkInfo ? `${checkInfo.startDate} ~ ${checkInfo.endDate}` : '';

  const onFinish = async (values) => {
    const data = {
      ...values,
      startDate: dayjs(values.startDate).format('YYYY-MM-DD'),
      endDate: dayjs(values.endDate).format('YYYY-MM-DD'),
    }

    if (!checkInfo) {
      const res = await postTaCheck(data);
      onChange(res);
    } else {
      const res = await putTaCheck(checkInfo.checkId, data);
      onChange(res);
    }

    return true;
  }

  React.useEffect(() => {
    if (checkInfo) {
      form.setFieldsValue({
        ...checkInfo,
        startDate: dayjs(checkInfo.startDate),
        endDate: dayjs(checkInfo.endDate),
      });
    }
  }, [checkInfo]);

  return (
    <Card bodyStyle={{ padding: 0 }}>
      <div style={{ display: 'flex', padding: '1em', alignItems: 'center' }}>
        <div style={{ flex: 'none' }}><Button type="link" onClick={onEdit} icon={<EditOutlined />} /></div>
        <div style={{ flex: 'none', margin: '0 1em' }}>{dateStr}</div>
        <div style={{ flex: '1', fontSize: '1.6em' }}>{title}</div>
        <div style={{ flex: 'none', fontSize: '1.6em' }}><Button type="primary" onClick={() => navigate(-1)}>返回</Button></div>
      </div>
      <Tabs
        defaultActiveKey='1'
        onChange={onTabChange}
        tabBarStyle={{ margin: '0 2em' }}
        items={[
          {
            label: '实地测评',
            key: '1',
          },
          {
            label: '问卷调查',
            key: '2',
          }
        ]}
      />
      <ModalForm title="测评维护" open={open} width={480} form={form} onFinish={onFinish} onOpenChange={setOpen}>
        <Form.Item name="title" label="测评名称" required>
          <Input placeholder="请输入测评名称" />
        </Form.Item>
        <Form.Item name="startDate" label="开始时间" required>
          <DatePicker placeholder="请选择" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item name="endDate" label="结束时间" required>
          <DatePicker placeholder="请选择" style={{ width: '100%' }} />
        </Form.Item>
      </ModalForm>
    </Card>
  )
}
