import { ConsoleSqlOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input, Select, Space, Modal, InputNumber, notification } from 'antd';
import React, {
  useState,
  forwardRef,
  useImperativeHandle,
  useRef,
  useEffect,
  useContext,
  useMemo,
  useCallback,
  memo,
} from 'react';
// import { unstable_batchedUpdates } from 'react-dom';
import { formItemLayout, StaticColumns, StaticColumnsPop } from '../config';
import EditFormTable from './EditFormTable';
import FormPackage from './FormPackage';
import {
  createProductData,
  cleanArray,
  filterCoverItemList,
  batchTableSourceData,
  fliterSkuListSortData,
  filterSkuNotIdList,
} from '../utils';
import { debounce } from '@/utils/utils';

import { ServiceContext } from '../context';
import { SelectTemplate, Title } from './CommonTemplate';

const initSpecReced = () => ({
  firstSpec: '',
  firstSpecId: null,
  firstSpecValue: [],
  secondSpec: '',
  secondSpecId: null,
  secondSpecValue: [],
});

const validatorSpecValue = (value, list, index, specName) => {
  const checkList = list.filter((item, ind) => {
    if (ind === index) {
      return false;
    }
    return item[specName] === value;
  });
  return checkList.length;
};

const SpecificationTemplate = (props, _) => {
  const {
    form,
    formName,
    label,
    specName,
    specList,
    selectName,
    onChange = () => {},
    specDataList,
  } = props;
  const customer = useContext(ServiceContext);

  const handleChange = (val, option) => {
    const optionSpecName = option ? option.specName : null;
    form.setFieldsValue({ [selectName]: optionSpecName });
    onChange();
  };

  const inputOnblurEvent = event => {
    if (event.target.value) {
      onChange();
    }
  };

  const bundlePlusAddSpecEvent = addCallback => {
    const specId = form.getFieldValue(formName);
    if (!specId) {
      Modal.warning({
        maskClosable: true,
        title: `请先选择${label}！`,
      });
      return;
    }
    addCallback();
  };

  const bundlePlusRemoveSpecEvent = (removeCallback, fieldName) => {
    removeCallback(fieldName);
    form.setFieldsValue({
      bacthFirst: undefined,
      bacthSecon: undefined,
    });
    const timer = setTimeout(() => {
      onChange();
      clearTimeout(timer);
    }, 500);
  };

  return (
    <>
      <Form.Item name={formName} label={label}>
        <Select
          disabled={customer.isEdit && customer.isNormal}
          allowClear
          options={specList}
          style={{ width: 200 }}
          fieldNames={{ label: 'specName', value: 'specId' }}
          placeholder={`请选择${label}`}
          showSearch
          filterOption={(input, option) =>
            option.specName.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }
          onChange={handleChange}
        />
      </Form.Item>
      <Form.Item name={selectName} hidden>
        <Input hidden />
      </Form.Item>
      <Form.List name={specName}>
        {(fields, { add, remove }) => (
          <>
            {fields.map((field, index) => (
              <Form.Item key={field.key} noStyle shouldUpdate={(prevValues, curValues) => false}>
                {() => (
                  <Space key={`space_${field.key}`} align="baseline">
                    <Form.Item
                      key={`item_${field.key}`}
                      style={{ marginLeft: 10 }}
                      name={[field.name, specName]}
                      rules={[
                        { required: true, message: '请输入规格名称' },
                        {
                          message: '规格名不能重复！',
                          validator(rule, value, callback) {
                            const checkList = form.getFieldValue(specName);
                            const check = validatorSpecValue(
                              value,
                              cleanArray(checkList),
                              index,
                              specName,
                            );
                            return check ? callback('规格名不能重复！') : callback();
                          },
                        },
                      ]}
                    >
                      <Input
                        disabled={specDataList[index] && specDataList[index].id}
                        onBlur={inputOnblurEvent}
                        placeholder="请输入规格名称"
                      />
                    </Form.Item>
                    {!(specDataList[index] && specDataList[index].id) && (
                      <MinusCircleOutlined
                        key={`minus_${field.key}`}
                        onClick={() => bundlePlusRemoveSpecEvent(remove, field.name)}
                      />
                    )}
                  </Space>
                )}
              </Form.Item>
            ))}
            {(!customer.isCard || fields.length < 3) && !customer.isDisabled && (
              <Form.Item noStyle key="btnpush">
                <Button
                  style={{ marginLeft: 10, marginBottom: 24 }}
                  type="dashed"
                  onClick={() => bundlePlusAddSpecEvent(add)}
                  icon={<PlusOutlined />}
                />
              </Form.Item>
            )}
          </>
        )}
      </Form.List>
    </>
  );
};

