import React, { useState, useEffect } from 'react';
import {
  InputNumber,
  message,
  Modal,
  Calendar,
  Popover,
  Form,
  Input,
  Row,
  Col,
  List,
  Button,
} from 'antd';
import styles from './index.less';
import moment from 'moment';

function CalendarModal(props) {
  const {
    allType,
    projectList,
    visible,
    onOk,
    onCancel,
    data,
    title,
    footer,
    loading,
  } = props;
  const [form] = Form.useForm();
  const [type, setType] = useState({});
  const [edit, setEdit] = useState(false);
  const [validRange, setValidRange] = useState(null);
  const [current, setCurrent] = useState({
    date: null,
    list: [],
  });
  const handleOk = () => {
    form.validateFields().then((values) => {
      let params = [];
      Object.keys(values).forEach((type_id) => {
        if (type_id == 'comment') return;
        let item = values[type_id];
        params.push({
          type_id: Number(type_id),
          comment: values.comment,
          data: data.time.map((obj) => ({
            id: obj.id,
            project_id: Number(obj.project_id),
            workload: item[obj.time],
            day: obj.time,
          })),
        });
      });
      onOk(params);
    });
  };
  const itemRender = (item) => {
    let name;
    if (item.project_id == '0') {
      let pid = allType[item.type_id].parent_id;
      name = allType[pid].name;
    } else {
      name = projectList.find((p) => p.ID == item.project_id)?.Name;
    }
    // if (edit) {
    //   return (
    //     <div>
    //       {allType[item.type_id].name}
    //       {form.getFieldDecorator(`${item.type_id}.${item.time}`, {
    //         initialValue: item?.workload,
    //       })(<InputNumber min={0} max={8}></InputNumber>)}
    //     </div>
    //   );
    // } else {
    return (
      <div>
        {name}-{allType[item.type_id].name}:{item.workload}小时
      </div>
    );
    // }
  };

  const dateCellRender = (value) => {
    let current = value.format('YYYY-MM-DD');
    let list = data.time.filter((item) => item.time == current);
    let total = list.reduce((total, item) => total + item.workload, 0);
    if (list.length == 0) return;
    // if (!edit) {
    return (
      <Popover content={<div>{list.map(itemRender)}</div>}>
        本日工时: {total}{' '}
      </Popover>
    );
    // } else {
    //   return <div>{list.map(itemRender)}</div>;
    // }
  };

  const onChangeDate = (value) => {
    let time = value.format('YYYY-MM-DD');
    setCurrent({
      date: value,
      list: data.time.filter((item) => item.time == time),
    });
  };

  useEffect(() => {
    if (data.time.length == 0) return;
    let month = moment(data.time[0].ts).month();
    let start = moment().month(month).date(1);
    let end = moment()
      .month(month + 1)
      .date(0);
    setValidRange([start, end]);

    let time = moment(data.date).format('YYYY-MM-DD');
    setCurrent({
      date: moment(data.date),
      list: data.time.filter((item) => item.time == time),
    });
  }, [data.time]);

  return (
    <Modal
      width={1400}
      title={`${data.date}工时`}
      open={visible}
      confirmLoading={loading}
      onCancel={onCancel}
      maskClosable={false}
      onOk={handleOk}
      footer={footer}
      destroyOnClose
    >
      <Row gutter={8}>
        <Col span={18}>
          <Calendar
            validRange={validRange}
            value={current.date}
            headerRender={() => {}}
            cellRender={dateCellRender}
            onChange={onChangeDate}
          />
        </Col>
        <Col span={6}>
          <Button>添加</Button>
          {current.list.map((item) => (
            <Form.Item
              label={item.TypeInfo?.name}
              name={`${item.type_id}.${item.time}`}
              initialValue={item?.workload}
            >
              <InputNumber min={0} max={8} disabled={!edit} />
            </Form.Item>
          ))}
          <Form.Item
            label="日志"
            name="comment"
            initialValue={current.list[0]?.comment}
          >
            <Input.TextArea rows={5} disabled={!edit} />
          </Form.Item>

          <div className={styles.btns}>
            {edit ? (
              <>
                <Button
                  onClick={() => {
                    form.resetFields();
                    setEdit(false);
                  }}
                >
                  取消
                </Button>
                <Button onClick={() => setEdit(false)} type="primary">
                  保存
                </Button>
              </>
            ) : (
              <Button type="primary" onClick={() => setEdit(true)}>
                编辑
              </Button>
            )}
          </div>
        </Col>
      </Row>
    </Modal>
  );
}

export default CalendarModal;
