import { forwardRef, useImperativeHandle, useState, useRef, createContext, useContext, useEffect } from "react";
import { Modal, Form, Input, InputNumber, Button, message, Row, Col, Card, Flex, Switch, Tabs, FormInstance } from "antd";
import { useMutation } from "@tanstack/react-query";
import { GetVqdConfigDefault } from "../api/config";
import { CreateVqdTimeTemplate, UpdateVqdTimeTemplate, } from "../api/vqdtimetemplate";
import type { CreateVqdTimeTemplateReq, VqdTimeTemplateItem } from "../types/vqdtimetemplate";
import { useGlobal } from "../Context";

const week = [
  '星期一',
  '星期二',
  '星期三',
  '星期四',
  '星期五',
  '星期六',
  '星期日',
];

const hour = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
  22, 23,
];

const gridStyle: React.CSSProperties = {
  border: '0.1px solid #ccc',
  textAlign: 'center',
  lineHeight: '40px',
  userSelect: 'none',
};
const titleStyle: React.CSSProperties = {
  border: '0.1px solid #ccc',
  width: '90px',
  textAlign: 'center',
  lineHeight: '40px',
  userSelect: 'none',
};
type PlansSpan = {
  start: string;
  end: string;
};

export const emptyList = [
  Array(24).fill(0),
  Array(24).fill(0),
  Array(24).fill(0),
  Array(24).fill(0),
  Array(24).fill(0),
  Array(24).fill(0),
  Array(24).fill(0),
];
interface AddVqdTimeTemplateProps {
  title: string;
  onSuccess: () => void;
}
interface IAddTemplateContext {
  editing: boolean;
  checkList: number[][];
  form: FormInstance<CreateVqdTimeTemplateReq>;
  setCheckList: React.Dispatch<React.SetStateAction<number[][]>>;
  onDelPullDeviceData: (index: number) => void;
}
const layout = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
};
const AddTemplateContext = createContext<IAddTemplateContext | null>(null);
const useAddTemplate = () => {
  const context = useContext(AddTemplateContext);
  if (!context) {
    throw new Error('useAddTemplate must be used within a AddTemplateProvider');
  }
  return context;
};
export interface AddVqdTimeTemplateRef {
  open: (task?: VqdTimeTemplateItem) => void;
}

