import React, {
  useState,
  useContext,
  useEffect,
  forwardRef,
  useImperativeHandle,
  useRef,
} from 'react';
import {
  Cascader,
  Form,
  Input,
  Select,
  Popover,
  Button,
  Checkbox,
  Divider,
  Modal,
  notification,
} from 'antd';
import { formItemLayout } from '../config';
import { ServiceContext } from '../context';
import { debounce } from '@/utils/utils';
import UploadCropImage from './UploadCropImage';
import { apiShopIds, apiQueryShopList, apiServiceByCategory } from '../service';
import GroupInfo from '../../GoodsManage/Takeaway/components/GroupInfo';

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,
    afterAddressList,
    specListData,
    shopGetByProductType,
    groupShopData,
  } = props;
  const [form] = Form.useForm();
  const [noreBrandList, setNoreBrandList] = useState([]);
  const customer = useContext(ServiceContext);
  const childAddMenusModalRef = useRef(null);
  const [takeawayImageList, setTakeawayImageList] = useState([]);
  const [shopIds, setShopIds] = useState([]);
  const [shopList, setShopList] = useState([]);
  const [isEditTakeaway, setIsEditTakeaway] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [shopIdSource, setShopIdSource] = useState('');
  const [serviceList, setServiceList] = useState({}); // 品类下的服务承诺
  const [specServiceList, setSpecServiceList] = useState([]); // 服务承诺列表

  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 getServiceList = async ids => {
    const id = ids[ids.length - 1];
    const res = await apiServiceByCategory(id);
    if (res?.data?.length > 0) {
      const obj = {};
      res.data.forEach(item => {
        obj[item.productServiceId] = item.required;
      });

      setServiceList(obj);
    }
  };

  const onCategoryChange = ids => {
    props.onCategoryChange(ids);
    getServiceList(ids);
  };

  // 自定义加入菜单
  const showModal = () => {
    if (shopIdSource || editData?.productRefShopId) {
      setIsModalOpen(true);
    } else {
      notification.error({ message: '请先选择名店在进行操作！' });
    }
  };
  // 自定义菜单下拉
  const dropdownRender = menus => (
    <div>
      {menus}
      <Divider
        style={{
          margin: 0,
        }}
      />
      <div
        style={{
          padding: 8,
          background: '#1890ff',
          color: '#fff',
          textAlign: 'center',
        }}
        onClick={showModal}
      >
        添加自定义分组
      </div>
    </div>
  );
  const onTakeawayImageList = imgList => {
    setTakeawayImageList(imgList);
    form.setFieldsValue({
      commonImageList: imgList,
    });
  };
  const getFormValues = debounce(() => {
    const values = form.getFieldsValue();
    props.onValuesChange({ infoMation: values });
  }, 400);
  // 查询shopIds
  const queryShopIds = async () => {
    if (!shopIds.length) {
      const result = await apiShopIds();
      setShopIds(result.data || []);
    }
  };
  // 查询分组列表
  const queryShopList = async params => {
    let result = [];
    if (params) {
      result = await apiQueryShopList(params);
    } else {
      result = await apiQueryShopList({ shopId: shopIdSource });
    }
    setShopList(result.data || []);
  };
  const onChangeShopId = async e => {
    if (e) {
      setShopList([]);
      queryShopList({ shopId: e });
      setShopIdSource(e);
      form.setFieldsValue({
        storageRackIds: '',
      });
    }
  };
  useImperativeHandle(ref, () => ({
    onCheck,
    reset: form.resetFields,
  }));
  useEffect(() => {
    queryShopIds();
  }, [customer.productType]);

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

  useEffect(() => {
    if (!editData) return;
    if ((editData?.productType === 5 && editData?.name) || customer.productType === 5) {
      shopGetByProductType(5);
      if (editData?.productRefShopId) {
        const productRefShopId = Array.isArray(editData?.productRefShopId)
          ? (editData?.productRefShopId).toString()
          : editData?.productRefShopId;
        setShopIdSource(productRefShopId);
        queryShopList({ shopId: productRefShopId });
      }
      setIsEditTakeaway(true);
    }
    if (editData?.categoryId?.length) {
      editData.categoryId = editData.categoryId.filter(item => !!item);
    }
    if (editData?.storageRackIds?.length) {
      editData.storageRackIds = editData?.storageRackIds.map(item => `${item}`);
    }
    form.setFieldsValue(editData);
    if (editData?.commonImageList?.length) {
      onTakeawayImageList(editData?.commonImageList);
    }
    getServiceList(editData.categoryId);
  }, [customer.isEdit, editData]);
  useEffect(() => {
    setShopList([]);
    const { shopId = '', groupId = '' } = groupShopData;
    if (shopId) {
      shopGetByProductType(5);
      setShopIdSource(shopId);
      queryShopList({ shopId });
    }
    const temp = {
      productRefShopId: shopId ? [`${shopId}`] : [],
      storageRackIds: groupId ? [`${groupId}`] : [],
    };
    form.setFieldsValue(temp);
  }, [groupShopData]);

  useEffect(() => {
    // 品类下的设置的服务承诺不可选 required true默认选中 false默认不选中
    if (specListData.length > 0) {
      const defaultChecked = new Set(editData?.[specListData[0].specId] || []);
      const arr = specListData[0].specValues.map(item => {
        if (serviceList[item.value]) {
          defaultChecked.add(item.value);
        }
        return {
          ...item,
          disabled: typeof serviceList[item.value] === 'boolean',
        };
      });
      setSpecServiceList(arr);
      form.setFieldsValue({ [specListData[0].specId]: Array.from(defaultChecked) });
    }
  }, [serviceList, specListData]);

  return (
    <Form
      {...formItemLayout}
      form={form}
      name="register"
      initialValues={{
        brandId: null,
        name: '',
        categoryId: [],
        description: '',
        productRefShopId: [],
        storageRackIds: null,
      }}
      scrollToFirstError
      onValuesChange={getFormValues}
    >
      <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.isTakeawayService && (
        <Form.Item
          name="productRefShopId"
          label="所属门店"
          rules={[{ required: true, message: '请选择所属门店' }]}
        >
          <Select
            fieldNames={{ label: 'name', value: 'id' }}
            filterOption={fileterBrandOptions}
            placeholder="请选择所属门店"
            options={shopIds}
            onChange={onChangeShopId}
          ></Select>
        </Form.Item>
      )}
      {/* 菜单分组 */}
      {customer.isTakeawayService && (
        <Form.Item
          name="storageRackIds"
          label="菜单分组"
          rules={[{ type: 'array', required: true, message: '请输入菜单分组' }]}
        >
          <Cascader
            placeholder="请选择菜单分组"
            disabled={customer.isEdit && customer.isNormal}
            showSearch={{ filter: filterCategoryOptions }}
            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
            options={shopList}
            dropdownRender={dropdownRender}
          />
        </Form.Item>
      )}
      <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={onCategoryChange}
          options={newCategoryList[customer.productType]}
        />
      </Form.Item>
      {/* 外卖-商品图片 */}
      {customer.isTakeawayService && (
        <Form.Item
          name="commonImageList"
          label="商品图片"
          extra="支持.jpg/png格式图片，建议单张比例1:1，大小200kb左右，最多可以上传5张"
          rules={[
            {
              required: true,
              type: 'array',
              message: '请上传商品图片',
            },
          ]}
        >
          <UploadCropImage
            name="takeawayImageList"
            limit={5}
            disabled={customer.isDisabled}
            pictures={takeawayImageList}
            setPictureList={list => onTakeawayImageList(list)}
          />
        </Form.Item>
      )}

      {!customer.isTakeawayService && !customer.isCard && (
        <Form.Item
          name="brandId"
          label="商品品牌"
          rules={[{ required: true, message: '请选择商品品牌' }]}
        >
          <Select
            showSearch
            disabled={customer.isDisabled}
            placeholder="请选择商品品牌"
            filterOption={fileterBrandOptions}
          >
            {customer.productType === 2
              ? CreateSelectOption(noreBrandList)
              : CreateSelectOption(brandList)}
          </Select>
        </Form.Item>
      )}

      {!customer.isTakeawayService && !customer.isCard && (
        <Form.Item
          name="character"
          label="商品卖点"
          rules={[{ required: true, message: '请输入商品卖点!', whitespace: true }]}
        >
          <Input
            maxLength={50}
            placeholder="卖点最优可填写3个词,12个字。前后用空格加竖杠分隔,例: 莹莹剔透 | 粒粒优选 | 易煮易熟"
          />
        </Form.Item>
      )}

      {!customer.isTakeawayService && !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.isTakeawayService &&
        !customer.isCard &&
        specListData.map((item, index) => (
          <Form.Item name={item.specId} key={item.specId} label={item.specName}>
            <Checkbox.Group options={specServiceList} />
          </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}
      <GroupInfo
        isModalOpen={isModalOpen}
        shopId={shopIdSource}
        search={queryShopList}
        handleClose={setIsModalOpen}
      />
    </Form>
  );
});

export default FormInformationBasic;
