import React, { useState, useContext, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Cascader, Form, Input, Select, Popover, Button, Checkbox } from 'antd';
import { formItemLayout } from '../config';
import { ServiceContext } from '../context';
import { debounce } from '@/utils/utils';

const CreateSelectOption = optionList =>
  optionList.map(brandItem => (
    <Select.Option key={brandItem.id} value={brandItem.id}>
      {brandItem.name}
    </Select.Option>
  ));

const fileterBrandOptions = (input, options) => options.children.includes(input);

const filterCategoryOptions = (inputValue, path) =>
  path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);

const FormInformationBasic = forwardRef((props, ref) => {
  const {
    editData,
    newCategoryList,
    categoryList,
    virtualCategoryList,
    brandList,
    shopList,
    afterAddressList,
    specListData,
  } = props;
  const [form] = Form.useForm();
  const [noreBrandList, setNoreBrandList] = useState([]);
  const customer = useContext(ServiceContext);

  const onCheck = async () => {
    try {
      const values = await form.validateFields();
      const specs = [];
      // 非服务类商品过滤specs数据
      if (!customer.isCard) {
        specListData.forEach(item => {
          const specValues = values[item.specId];
          // 判断是否包含改参数
          if (specValues) {
            specs.push({ specId: item.specId, specValues });
          }
          delete values[item.specId];
        });
      }
      values.specs = specs;
      values.temp = 'infoMation';
      return values;
    } catch (errorInfo) {
      return null;
    }
  };

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

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

  useEffect(() => {
    const noreList = (brandList || []).filter(item => item.name === '虚拟商品');
    setNoreBrandList(noreList);
  }, [brandList]);

  useEffect(() => {
    if (!editData) return;
    form.setFieldsValue(editData);
  }, [customer.isEdit, editData]);

  return (
    <Form
      {...formItemLayout}
      form={form}
      name="register"
      initialValues={{
        brandId: null,
        name: '',
        categoryId: [],
        description: '',
      }}
      scrollToFirstError
      onValuesChange={getFormValues}
    >
      <Form.Item
        name="categoryId"
        label="商品类目"
        rules={[{ type: 'array', required: true, message: '请输入商品类目!' }]}
      >
        <Cascader
          placeholder="请选择商品类目！"
          disabled={customer.isEdit && customer.isNormal}
          showSearch={{ filter: filterCategoryOptions }}
          fieldNames={{ label: 'name', value: 'id', children: 'children' }}
          onChange={props.onCategoryChange}
          options={newCategoryList[customer.productType]}
        />
      </Form.Item>
      {!customer.isCard && (
        <Form.Item
          name="brandId"
          label="商品品牌"
          rules={[{ required: true, message: '请选择商品品牌!' }]}
          extra="若需新增品牌请联系业务员"
        >
          <Select
            showSearch
            disabled={customer.isDisabled}
            placeholder="请选择商品品牌"
            filterOption={fileterBrandOptions}
          >
            {customer.productType === 2
              ? CreateSelectOption(noreBrandList)
              : CreateSelectOption(brandList)}
          </Select>
        </Form.Item>
      )}
      <Popover content={form.getFieldValue('name')} trigger="hover">
        <Form.Item
          key="name"
          name="name"
          label="商品名称"
          rules={[
            { required: true, min: 2, message: '请输入最少两个字符的商品名称!', whitespace: true },
          ]}
        >
          <Input placeholder="请输入商品名称" disabled={customer.isDisabled} />
        </Form.Item>
      </Popover>
      {!customer.isCard && (
        <Form.Item
          name="character"
          label="商品卖点"
          rules={[{ required: true, message: '请输入商品卖点!', whitespace: true }]}
        >
          <Input
            maxLength={50}
            placeholder="卖点最优可填写3个词,12个字。前后用空格加竖杠分隔,例: 莹莹剔透 | 粒粒优选 | 易煮易熟"
          />
        </Form.Item>
      )}

      {!customer.isCard && (
        <Form.Item name="afterAddressId" label="售后地址">
          <Select showSearch placeholder="请选择售后地址" filterOption={fileterBrandOptions}>
            {(afterAddressList || []).map(item => (
              <Select.Option key={item.id} value={item.id}>
                {item.addressName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      )}

      {!customer.isCard &&
        specListData.map((item, index) => (
          <Form.Item name={item.specId} key={item.specId} label={item.specName}>
            <Checkbox.Group options={item.specValues} />
          </Form.Item>
        ))}

      {/* <Form.Item
        name="brandId"
        label="供应商名称"
        rules={[{ required: true, message: '请选择供应商名称!' }]}
      >
        <Select showSearch placeholder="请选择供应商名称" filterOption={fileterBrandOptions}>
          {CreateSelectOption(brandList)}
        </Select>
      </Form.Item> */}

      {customer.isCard ? (
        <Form.Item
          key="description"
          name="description"
          label="描述"
          rules={[{ required: true, message: '请输入描述,100字以内！' }]}
        >
          <Input.TextArea showCount maxLength={100} placeholder="请输入描述, 100字以内！" />
        </Form.Item>
      ) : null}
    </Form>
  );
});

export default FormInformationBasic;