const AddVqdTimeTemplate = forwardRef<AddVqdTimeTemplateRef, AddVqdTimeTemplateProps>(
  ({ title, onSuccess }, ref) => {
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<boolean>(false);
    const [checkList, setCheckList] = useState<number[][]>([...emptyList.map((list) => [...list])]);

    const [form] = Form.useForm();
    const { ErrorHandle } = useGlobal();

    const arrayToString = (arr: number[][]): string => {
      return arr.map((subArr) => subArr.join('')).join('');
    }
    const parsePlans = (value: string | undefined): number[][] => {
      const result: number[][] = [];
      if (!value) return result;
      const binaryArray: number[] = value.split('').map(Number);
      while (binaryArray.length) {
        result.push(binaryArray.splice(0, 24));
      }
      return result;
    };
    const onChange = (key: string) => {
      console.log(key);
    };
    const { mutate: getVqdConfigDefault } = useMutation({
      mutationFn: GetVqdConfigDefault,
      onSuccess: (res) => {
        const formValues = {
          vqd_config: {
            enable: false,
            frm_num: res.data.frm_num,
            is_deep_learn: res.data.is_deep_learn,
          },
          enable: true,
          plans: '',
          des: '',
          name: '',
          vqd_lgt_dark: res.data.vqd_lgt_dark,
          vqd_blue: res.data.vqd_blue,
          vqd_clarity: res.data.vqd_clarity,
          vqd_shark: res.data.vqd_shark,
          vqd_freeze: res.data.vqd_freeze,
          vqd_color: res.data.vqd_color,
          vqd_occlusion: res.data.vqd_occlusion,
          vqd_noise: res.data.vqd_noise,
          vqd_contrast: res.data.vqd_contrast,
          vqd_mosaic: res.data.vqd_mosaic,
          vqd_flower: res.data.vqd_flower,
        };
        formValues.vqd_lgt_dark.enable = false
        formValues.vqd_blue.enable = false
        formValues.vqd_clarity.enable = false
        formValues.vqd_shark.enable = false
        formValues.vqd_freeze.enable = false
        formValues.vqd_color.enable = false
        formValues.vqd_occlusion.enable = false
        formValues.vqd_noise.enable = false
        formValues.vqd_contrast.enable = false
        formValues.vqd_mosaic.enable = false
        formValues.vqd_flower.enable = false
        form.setFieldsValue(formValues);
      },
      onError: ErrorHandle,
    });
    useImperativeHandle(ref, () => ({
      open: (task?: VqdTimeTemplateItem) => {
        if (task) {
          setEditing(true);
          const formValues = {
            name: task.name,
            id: task.id,
            plans: task.plans,
            enable: task.enable,
            des: task.des,
          };
          setCheckList(parsePlans(task.plans))
          form.setFieldsValue(formValues);
        } else {
          getVqdConfigDefault()
          setEditing(false);
          form.resetFields();
          form.setFieldsValue({

          });
        }
        setOpen(true);
      },
    }));

    const { mutate: createMutate, isPending: creating } = useMutation({
      mutationFn: CreateVqdTimeTemplate,
      onSuccess: () => {
        message.success("创建成功");
        handleClose();
        onSuccess?.();
      },
      onError: ErrorHandle,
    });

    const { mutate: updateMutate, isPending: updating } = useMutation({
      mutationFn: UpdateVqdTimeTemplate,
      onSuccess: () => {
        message.success("更新成功");
        handleClose();
        onSuccess?.();
      },
      onError: ErrorHandle,
    });

    const handleClose = () => {
      setOpen(false);
      setEditing(false);
      setCheckList([...emptyList.map((list) => [...list])])
      form.resetFields();
    };
    const onDelPullDeviceData = (index: number) => {

    }
    return (
      <AddTemplateContext.Provider
        value={{
          form,
          checkList,
          editing,
          setCheckList,
          onDelPullDeviceData
        }}
      >
        <Modal
          // style={{ top: '-180px' }} // 距离顶部 80px（可改为 10% 等百分比）
          title={title}
          width={"64%"}
          open={open}
          onCancel={handleClose}
          destroyOnHidden={true}
          centered
          onOk={() => form.submit()}
          confirmLoading={creating || updating}
        >
          <Form
            form={form}
            {...layout}
            onFinish={(values: CreateVqdTimeTemplateReq) => {
              if (creating || updating) return
              const payload = values as CreateVqdTimeTemplateReq;
              payload.plans = arrayToString(checkList)
              console.log(payload);
              if (editing) {
                const id = (values as any).id;
                updateMutate({ id: String(id), ...payload });
              } else {
                createMutate(payload);
              }
            }}
          >
            <br />
            <Flex gap="large"  >

              <Form.Item
                style={{ width: '30%' }}
                name="name"
                label="计划名称"
                rules={[{ required: true, message: "请输入计划名称" }]}
              >
                <Input placeholder="请输入名称" />
              </Form.Item>

              <Form.Item
                style={{ width: '30%' }}
                name="des"
                label="描述"
              >
                <Input placeholder="请输入描述" />
              </Form.Item>
              <Form.Item
                style={{ width: '20%' }}
                name="enable"
                label="启用"
              >
                <Switch />
              </Form.Item>
            </Flex>
            <TemplatePlans />
            {editing && (
              <Form.Item name="id" hidden>
                <Input />
              </Form.Item>
            )}
          </Form>
        </Modal>
      </AddTemplateContext.Provider>
    );
  }
);

export default AddVqdTimeTemplate;




