import React, { useCallback, useEffect, useState } from "react";
import styles from "./index.module.scss";
import classNames from "classnames";
import {
  Button,
  Checkbox,
  DatePicker,
  Empty,
  Input,
  Popconfirm,
  Tooltip,
} from "antd";
import {
  PlusCircleOutlined,
  DeleteOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import { TimePicker } from "antd";
import { A1OunitType, A1TimeType } from "@/types";
import dayjs from "dayjs";
import { MessageFu } from "@/utils/message";
import { A1_APIOgetInfo, A1_APIOsave } from "@/store/action/A1Order";
import TextArea from "antd/es/input/TextArea";

const tabArr = [
  { id: 118, name: "南京博物院" },
  { id: 114, name: "扬州中国大运河博物馆" },
];

const dateArr = [
  { id: 1, name: "周一", type: "pcs1" },
  { id: 2, name: "周二", type: "pcs2" },
  { id: 3, name: "周三", type: "pcs3" },
  { id: 4, name: "周四", type: "pcs4" },
  { id: 5, name: "周五", type: "pcs5" },
  { id: 6, name: "周六", type: "pcs6" },
  { id: 0, name: "周日", type: "pcs0" },
] as {
  id: number;
  name: string;
  type: "pcs0" | "pcs1" | "pcs2" | "pcs3" | "pcs4" | "pcs5" | "pcs6";
}[];

type Props = {
  colseFu: () => void;
};

function A1SetOrder({ colseFu }: Props) {
  const [tab, setTab] = useState(118);

  const getInfoFuUnit = useCallback(async (id: number) => {
    const res = await A1_APIOgetInfo(id);

    if (res.code === 0) {
      setRow1(
        res.data.date.map((v: any, i: number) => ({
          id: Date.now() + i,
          time: v.timeScope.split(" - "),
          date: v.weeks.split(",").map((v: string) => Number(v)),
        }))
      );

      setRow2(
        res.data.unableDate.map((v: string, i: number) => ({
          id: Date.now() + i,
          time: v,
        }))
      );

      setUnitArr(res.data.unitPcs);

      setDescription(res.data.bookDesc);
    }
  }, []);

  useEffect(() => {
    getInfoFuUnit(tab);
  }, [getInfoFuUnit, tab]);

  // 是否进入编辑状态
  const [isEdit, setIsEdit] = useState(false);

  // 点击编辑状态的取消
  const clickXFu = useCallback(() => {
    getInfoFuUnit(tab);
    setIsEdit(false);
  }, [getInfoFuUnit, tab]);

  // ----------可预约日期--------------
  const [row1, setRow1] = useState([
    // { id: 1, time: ["04:00", "05:00"], date: [] }
  ] as A1TimeType[]);

  // 点击 + 号
  const addRow1Fu = useCallback(() => {
    if (row1.length >= 3) return MessageFu.warning("最多增加3条可预约日期!");
    setRow1([...row1, { id: Date.now(), time: null, date: [] }]);
  }, [row1]);

  // 时间选择器改变
  const row1OnChangeFu = useCallback(
    (time: any, id: number) => {
      let str: any = null;

      if (time && time.length && time.length > 1) {
        const str1 = dayjs(time[0]).format("HH:mm");
        const str2 = dayjs(time[1]).format("HH:mm");

        if (str1 === str2)
          return MessageFu.warning("开始时间和结束时间不能一样!");
        str = [str1, str2];
      }

      setRow1(
        row1.map((v) => ({
          ...v,
          time: v.id === id ? str : v.time,
        }))
      );
    },
    [row1]
  );

  // 星期勾选的改变
  const row1DateChange = useCallback(
    (val: boolean, id1: number, id2: number) => {
      setRow1(
        row1.map((v) => ({
          ...v,
          date:
            v.id === id1
              ? val
                ? [...v.date, id2]
                : v.date.filter((v2) => v2 !== id2)
              : v.date,
        }))
      );
    },
    [row1]
  );

  // 点击删除
  const delRow1Fu = useCallback(
    (id: number) => {
      setRow1(row1.filter((v) => v.id !== id));
    },
    [row1]
  );

  // ---------------不可预约日期---------------
  const [row2, setRow2] = useState([
    // {id:1,time:''}
  ] as {
    id: number;
    time: string | null;
  }[]);

  const row2ChangeFu = useCallback(
    (_: any, val: string, id: number) => {
      if (row2.some((v) => v.time === val) && val !== "")
        return MessageFu.warning("不可预约日期不能相同!");
      setRow2(
        row2.map((v) => ({
          ...v,
          time: v.id === id ? val : v.time,
        }))
      );
    },
    [row2]
  );

  // ---------------单日人数限制---------------
  const [unitArr, setUnitArr] = useState([] as A1OunitType[]);

  const row3ChangeFu = useCallback(
    (
      val: string,
      id: number,
      type: "pcs0" | "pcs1" | "pcs2" | "pcs3" | "pcs4" | "pcs5" | "pcs6"
    ) => {
      let txt = val;
      // if (Number(txt) > 999) txt = "999";
      txt = txt.replace(/^(0+)|[^\d]+/g, "");
      // if (Number(txt) === 0) txt = "1";

      setUnitArr(
        unitArr.map((v) => ({
          ...v,
          [type]: v.id === id ? Number(txt) : v[type],
        }))
      );
    },
    [unitArr]
  );

  // ---------------备注---------------
  const [description, setDescription] = useState("");

  // 点击确定
  const clickOkFu = useCallback(async () => {
    // 可预约日期的数据整理
    const arr1 = row1.filter((v) => v.time);
    if (arr1.length <= 0) return MessageFu.warning("至少添加一条可预约日期!");

    // 不可预约日期数据整理
    const arr2 = row2.filter((v) => v.time);

    const obj = {
      date: arr1.map((v) => ({
        timeScope: v.time![0] + " - " + v.time![1],
        weeks: v.date.join(","),
      })),
      description,
      exhibitionId: tab,
      unableDate: arr2.map((v) => v.time),
      unitPcs: unitArr.map((v) => ({
        unitId: v.unitId,
        pcs0: v.pcs0,
        pcs1: v.pcs1,
        pcs2: v.pcs2,
        pcs3: v.pcs3,
        pcs4: v.pcs4,
        pcs5: v.pcs5,
        pcs6: v.pcs6,
      })),
    };

    const res = await A1_APIOsave(obj);

    if (res.code === 0) {
      MessageFu.success("编辑成功!");
      getInfoFuUnit(tab);
      setIsEdit(false);
    }
  }, [description, getInfoFuUnit, row1, row2, tab, unitArr]);

  return (
    <div className={styles.A1SetOrder}>
      <div className="A1Stab">
        {tabArr.map((v) => (
          <div
            hidden={isEdit && v.id !== tab}
            onClick={() => setTab(v.id)}
            className={classNames(tab === v.id ? "acRow" : "")}
            key={v.id}
          >
            {v.name}
          </div>
        ))}
        &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
        {isEdit ? null : (
          <>
            <Button type="primary" onClick={() => setIsEdit(true)}>
              编辑
            </Button>
            <Button className="A1SbackBtn" onClick={colseFu}>
              返回
            </Button>
          </>
        )}
      </div>
      <div className={classNames("A1Smain", isEdit ? "" : "A1SmainLook")}>
        {/* 取消和确定按钮 */}
        {isEdit ? (
          <div className="A1SmainBtn">
            <Button type="primary" onClick={clickOkFu}>
              确定
            </Button>
            <br />
            <br />
            <br />
            <br />
            <Popconfirm
              title="放弃编辑后，信息将不会保存!"
              okText="放弃"
              cancelText="取消"
              onConfirm={clickXFu}
              okButtonProps={{ loading: false }}
            >
              <Button>取消</Button>
            </Popconfirm>
          </div>
        ) : null}

        {/* 主要内容 */}
        {/* ------------可预约日期----------------- */}
        <div className="A1Srow">
          <div className="A1Srowl">
            <span>*</span> 可预约日期：
          </div>
          <div className="A1Srowr A1Srowr1">
            {/* + 号 */}
            {isEdit ? (
              <div
                className={classNames(
                  "A1Srowr1Add",
                  row1.length >= 3 ? "noClickDis" : ""
                )}
                title="新增"
                onClick={addRow1Fu}
              >
                <PlusCircleOutlined rev={undefined} />
              </div>
            ) : null}

            {/* 标题 */}
            <div className="A1S1Title">
              <div>时段</div>
              {dateArr.map((v) => (
                <div key={v.id}>{v.name}</div>
              ))}
            </div>

            {/* 列表 */}
            {row1.length ? (
              <div className="A1Srow1List">
                {row1.map((v, i) => (
                  <div className="A1Srow1List1" key={v.id}>
                    {isEdit ? (
                      <Popconfirm
                        title="删除后无法恢复，是否删除?"
                        okText="删除"
                        cancelText="取消"
                        onConfirm={() => delRow1Fu(v.id)}
                        okButtonProps={{ loading: false }}
                      >
                        <div
                          title="删除"
                          className="A1Srow1Del"
                          style={{ top: i * 48 + 12 + "px" }}
                        >
                          <DeleteOutlined rev={undefined} />
                        </div>
                      </Popconfirm>
                    ) : null}

                    {/* 时间段的选择 */}
                    <div className="A1Srow1TimeS">
                      <TimePicker.RangePicker
                        format="HH:mm"
                        value={
                          v.time
                            ? [
                                dayjs(v.time[0], "HH:mm"),
                                dayjs(v.time[1], "HH:mm"),
                              ]
                            : null
                        }
                        onChange={(e) => row1OnChangeFu(e, v.id)}
                      />
                    </div>

                    {/* 星期的勾选 */}
                    {dateArr.map((v2) => (
                      <div key={v2.id}>
                        <Checkbox
                          checked={v.date.includes(v2.id)}
                          onChange={(e) =>
                            row1DateChange(e.target.checked, v.id, v2.id)
                          }
                        ></Checkbox>
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </div>
        </div>

        {/* -----------------不可预约日期----------------- */}
        <div className="A1Srow">
          <div className="A1Srowl">
            <span></span> 不可预约日期：
          </div>
          <div className="A1Srowr A1Srowr2">
            {isEdit ? (
              <Button
                disabled={row2.length >= 5}
                type="primary"
                onClick={() => setRow2([...row2, { id: Date.now(), time: "" }])}
              >
                新增
              </Button>
            ) : (
              <>&emsp;&nbsp;&nbsp;</>
            )}

            {row2.length ? (
              <>
                {row2.map((v) => (
                  <div className="A1Srow2Del" key={v.id}>
                    <DatePicker
                      // allowClear={false}
                      style={{ width: 130 }}
                      onChange={(_, val) => row2ChangeFu(_, val, v.id)}
                      value={v.time ? dayjs(v.time) : null}
                      disabledDate={(current) =>
                        current && current < dayjs().subtract(1, "days")
                      }
                    />
                    {isEdit ? (
                      <Popconfirm
                        title="删除后无法恢复，是否删除?"
                        okText="删除"
                        cancelText="取消"
                        onConfirm={() =>
                          setRow2(row2.filter((c) => c.id !== v.id))
                        }
                        okButtonProps={{ loading: false }}
                      >
                        <div title="删除" className="A1Sdel">
                          <DeleteOutlined rev={undefined} />
                        </div>
                      </Popconfirm>
                    ) : null}
                  </div>
                ))}
              </>
            ) : isEdit ? null : (
              <div className="A1SroRow2Null">（空）</div>
            )}
          </div>
        </div>

        {/* -----------------单日人数限制----------------- */}
        <div className="A1Srow">
          <div className="A1Srowl">
            <span>*</span> 单日人数限制：
          </div>
          <div className="A1Srowr A1Srowr3">
            {/* 标题 */}
            <div className="A1S1Title">
              <div>
                发起预约单位 {/* 填写提示 */}
                {isEdit ? (
                  <Tooltip title="请填写0-999的整数，0表示不可预约">
                    <div className="A1Srowr3inco">
                      <ExclamationCircleFilled rev={undefined} />
                    </div>
                  </Tooltip>
                ) : null}
              </div>
              {dateArr.map((v) => (
                <div key={v.id}>{v.name}</div>
              ))}
            </div>
            {/* 列表 */}
            <div className="A1S3List">
              {unitArr.map((v) => (
                <div className="A1S3ListRow" key={v.id}>
                  <div title={v.unitName}>{v.unitName}</div>
                  {/* 星期的勾选 */}
                  {dateArr.map((v2) => (
                    <div className="A1S3ListRowInp" key={v2.id}>
                      <Input
                        value={v[v2.type]}
                        onChange={(e) =>
                          row3ChangeFu(e.target.value, v.id, v2.type)
                        }
                        style={{ width: 80 }}
                        maxLength={3}
                      />
                    </div>
                  ))}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* -----------------备注----------------- */}
        <div className="A1Srow">
          <div className="A1Srowl">
            <span></span> 备注：
          </div>
          <div className="A1Srowr A1Srowr4">
            <TextArea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              autoSize
              placeholder="请输入内容"
              showCount
              maxLength={1000}
            />
          </div>
        </div>
        <br />
        <br />
      </div>
    </div>
  );
}

const MemoA1SetOrder = React.memo(A1SetOrder);

export default MemoA1SetOrder;
