import React, { useState, useEffect } from "react";
import "@ant-design/compatible/assets/index.css";
import { Alert, Modal, Form, message, InputNumber } from "antd";
import { ListResult, SaveParams, saveApi, Staff } from "../api";

const FormItem = Form.Item;
const maxFormProps = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

interface Props {
  visible: boolean;
  onCancel: () => any;
  detail?: ListResult;
}

export default function ConfigModal({ visible, onCancel, detail }: Props) {
  const [form] = Form.useForm();
  console.log("detail", detail);

  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);

  useEffect(() => {
    if (visible) {
      form.resetFields();
      // init form values
      const initialValues: any = {};
      detail?.userInfoVOS?.forEach((user: Staff) => {
        initialValues[user.staffId] = user.manHoursProp;
      });
      form.setFieldsValue(initialValues);
    }
  }, [visible]);

  function handleSubmit(fieldsValue: any) {
    const configItems = detail!.userInfoVOS.map((user: Staff) => ({
      id: user.id,
      staffId: user.staffId,
      staffName: user.staffName,
      manHoursProp: fieldsValue[user.staffId],
    }));
    const sum = configItems.reduce((acc: number, cur: Staff) => acc + cur.manHoursProp, 0);
    if (sum !== 1) {
      message.error("所有人员分成占比之和必须等于1");
      return;
    }

    const params: SaveParams = {
      shopId: detail!.shopId,
      shopName: detail!.shopName,
      teamId: detail!.teamId,
      teamName: detail!.teamName,
      userInfoVOS: configItems,
    };

    setConfirmLoading(true);
    saveApi(params)
      .then(() => {
        message.success("配置成功！");
        setConfirmLoading(false);
        onCancel();
      })
      .catch((e) => {
        setConfirmLoading(false);
        message.error(e.message);
      });
  }

  return (
    <Modal
      title="配置机修组工时分成比例"
      width={640}
      open={visible}
      confirmLoading={confirmLoading}
      onOk={() => form.submit()}
      onCancel={onCancel}
    >
      <Alert message="每人分成占比以小数表示，所有人员分成占比之和必须等于1" type="info" style={{ marginBottom: 20 }} />

      <Form form={form} onFinish={handleSubmit}>
        {detail?.userInfoVOS?.map((user: Staff) => (
          <FormItem
            key={user.id}
            name={user.staffId}
            label={user.staffName}
            rules={[{ required: true, message: "必填" }]}
            {...maxFormProps}
          >
            <InputNumber style={{ width: 200 }} max={1} min={0} step={0.1} defaultValue={user.manHoursProp} />
          </FormItem>
        ))}
      </Form>
    </Modal>
  );
}