const CreateBatchFormItems = ({ specInitValue, batchChange, defaultColumns }) => {
  const customer = useContext(ServiceContext);
  const formItems = defaultColumns
    .filter(item => item.batchRole && item?.batchRole.includes(customer.productType))
    .map((item, index) => (
      <Form.Item
        noStyle
        key={`${item.dataIndex}`}
        name={['batchItem', item.dataIndex]}
        initialValue={null}
      >
        <InputNumber {...(item.batchProps || {})} placeholder={item.title} />
      </Form.Item>
    ));
  return (
    <>
      {formItems.length ? (
        <Space style={{ marginBottom: 20 }}>
          <SelectTemplate
            width={150}
            noSty
            formName="bacthFirst"
            placeholder={specInitValue.firstSpec}
            dataList={specInitValue.firstSpecValue || []}
            fieldNames={{ label: 'firstSpecValue', value: 'firstSpecValue' }}
          />
          <SelectTemplate
            noSty
            width={150}
            formName="bacthSecon"
            placeholder={specInitValue.secondSpec}
            dataList={specInitValue.secondSpecValue || []}
            fieldNames={{ label: 'secondSpecValue', value: 'secondSpecValue' }}
          />
          {formItems.concat(
            <Button
              key="batch"
              type="primary"
              disabled={customer.isEdit && customer.isNormal}
              onClick={batchChange}
            >
              批量设置
            </Button>,
          )}
        </Space>
      ) : null}
    </>
  );
};