const TemplatePlans: React.FC = () => {
  const {
    checkList,
    editing,
    setCheckList,
    form,
  } = useAddTemplate();
  // 开始滑动选择
  const [config, setConfig] = useState<{
    start: boolean;
  }>({ start: false });

  const selector = useRef<boolean>(true);

  const [coping, setCoping] = useState<
    { index: number; value: number[] } | undefined
  >();

  const handler = (list: number[]) => {
    let out: PlansSpan[] = [];
    let start = false;
    let timeParam: PlansSpan = { start: '', end: '' };
    for (let i = 0; i < list.length; i++) {
      const v = list[i];

      let s = i.toString().padStart(2, '0');
      if (i == 23 && v == 1) {
        s = '24';
      }

      if (!start && v == 1) {
        start = true;
        timeParam = { start: `${i}:00`, end: '' };
      }

      if (start && (v == 0 || i == list.length - 1)) {
        start = false;
        timeParam.end = `${s}:00`;
        out.push(timeParam);
      }
    }
    return out;
  };

  return <>
    <div style={{ border: '1px solid #999' }}>
      <Row wrap={false}>
        <div
          style={{
            ...titleStyle,
          }}
        >
          Week/Time
        </div>
        <Row wrap={false} style={{ width: '86.5%' }}>
          {[...hour].map((v, idx) => {
            return (
              <Col key={v} span={1} style={gridStyle}>
                {v}
              </Col>
            );
          })}
        </Row>
      </Row>
      {week.map((v, weekIdx) => {
        return (
          <Row
            key={v}
            onMouseDown={() => setConfig({ ...config, start: true })}
            onMouseUp={() => setConfig({ ...config, start: false })}
            wrap={false}
          >
            <div style={titleStyle}>{v}</div>
            <Row key={v + '1'} wrap={false} style={{ width: '86.5%' }}>
              {[...hour].map((v, hourIdx) => {
                // 时间选择
                return (
                  <Col
                    onMouseOver={() => {
                      if (!config.start) return;
                      setCheckList((v) => {
                        let list = [...v];
                        list[weekIdx][hourIdx] = selector.current ? 1 : 0;
                        return list;
                      });
                    }}
                    onMouseDown={() => {
                      selector.current = checkList[weekIdx][hourIdx] == 0;
                      setCheckList((v) => {
                        let list = [...v];
                        list[weekIdx][hourIdx] = selector.current ? 1 : 0;
                        return list;
                      });
                    }}
                    key={v}
                    span={1}
                    style={{
                      ...gridStyle,
                      backgroundColor:
                        checkList[weekIdx][hourIdx] == 1
                          ? '#658EE0'
                          : 'white',
                    }}
                  ></Col>
                );
              })}
              <div
                style={{
                  margin: 'auto',
                  marginLeft: '2px',
                }}
              >
                <Button
                  type={coping?.index == weekIdx ? 'primary' : 'default'}
                  size="small"
                  style={{ padding: '1px 5px', fontSize: '12px' }}
                  onClick={() => {
                    if (!coping) {
                      setCoping({
                        index: weekIdx,
                        value: checkList[weekIdx],
                      });
                      return;
                    }
                    setCheckList((v) => {
                      let list = [...v];
                      list[weekIdx] = [...coping.value];
                      return list;
                    });
                    setCoping(undefined);
                  }}
                >
                  {!coping || coping?.index == weekIdx ? "复制" : "粘贴"}
                </Button>
              </div>
            </Row>
          </Row>
        );
      })}
    </div>

    <div style={{ height: '20px' }}></div>

    <Card>
      <div>
        <span>时间段</span>
      </div>
      <div>
        {week.map((v, weekIdx) => {
          return (
            // 周
            <Row wrap={false} key={v}>
              <div style={{ color: '#9A9A9A', paddingRight: '5px' }}>
                <span>{v}</span> :
              </div>
              <Row wrap={false}>
                {handler(checkList[weekIdx]).map((v, idx, arr) => {
                  // 已选时间段
                  return (
                    <Col key={`${v.start}~${v.end}_${idx}_${weekIdx}`}>
                      {`${v.start}~${v.end}` +
                        (idx < arr.length - 1 ? ',' : '')}
                    </Col>
                  );
                })}
              </Row>
            </Row>
          );
        })}
      </div>
    </Card>
  </>
}