import { Modal, Form, Input, Button, Row, Col, message } from "antd";
import React, { useEffect, useState } from "react";

import { PlusOutlined, MinusOutlined } from "@ant-design/icons";
import { PropsType } from "~/common/interface/modal";
import { categoryDec } from "~/api/modules/goods";
import { CategoryManageAPI } from "~/api";

interface selfPropsType {
  directoryList: categoryDec[];
  refreshDec: Function;
}

const AddOrEditDec: React.FC<PropsType & selfPropsType> = ({
  isModalVisible,
  handleOk,
  handleCancel,
  directoryList,
  refreshDec,
}) => {
  const [form] = Form.useForm<any>();
  // 表单目录标题列表
  const [addOrEditDirectoryList, setAddOrEditDirectoryList] = useState<
    categoryDec[]
  >([]);
  // 是否点击删除按钮
  const [isClickDle, setIsClickDle] = useState<boolean>(false);
  useEffect(() => {
    if (directoryList.length != 0 && !isClickDle) {
      setAddOrEditDirectoryList(directoryList);
      const defaultFormValue = directoryList.reduce(
        (pre: any, cur: categoryDec) => {
          Object.keys(cur).map((item: string) => {
            if (item === "id") {
              pre[cur[item]] = cur.sortName;
            }
          });
          return pre;
        },
        {}
      );
      form.setFieldsValue(defaultFormValue);
    }
  }, [directoryList]);
  // 新增或修改目录
  const addDirectoryTitle = () => {
    const decList: categoryDec[] = [...addOrEditDirectoryList].sort(
      (a: categoryDec, b: categoryDec) => a.id - b.id
    );
    setAddOrEditDirectoryList([
      ...addOrEditDirectoryList,
      {
        id: decList[decList.length - 1].id + 1,
        defaultType: 1,
        sortName: "",
      },
    ]);
  };
  // 删除目录
  const deleteDirectory = async (id: number) => {
    const bol: boolean = directoryList.some(
      (item: categoryDec) => item.id === id
    );
    const index = addOrEditDirectoryList.findIndex(
      (item: categoryDec) => item.id === id
    );
    if (bol) {
      const res: any = await CategoryManageAPI.removeDirectory(id);
      if (res.code === "200") {
        message.success("删除成功");
        setIsClickDle(true);
        refreshDec(id);
      } else {
        return message.warning(res.message);
      }
    }
    const obj: any = {};
    obj[id] = undefined;
    form.setFieldsValue(obj);
    addOrEditDirectoryList.splice(index, 1);
    setAddOrEditDirectoryList([...addOrEditDirectoryList]);
  };
  const directorySureEvent = () => {
    form.validateFields().then(async (value: any) => {
      const requestList = Object.keys(value).reduce((pre: any, cur: string) => {
        const bol: boolean = directoryList.some(
          (item: any) => item.id === Number(cur)
        );
        if (bol) {
          pre.push({
            id: Number(cur),
            directoryName: value[cur],
          });
        } else {
          pre.push({
            directoryName: value[cur],
          });
        }
        return pre;
      }, []);
      const res: any = await CategoryManageAPI.addOrEditDirectory(requestList);
      if (res.code === "200") {
        message.success("操作成功");
        form.resetFields();
        setIsClickDle(false);
        handleOk();
      } else {
        message.warning(res.message);
      }
    });
  };
  const directoryCancel = () => {
    form.resetFields();
    setIsClickDle(false);
    handleCancel();
  };
  return (
    <Modal
      title="目录管理"
      visible={isModalVisible}
      onOk={directorySureEvent}
      onCancel={directoryCancel}
    >
      <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
        <Form.Item
          label="添加目录"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
        >
          <Button icon={<PlusOutlined />} onClick={addDirectoryTitle} />
        </Form.Item>
        {addOrEditDirectoryList.map((item: categoryDec) => (
          <Row key={item.id} gutter={{ xs: 8, sm: 16, md: 24 }}>
            <Col span={16}>
              <Form.Item
                label="目录名称"
                name={item.id}
                rules={[{ required: true, message: "请输入目录名称" }]}
              >
                <Input placeholder="请输入目录名称" maxLength={30} />
              </Form.Item>
            </Col>
            <Col>
              {item.defaultType ? (
                <Button
                  icon={<MinusOutlined />}
                  type="primary"
                  onClick={() => deleteDirectory(item.id)}
                />
              ) : (
                ""
              )}
            </Col>
          </Row>
        ))}
      </Form>
    </Modal>
  );
};

export default AddOrEditDec;
