import React, { useCallback, useEffect, useState } from "react";
import styles from "./index.module.scss";
import { Button, Checkbox, Modal } from "antd";

const defaultCheckedList = [
  { id: 1, label: "Apple", done: false },
  { id: 2, label: "Pear", done: false },
  { id: 3, label: "Orange", done: false },
];

type Props = {
  id: number;
  closeFu: () => void;
};

function A1Down({ id, closeFu }: Props) {
  const [checkedList, setCheckedList] = useState(defaultCheckedList);

  // 全选的状态
  const [indeterminate, setIndeterminate] = useState(false);
  const [checkAll, setCheckAll] = useState(false);

  const onCheckAllChange = useCallback(
    (val: boolean) => {
      const newArr = checkedList.map((v) => ({
        ...v,
        done: val,
      }));

      setCheckedList(newArr);
      setCheckAll(val);
    },
    [checkedList]
  );

  const onChange = useCallback(
    (val: boolean, id: number) => {
      setCheckedList(
        checkedList.map((v) => ({
          ...v,
          done: v.id === id ? val : v.done,
        }))
      );
    },
    [checkedList]
  );

  useEffect(() => {
    const newArr = checkedList.filter((v) => v.done);

    setIndeterminate(!!newArr.length && newArr.length < checkedList.length);
    setCheckAll(newArr.length === checkedList.length);
  }, [checkedList]);

  // 点击提交
  const btnOkFu = useCallback(() => {
    console.log("-------", checkedList);
  }, [checkedList]);

  return (
    <Modal
      wrapClassName={styles.A1Down}
      destroyOnClose
      open={true}
      title="xxx项目"
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="A1DownMain">
        <h3>请选择下载的项目文件类型</h3>
        <Checkbox
          indeterminate={indeterminate}
          onChange={(e) => onCheckAllChange(e.target.checked)}
          checked={checkAll}
        >
          全选
        </Checkbox>

        <div className="A1DownMainC">
          {checkedList.map((v) => (
            <div className="A1DownMainCRow" key={v.id} title={v.label}>
              <Checkbox
                onChange={(e) => onChange(e.target.checked, v.id)}
                checked={v.done}
              >
                {v.label}
              </Checkbox>
            </div>
          ))}
        </div>

        <div className="A1DownBtn">
          <div className="A1DownBtn1">
            <Button>保存设置</Button>
          </div>

          <div className="A1DownBtn2">
            <Button onClick={closeFu}>取消</Button>
            &emsp;
            <Button
              type="primary"
              onClick={btnOkFu}
              disabled={checkedList.length < 1}
            >
              提交
            </Button>
          </div>
        </div>
      </div>
    </Modal>
  );
}

const MemoA1Down = React.memo(A1Down);

export default MemoA1Down;