const FormPriceOrStock = forwardRef((props, ref) => {
  const { specList, editData, skuList = [], onSpecChange } = props;

  const editRef = useRef(null);
  const packageRef = useRef(null);
  const customer = useContext(ServiceContext);
  const customerRef = useRef(customer);
  const [form] = Form.useForm();
  const [specInitValue, setSpecInitValue] = useState(initSpecReced());

  const [defaultColumns, setDefaultColumns] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [mergeTable, setMergeTable] = useState(false);

  const insertSpecID = items => {
    const sids = items.filter(item => item.id);
    if (sids.length !== skuList.length) {
      let i = 0;
      const ids = skuList.reduce((prev, cur) => {
        if (!sids.includes(cur.id)) {
          prev.push(cur.id);
        }
        return prev;
      }, []);
      items.forEach(item => {
        if (!item.id && i < ids.length) {
          item.id = ids[i++];
        }
      });
    }
  };

  const onCheck = async () => {
    try {
      let setMealContent = '';
      if (customer.isCard) {
        setMealContent = await packageRef.current.onCheck();
      }
      const values = await form.validateFields();
      if (!values.firstSpecValue || !values.firstSpecValue.length) {
        values.firstSpecId = null;
        values.firstSpec = '';
      }
      if (!values.secondSpecValue || !values.secondSpecValue.length) {
        values.secondSpecId = null;
        values.secondSpec = '';
      }
      const items = await editRef.current.onCheck();
      if (customer.isCard && !setMealContent) {
        notification.open({
          message: '提示',
          description: '请添加正确的套餐信息！',
        });
        return null;
      }
      if (items && items.length) {
        if (customer.isEdit && skuList.length) {
          insertSpecID(items);
        }
        const obj = { ...values, items, temp: 'infoSpecData' };
        customer.isCard && setMealContent && (obj.setMealContent = setMealContent);
        return obj;
      }
      notification.open({
        message: '提示',
        description: '请生成商品信息！',
      });
      return null;
    } catch (errorInfo) {
      return null;
    }
  };

  const CreateColumnsEvent = specData => {
    const columsData = [];
    if (specData.firstSpec && specData.firstSpecValue && specData.firstSpecValue.length) {
      columsData.push({
        title: specData.firstSpec,
        dataIndex: 'firstSpecValue',
        inputType: 'text',
      });
    }

    if (specData.secondSpec && specData.secondSpecValue && specData.secondSpecValue.length) {
      columsData.push({
        title: specData.secondSpec,
        dataIndex: 'secondSpecValue',
        inputType: 'text',
      });
    }

    // isGoodsManage用来判断是否是popGoodsManage页面,这个页面是用来应付审计团队的,没有实际功能,这里删掉了供货价字段,正常业务逻辑不用考虑这个字段,这就用第一个数据就好了
    const isGoodsManage = window.location.pathname.indexOf('popGoodsManage') < 0;
    const dynamicColumns = [
      ...columsData,
      ...(isGoodsManage
        ? StaticColumns(customerRef.current)
        : StaticColumnsPop(customerRef.current)),
    ];
    setDefaultColumns(dynamicColumns);
  };

  const onFinish = async () => {
    try {
      const values = await form.validateFields();
      const cleanValues = {
        firstValues: cleanArray(values.firstSpecValue || []),
        secondValues: cleanArray(values.secondSpecValue || []),
        firstSpecId:
          values.firstSpecValue && values.firstSpecValue.length ? values.firstSpecId : null,
        secondSpecId:
          values.secondSpecValue && values.secondSpecValue.length ? values.secondSpecId : null,
      };

      const { inIdList: fisrtInIdList, noIdList: fisrtNoIdList } = filterSkuNotIdList(
        cleanValues.firstValues,
      );
      const { inIdList: secndInIdList, noIdList: secndNoIdList } = filterSkuNotIdList(
        cleanValues.secondValues,
      );
      const createSkuList = createProductData(
        {
          firstSpecId: cleanValues.firstSpecId,
          secondSpecId: cleanValues.secondSpecId,
          fisrtInIdList,
          secndInIdList,
          fisrtNoIdList,
          secndNoIdList,
        },
        customer.isEdit,
        skuList,
      );
      CreateColumnsEvent(values);
      // 没有规格默认创建一条数据
      if (!cleanValues.firstSpecId && !createSkuList.secondSpecId) {
        setTableData([...createSkuList]);
        return;
      }
      // 是否合并单元格
      setMergeTable(Boolean(cleanValues.secondValues.length));
      setTableData(fliterSkuListSortData([...createSkuList]));
    } catch (error) {
      console.log(error);
    }
  };

  const batchChange = () => {
    const values = form.getFieldsValue();
    const { batchItem, bacthFirst, bacthSecon } = values;
    const resetObject = batchTableSourceData({ batchItem, tableData, bacthSecon, bacthFirst });
    props.onValuesChange({ skuList: resetObject });
    setTableData(resetObject);
  };

  const onSpecificationEvent = async () => {
    try {
      const values = await form.validateFields();
      const cleanValues = {
        firstSpec: values.firstSpec,
        firstSpecId: values.firstSpecId,
        firstSpecValue: cleanArray(values.firstSpecValue),
        secondSpec: values.secondSpec,
        secondSpecId: values.secondSpecId,
        secondSpecValue: cleanArray(values.secondSpecValue),
      };
      setSpecInitValue(cleanValues);
      CreateColumnsEvent(cleanValues);
      return cleanValues;
    } catch (error) {
      console.log(error);
    }
    return null;
  };

  const getFormValues = debounce(async () => {
    const cleanValues = await onSpecificationEvent();
    props.onValuesChange({ infoSpecData: cleanValues });
  }, 400);

  const packageValueChange = () => {
    const efvalues = editRef.current.getValues();
    if (customer.isCard) {
      const packageV = packageRef.current.getValues();
      efvalues.forEach((item, i) => {
        item.serviceItem = {
          setMealContent: packageV.lists[i].children,
        };
      });
    }
    props.onValuesChange({ skuList: efvalues });
  };

  const firstOnChangeEvent = async () => {
    const cleanValues = await onSpecificationEvent();
    if (cleanValues) {
      const firstSpecValueList = cleanArray(cleanValues.firstSpecValue).map(
        item => item.firstSpecValue,
      );
      onSpecChange(firstSpecValueList);
    }
    onFinish();
  };

  const seconOnChangeEvent = async () => {
    await onSpecificationEvent();
    onFinish();
  };

  useImperativeHandle(ref, () => ({
    onCheck,
    onFinish,
    reset: () => {
      form.resetFields();
      setDefaultColumns([]);
      setTableData([]);
      setMergeTable(false);
      setSpecInitValue(initSpecReced());
    },
  }));

  useEffect(() => {
    customerRef.current = customer;
  }, [customer]);

  useEffect(() => {
    if (customer.isEdit || customer.isUseCache) {
      if (!editData) {
        onFinish();
        return;
      }
      form.setFieldsValue(editData); // 设置规格数据
      firstOnChangeEvent(); // 触发成底部动态表格数据
      setSpecInitValue(editData); // 缓存规格数据
      CreateColumnsEvent(editData);
      setMergeTable(Boolean(editData.secondSpecValue && editData.secondSpecValue.length));
      setTableData(fliterSkuListSortData(skuList) || []);
    }
  }, [customer.isEdit, customer.isUseCache, editData, customer.isGold]);

  return (
    <>
      <Form
        form={form}
        autoComplete="off"
        initialValues={initSpecReced()}
        onValuesChange={getFormValues}
      >
        <SpecificationTemplate
          form={form}
          label="一级规格"
          selectName="firstSpec"
          formName="firstSpecId"
          specName="firstSpecValue"
          onChange={firstOnChangeEvent}
          specList={specList}
          specDataList={specInitValue.firstSpecValue}
        />
        <SpecificationTemplate
          form={form}
          label="二级规格"
          selectName="secondSpec"
          formName="secondSpecId"
          specName="secondSpecValue"
          onChange={seconOnChangeEvent}
          specList={specList}
          specDataList={specInitValue.secondSpecValue}
        />
        {/* <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 20 }}>
          <Button type="primary" onClick={onFinish}>
            生成商品信息
          </Button>
        </div> */}
        <div>
          <CreateBatchFormItems
            batchChange={batchChange}
            specInitValue={specInitValue}
            defaultColumns={defaultColumns}
          />
        </div>
      </Form>
      <EditFormTable
        ref={editRef}
        mergeTable={mergeTable}
        setTableData={setTableData}
        defaultColumns={defaultColumns}
        initData={tableData}
        onValuesChange={packageValueChange}
      />
      {customer.isCard && (
        <>
          <Title title="套餐内容" key="tctitle" />
          <FormPackage
            ref={packageRef}
            initData={tableData}
            key="tc"
            onValuesChange={packageValueChange}
          />
        </>
      )}
    </>
  );
});

export default FormPriceOrStock;
