import React, { useCallback, useEffect, useState } from "react";
import styles from "./index.module.scss";
import { Button, Checkbox, Empty, Modal } from "antd";
import { A1_APIdownBtnOk, A1_APIgetDownList } from "@/store/action/A1Project";
import { A1getStorage, A1setStorage } from "@/utils/storage";
import { MessageFu } from "@/utils/message";
import { urlChangeFu } from "@/utils/authFilesLook";

type SelectType = {
  attrId: number;
  name: string;
  hasUpload: boolean;
  done: boolean;
};

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

function A1Down({ downId, closeFu }: Props) {
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A1_APIgetDownList(id);
    if (res.code === 0) {
      let arr: SelectType[] = res.data.filter((v: SelectType) => v.hasUpload);

      const storeIds = A1getStorage();

      if (storeIds) {
        arr = arr.map((v) => ({
          ...v,
          done: storeIds.includes(v.attrId) ? true : false,
        }));
      }

      setCheckedList(arr);
    }
  }, []);

  useEffect(() => {
    getInfoFu(downId.id);
  }, [getInfoFu, downId.id]);

  const [checkedList, setCheckedList] = useState([] as SelectType[]);

  // 全选的状态
  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.attrId === 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(async () => {
    const obj = {
      projectId: downId.id,
      attrId: checkedList.map((v) => v.attrId),
    };

    const res = await A1_APIdownBtnOk(obj);

    if (res.code === 0) {
      urlChangeFu(res.data, true, undefined, downId.txt);
      // 清空所有选中状态
      setCheckedList(
        checkedList.map((v) => ({
          ...v,
          done: false,
        }))
      );
    }
  }, [checkedList, downId.id, downId.txt]);

  // 点击保存设置 到 本地
  const clickStoreFu = useCallback(() => {
    const arr = checkedList.filter((v) => v.done).map((v) => v.attrId);
    A1setStorage(arr);
    MessageFu.success("保存设置到本地成功!");
  }, [checkedList]);

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

        {checkedList.length ? (
          <div className="A1DownMainC">
            {checkedList.map((v) => (
              <div className="A1DownMainCRow" key={v.attrId} title={v.name}>
                <Checkbox
                  onChange={(e) => onChange(e.target.checked, v.attrId)}
                  checked={v.done}
                >
                  {v.name}
                </Checkbox>
              </div>
            ))}
          </div>
        ) : (
          <>
            <br />
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          </>
        )}

        <div className="A1DownBtn">
          {checkedList.length ? (
            <div className="A1DownBtn1" onClick={clickStoreFu}>
              <Button disabled={checkedList.filter((v) => v.done).length < 1}>
                保存设置
              </Button>
            </div>
          ) : (
            <span></span>
          )}

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

const MemoA1Down = React.memo(A1Down);

export default MemoA1Down;
