import { forwardRef, useImperativeHandle, useState, createContext, useContext } from "react";
import { Modal, Form, Input, InputNumber, message, Flex, Switch, FormInstance } from "antd";
import { useMutation } from "@tanstack/react-query";
import { GetVqdConfigDefault } from "../api/config";
import { CreateVqdTaskTemplate, UpdateVqdTaskTemplate, } from "../api/vqdtasktemplate";
import type { CreateVqdTaskTemplateReq, VqdTaskTemplateItem } from "../types/vqdtasktemplate";
import { useGlobal } from "../Context";

interface AddVqdTaskTemplateProps {
  title: string;
  onSuccess: () => void;
}
interface IAddTemplateContext {
  editing: boolean;
  form: FormInstance<CreateVqdTaskTemplateReq>;
  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 AddVqdTaskTemplateRef {
  open: (task?: VqdTaskTemplateItem) => void;
}

const AddVqdTaskTemplate = forwardRef<AddVqdTaskTemplateRef, AddVqdTaskTemplateProps>(
  ({ title, onSuccess }, ref) => {
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<boolean>(false);

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

    const { mutate: getVqdConfigDefault } = useMutation({
      mutationFn: GetVqdConfigDefault,
      onSuccess: (res) => {
        const formValues = {
          name: '',
          des: '',
          vqd_config: {
            enable: false,
            frm_num: res.data.frm_num,
            is_deep_learn: res.data.is_deep_learn,
          },
          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?: VqdTaskTemplateItem) => {
        if (task) {
          setEditing(true);
          const formValues = {
            name: task.name,
            id: task.id,
            des: task.des,
            vqd_config: task.vqd_config,
            vqd_lgt_dark: task.vqd_lgt_dark,
            vqd_blue: task.vqd_blue,
            vqd_clarity: task.vqd_clarity,
            vqd_shark: task.vqd_shark,
            vqd_freeze: task.vqd_freeze,
            vqd_color: task.vqd_color,
            vqd_occlusion: task.vqd_occlusion,
            vqd_noise: task.vqd_noise,
            vqd_contrast: task.vqd_contrast,
            vqd_mosaic: task.vqd_mosaic,
            vqd_flower: task.vqd_flower,
          };
          form.setFieldsValue(formValues);
        } else {
          getVqdConfigDefault()
          setEditing(false);
          form.resetFields();
          form.setFieldsValue({

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

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

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

    const handleClose = () => {
      setOpen(false);
      setEditing(false);
      form.resetFields();
    };
    const onDelPullDeviceData = (index: number) => {

    }
    return (
      <AddTemplateContext.Provider
        value={{
          form,
          editing,
          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: CreateVqdTaskTemplateReq) => {
              if (creating || updating) return
              const payload = values as CreateVqdTaskTemplateReq;

              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>
            </Flex>

            <TemplateConfig />

            {editing && (
              <Form.Item name="id" hidden>
                <Input />
              </Form.Item>
            )}
          </Form>
        </Modal>
      </AddTemplateContext.Provider>
    );
  }
);

export default AddVqdTaskTemplate;

const BoxInputNumber: React.FC<{
  parent: string;
  children: string;
  defaultValue: number
  labelName: string;
}> = ({ parent, children, defaultValue, labelName }) => {
  return (
    <Form.Item
      className="mb-1"
      name={[parent, children]}
      label={labelName}
      normalize={(value) => {
        return value ? parseFloat(value) : defaultValue;
      }}
    >
      <InputNumber
        size="small"
        defaultValue={defaultValue}
        min={0}
        max={1}
        step={0.1}
        stringMode
      />
    </Form.Item>
  );
};
const TemplateConfig: React.FC = () => {
  const {
    editing,
    form,
  } = useAddTemplate();

  const handleValuesChange = (value: string) => {
    if (value) {
      // form.setFieldsValue({  });
    }
  };
  return <>
    <Flex gap="large" wrap justify="space-between">
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade" >
          <h4>基础配置</h4>
          <Form.Item
            className="mb-0"
            name={['vqd_config', 'enable']}
          >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <Form.Item
            className="mb-1"
            name={['vqd_config', 'is_deep_learn']}
            label="深度学习"
          >
            <Switch size="small" />
          </Form.Item>
          <Form.Item
            className="mb-1"
            name={['vqd_config', 'frm_num']}
            label="连续分析帧数"
          >
            <InputNumber min={2} max={64} defaultValue={10} size="small" />
          </Form.Item>
        </div>
      </Flex>

      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>蓝屏检查</h4>
          <Form.Item className="mb-0" name={['vqd_blue', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_blue" children="blue_thr" defaultValue={0.6} labelName="判断阈值" />
          <BoxInputNumber parent="vqd_blue" children="blue_abn_num_ratio" defaultValue={0.5} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>清晰度检查</h4>
          <Form.Item className="mb-0" name={['vqd_clarity', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_clarity" children="clarity_thr" defaultValue={0.4} labelName="判断阈值" />
          <BoxInputNumber parent="vqd_clarity" children="clarity_abn_num_ratio" defaultValue={0.5} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>抖动检查</h4>
          <Form.Item className="mb-0" name={['vqd_shark', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_shark" children="shark_thr" defaultValue={0.2} labelName="阈值参数" />
          <BoxInputNumber parent="vqd_shark" children="shark_abn_num_ratio" defaultValue={0.2} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>冻结检测</h4>
          <Form.Item className="mb-0" name={['vqd_freeze', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_freeze" children="freeze_thr" defaultValue={0.4} labelName="阈值参数" />
          <BoxInputNumber parent="vqd_freeze" children="freeze_abn_num_ratio" defaultValue={0.9} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>偏色检测</h4>
          <Form.Item className="mb-0" name={['vqd_color', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_color" children="color_thr" defaultValue={0.2} labelName="偏色判断值" />
          <BoxInputNumber parent="vqd_color" children="color_abn_num_ratio" defaultValue={0.5} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>遮挡检测</h4>
          <Form.Item className="mb-0" name={['vqd_occlusion', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_occlusion" children="occlusion_thr" defaultValue={0.1} labelName="判断阈值" />
          <BoxInputNumber parent="vqd_occlusion" children="occlusion_abn_num_ratio" defaultValue={0.5} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>马赛克检测</h4>
          <Form.Item className="mb-0" name={['vqd_mosaic', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_mosaic" children="mosaic_thr" defaultValue={0.1} labelName="阈值参数" />
          <BoxInputNumber parent="vqd_mosaic" children="mosaic_abn_num_ratio" defaultValue={0.5} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>噪声检测</h4>
          <Form.Item className="mb-0" name={['vqd_noise', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_noise" children="noise_thr" defaultValue={0.3} labelName="过暗阈值" />
          <BoxInputNumber parent="vqd_noise" children="noise_abn_num_ratio" defaultValue={0.6} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>对比度检测</h4>
          <Form.Item className="mb-0" name={['vqd_contrast', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_contrast" children="ctra_low_thr" defaultValue={0.2} labelName="低判断阈值" />
          <BoxInputNumber parent="vqd_contrast" children="ctra_high_thr" defaultValue={0.8} labelName="高判断阈值" />
          <BoxInputNumber parent="vqd_contrast" children="ctra_abn_num_ratio" defaultValue={0.5} labelName="次数比例" />
        </div>
      </Flex>

      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>亮度检测</h4>
          <Form.Item className="mb-0" name={['vqd_lgt_dark', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_lgt_dark" children="dark_thr" defaultValue={0.4} labelName="过暗阈值" />
          <BoxInputNumber parent="vqd_lgt_dark" children="lgt_thr" defaultValue={0.1} labelName="过亮阈值" />
          <BoxInputNumber parent="vqd_lgt_dark" children="lgt_dark_abn_num_ratio" defaultValue={0.5} labelName="次数比例" />
        </div>
      </Flex>
      <Flex vertical className="config-box">
        <Flex justify="space-between" align="center" className="config-box-hade">
          <h4>花屏检测</h4>
          <Form.Item className="mb-0" name={['vqd_flower', 'enable']} >
            <Switch className="ml-1" size="small" />
          </Form.Item>
        </Flex>
        <div className="config-box-item">
          <BoxInputNumber parent="vqd_flower" children="flower_thr" defaultValue={0.3} labelName="阈值参数" />
          <BoxInputNumber parent="vqd_flower" children="flower_abn_num_ratio" defaultValue={0.6} labelName="过亮阈值" />
          <BoxInputNumber parent="vqd_flower" children="mosaic_thr" defaultValue={0.3} labelName="马赛克阈值参数" />
        </div>
      </Flex>
    </Flex>

  </>
}