/* eslint-disable consistent-return */
import React, { forwardRef, useState, useEffect, useImperativeHandle } from 'react';
import { Form, Row, Col, Button } from 'antd';
import { unstable_batchedUpdates } from 'react-dom';
import { UpOutlined, DownOutlined } from '@ant-design/icons';
import styles from '../common.less';
import { apiGetAttribute } from '../service';
import CustomSelect from '@/components/CustomSelect';
import { debounce } from '@/utils/utils';

const FormAttr = forwardRef((props, ref) => {
  const [form] = Form.useForm();
  const [isMore, setIsMome] = useState(false);
  const [categoryAttrs, setCategoryAttrs] = useState([]);
  const [skuOldAttr, setSkuOldAttr] = useState([]);
  const [initAttrData, setInitAttrData] = useState({});

  const formItemAttr = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  const onChangeMore = () => {
    setIsMome(!isMore);
  };

  // 验证是否失效属性（已失效的商品不显示）
  const checkInAttrList = (id, categoryList) =>
    categoryList.some(item => item.valueList.some(v => +v.id === +id));

  // 获取初始化属性数据
  const getInitAttrValue = categoryList => {
    const skuAttr = props.initData.productAttributeApplyList?.productAttributeApplyList || [];
    const obj = {
      initValue: {},
    };
    const key = 'productAttributeApplyValueList';

    skuAttr.forEach(item => {
      if (item[key].length) {
        let values = [];
        if ((item.optionType && +item.optionType.code === 1) || typeof item[key] === 'string') {
          values = '';
        }
        obj[item.productAttributeId] = [];
        item[key].forEach(attr => {
          const { attributeValueId, attributeValueName } = attr;
          const json = {
            attributeValueId,
            attributeValueName,
            name: attributeValueName,
          };
          if (attributeValueId === 0 || checkInAttrList(attributeValueId, categoryList)) {
            const v = JSON.stringify(json);
            if (attributeValueId === 0) {
              obj[item.productAttributeId].push(json);
            }
            // eslint-disable-next-line no-unused-expressions
            if ((item.optionType && +item.optionType.code === 1) || typeof item[key] === 'string') {
              values = v;
            } else {
              values.push(v);
            }
          }
        });
        obj.initValue[item.productAttributeId] = values;
      }
    });
    return obj;
  };

  // 获取属性
  const getAttribute = async categoryId => {
    console.log('categoryId :>> ', categoryId);
    console.log('props.initData :>> ', props.initData);
    const res = await apiGetAttribute(categoryId);
    if (res && res.data && res.data.length) {
      let initValue = {
        initValue: {},
      };
      if (props.initData) {
        if (props.initData.productAttributeApplyList?.oldProductAttributeApplyList) {
          const oattr = props.initData.productAttributeApplyList;
          setSkuOldAttr((oattr && oattr.oldProductAttributeApplyList) || []);
        }
        if (props.initData.productAttributeApplyList?.productAttributeApplyList) {
          initValue = getInitAttrValue(res.data);
        }
      }

      res.data.forEach(item => {
        item.valueList = item.valueList.map(v => ({
          attributeValueId: v.id,
          attributeValueName: v.name,
          name: v.name,
        }));
        if (initValue[item.id] && initValue[item.id].length) {
          item.valueList.push(...initValue[item.id]);
        }
      });
      unstable_batchedUpdates(() => {
        setInitAttrData(initValue.initValue);
        setCategoryAttrs(res.data);
      });
    } else {
      setInitAttrData({});
      setCategoryAttrs([]);
    }
  };

  // 获取下拉框类型
  const getMode = optionType => (+optionType.code === 2 ? 'multiple' : 'default');

  // 获取下拉框校验
  const getAttrRules = k => {
    if (+k.required.code === 1) {
      return [
        {
          required: true,
          type: +k.optionType.code === 2 ? 'array' : 'string',
          message: '请选择',
        },
      ];
    }
    return [];
  };

  // 处理下拉框返回值
  const deal = attr => {
    try {
      const json = JSON.parse(attr);
      if (json.attributeValueId) {
        return json;
      }
      return { attributeValueName: json.name };
    } catch {
      return { attributeValueName: attr };
    }
  };

  const getFormValues = debounce(() => {
    const values = form.getFieldsValue();
    const arr = Object.keys(values).map(item => {
      const obj = {
        productAttributeId: item,
      };
      if (typeof values[item] === 'string') {
        obj.productAttributeApplyValueList = JSON.parse(values[item]);
      } else {
        obj.productAttributeApplyValueList = values[item].map(v => JSON.parse(v));
      }
      return obj;
    });
    props.onValuesChange({
      productAttributeApplyList: {
        productAttributeApplyList: arr,
      },
    });
  }, 400);

  const onCheck = async () => {
    try {
      const values = await form.validateFields();
      const attributeApplyList = [];
      // eslint-disable-next-line no-restricted-syntax
      for (const key in values) {
        if (values.hasOwnProperty(key) && values[key]) {
          let attrs = values[key];
          if (Array.isArray(values[key])) {
            attrs = [];
            values[key].forEach(attr => {
              if (typeof attr !== 'undefined') {
                attrs.push(deal(attr));
              }
            });
          } else {
            const json = deal(values[key]);
            json && (attrs = [json]);
          }
          attributeApplyList.push({
            attributeId: key,
            attributeApplyValueList: attrs,
          });
        }
      }
      return {
        temp: 'attributeApplyList',
        attributeApplyList,
      };
    } catch (errorInfo) {
      return null;
    }
  };

  useEffect(() => {
    const ids = props.categoryIds;
    if (ids && ids.length) {
      getAttribute(ids[ids.length - 1]);
    } else {
      setInitAttrData({});
      setCategoryAttrs([]);
    }
  }, [props.categoryIds]);

  useImperativeHandle(ref, () => ({
    onCheck,
    reset: form.resetFields,
  }));

  return (
    <>
      <div className={styles.attrbox + (isMore ? styles.attrboxMore : '')}>
        {categoryAttrs.length > 0 && (
          <Form form={form} initialValues={initAttrData} onValuesChange={getFormValues}>
            <Row>
              {categoryAttrs.map(k => (
                <Col span={12} key={k.id}>
                  <Form.Item
                    label={k.name}
                    name={k.id}
                    {...formItemAttr}
                    key={k.id}
                    rules={getAttrRules(k)}
                  >
                    <CustomSelect
                      options={k.valueList || []}
                      isCustom={+k.supportCustomValue.code === 1}
                      mode={getMode(k.optionType)}
                    />
                  </Form.Item>
                </Col>
              ))}
            </Row>
          </Form>
        )}
      </div>
      {categoryAttrs.length > 12 && (
        <div className={styles.btnMore}>
          <Button type="link" onClick={onChangeMore}>
            {isMore ? (
              <>
                收起 <UpOutlined />
              </>
            ) : (
              <>
                展示更多 <DownOutlined />
              </>
            )}
          </Button>
        </div>
      )}
      {skuOldAttr.length > 0 && (
        <div>
          <Row>注：以下商品属性已失效，请使用新的属性</Row>
          <Row>
            {skuOldAttr.map(s => (
              <Col span={12} key={s.id}>
                <Form.Item
                  label={s.productAttributeName}
                  {...formItemAttr}
                  required={false}
                  key={s.id}
                >
                  {s.productAttributeApplyValueList.map(item => item.attributeValueName).join('；')}
                </Form.Item>
              </Col>
            ))}
          </Row>
        </div>
      )}
    </>
  );
});

export default FormAttr;
