/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
import React, { useState, useEffect, useContext, forwardRef, useImperativeHandle } from 'react';
import { Form, Button } from 'antd';
import { ServiceContext } from '../context';
import { TaskList, formItemLayout } from '../config';
import UploadImage from './UploadImage';
import commonStyle from '../common.less';
import { debounce } from '@/utils/utils';

const FormRuleVPictures = forwardRef((props, ref) => {
  const { editData, specKeyItem } = props;
  const [imageList, setImageList] = useState({});
  const [commonImageList, setCommonImageList] = useState([]);
  const [detailImageList, setDetailImageList] = useState([]);
  const [cardImageList, setCardImageList] = useState([]);

  const [form] = Form.useForm();

  const customer = useContext(ServiceContext);
  const typeConfig = TaskList(customer.canAddService, customer.canAddNormal);
  const [{ imgConfig }] = typeConfig.filter(item => item.type === customer.productType);

  useEffect(() => {
    if (customer.isEdit || customer.isUseCache) {
      if (editData) {
        setImageList(editData.imageList || {});
        setCardImageList(editData.cardImageList || []);
        setCommonImageList(editData.commonImageList || []); // 编辑状态下设置公共图
        setDetailImageList(editData.detailImageList || []); // 编辑状态下设置详情图
        const editParams = {
          commonImageList: editData.commonImageList,
          detailImageList: editData.detailImageList,
        };
        if (customer.isCard) {
          editParams.cardImageList = editData.cardImageList;
        } else {
          editParams.imageList = editData.imageList;
        }
        const timer = setTimeout(() => {
          form.setFieldsValue(editParams);
          clearTimeout(timer);
        });
      }
    }
  }, [customer.isEdit, customer.isUseCache, editData]);

  useEffect(() => {
    if (customer.isCard) return;
    if (specKeyItem.length) {
      const newImageList = specKeyItem.reduce((origin, item) => {
        const showItem = imageList[item] || [];
        origin[item] = showItem;
        return origin;
      }, {});
      setImageList(newImageList);
    }
  }, [specKeyItem]);

  const onCheck = async () => {
    try {
      const values = await form.validateFields();
      values.temp = 'infoImageData';
      return values;
    } catch (errorInfo) {
      console.log(errorInfo);
      return null;
    }
  };

  const getFormValues = debounce(() => {
    const values = form.getFieldsValue();
    props.onValuesChange({ infoImageData: values });
    // props.onValuesChange(values);
  }, 400);

  useImperativeHandle(ref, () => ({
    onCheck,
    setFieldsValue: obj => {
      setDetailImageList(obj.detailImageList || []);
      for (const key in obj.imageList) {
        if (!obj.imageList[key]) {
          obj.imageList[key] = [];
        }
      }
      setImageList(obj.imageList || {});
      form.setFieldsValue(obj);
    },
    getFieldsValue: form.getFieldsValue,
    reset: () => {
      form.resetFields();
      setImageList({});
      setCardImageList([]);
      setCommonImageList([]);
      setDetailImageList([]);
    },
  }));

  const onPictureSuccessEvent = (imgList, key) => {
    const newImgList = { ...imageList, [key]: imgList };
    setImageList(newImgList);
    form.setFieldsValue({
      imageList: newImgList,
    });
  };

  const onCommonSuccessEvent = imgList => {
    setCommonImageList(imgList);
    form.setFieldsValue({
      commonImageList: imgList,
    });
  };

  const onCardSuccessImageList = imgList => {
    setCardImageList(imgList);
    form.setFieldsValue({
      cardImageList: imgList,
    });
  };

  // 拉取公共图片
  const onPullCommonImg = key => {
    const cimg = form.getFieldValue('commonImageList');
    const obj = { ...imageList };
    obj[key] = cimg;
    setImageList(obj);
  };

  const onDetailSuccessImageList = imgList => {
    setDetailImageList(imgList);
    form.setFieldsValue({
      detailImageList: imgList,
    });
  };

  return (
    <Form
      form={form}
      labelCol={{ flex: '110px' }}
      labelAlign="right"
      labelWrap
      colon
      initialValues={{
        commonImageList: [],
        cardImageList: [],
        imageList: {},
        detailImageList: [],
      }}
      onValuesChange={getFormValues}
    >
      <Form.Item
        name="commonImageList"
        label={imgConfig.commonImageList.title}
        extra={imgConfig.commonImageList.renderExtra(commonImageList.length)}
        rules={[
          {
            required: imgConfig.commonImageList.rule,
            type: 'array',
            message: '请上传图片！',
          },
          {
            validateTrigger: 'submit',
            validator(rule, value, callback) {
              if (customer.productType !== 1) {
                return callback();
              }
              // 规格图不为必传，如未上传规格图时，公共图为必传图
              const checkImageList = form.getFieldValue('imageList');
              const check = Object.keys(checkImageList || {}).length;
              return check || value.length ? callback() : callback('请上传封面图片');
            },
          },
        ]}
      >
        <UploadImage
          multiple={!customer.isCard}
          maxWidth={customer.isCard ? 0 : 1200}
          maxHeight={customer.isCard ? 0 : 1200}
          superTips="公共滑动图尺寸不可大于 1200*1200"
          name="commonImageList"
          disabled={customer.isDisabled}
          limit={imgConfig.commonImageList.limit}
          pictures={commonImageList}
          setPictureList={list => onCommonSuccessEvent(list)}
        />
      </Form.Item>
      {customer.isCard && (
        <Form.Item
          name="cardImageList"
          label={imgConfig.cardImageList.title}
          extra={imgConfig.cardImageList.renderExtra(cardImageList.length)}
          rules={[
            {
              required: imgConfig.cardImageList.rule,
              type: 'array',
              message: `请上传${imgConfig.cardImageList.title}！`,
            },
          ]}
        >
          <UploadImage
            name="cardImageList"
            limit={imgConfig.cardImageList.limit}
            disabled={customer.isDisabled}
            pictures={cardImageList}
            setPictureList={list => onCardSuccessImageList(list)}
          />
        </Form.Item>
      )}
      {!customer.isCard &&
        Object.keys(imageList).map(key => (
          <div key={key} className={commonStyle.pictureWrapper}>
            <Form.Item
              name={['imageList', key]}
              key={key}
              label={`商品图片(${key})`}
              rules={[
                { required: imgConfig.imageList.rule, type: 'array', message: '请上传图片！' },
              ]}
              extra={imgConfig.imageList.renderExtra()}
            >
              <UploadImage
                name={key}
                limit={11}
                disabled={customer.isDisabled}
                pictures={imageList[key]}
                setPictureList={list => onPictureSuccessEvent(list, key)}
              />
            </Form.Item>
            {!imageList[key]?.length && (
              <Button
                disabled={imageList[key]?.length}
                className={commonStyle.pullImage}
                onClick={() => onPullCommonImg(key)}
                type="primary"
              >
                拉取公共图
              </Button>
            )}
          </div>
        ))}
      <Form.Item
        name="detailImageList"
        label={imgConfig.detailImageList.title}
        rules={[
          {
            type: 'array',
            required: imgConfig.detailImageList.rule,
            message: `请上传${imgConfig.detailImageList.title}！`,
          },
        ]}
        extra={imgConfig.detailImageList.renderExtra()}
      >
        <UploadImage
          limit={imgConfig.detailImageList.limit}
          maxWidth={customer.isCard ? 0 : 800}
          superTips="详情图宽度不可大于800"
          name="detailImageList"
          disabled={customer.isDisabled}
          pictures={detailImageList}
          setPictureList={list => onDetailSuccessImageList(list)}
        />
      </Form.Item>
    </Form>
  );
});

export default FormRuleVPictures;
