import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { Spin, Button, Modal, message, notification } from 'antd';
import moment from 'moment';
import PubSub from 'pubsub-js';
import { Title, WrapperContainer } from './components/CommonTemplate';
import { TaskTypeSelect } from './components/TaskTypeSelect';
import FormInformationBasic from './components/FormInformationBasic';
import FormPriceOrStock from './components/FormPriceOrStock';
import FormRuleSetting from './components/FormRuleSetting';
import FormRuleVPictures from './components/FormRuleVPictures';
import FormSettlementOthers from './components/FormSettlementOthers';
import FormAttr from './components/FormAttr';
import FormTakeaway from './components/FormTakeaway';
import localStorage from '@/utils/localStorage';
import {
  merchantBrandList,
  merchantSpecList,
  afterSalesAddrsPage,
  merchantgetJdPicList,
  shopGetBySupplierId,
  merchantProductAdd,
  merchantProductEdit,
  getByProductType,
  apiCreateDraft,
  apiEditDraft,
  apiGetShopDetail,
} from './service';
import { isUrl, filterSendData, clearCurrent, onAutoSaveValue, localAutoSaveKey } from './utils';
import { ServiceContext } from './context';
import { GOOD_MANAGE } from '@/../config/permission.config';
import styles from './common.less';

/**
 * 服务商品改造-商品模块
 * @param {*} router options
 * @returns ReactDOM
 */
const ServiceGoods = options => {
  const {
    SourceData,
    categoryList,
    virtualCategoryList,
    specListData,
    permissions,
    takeAway,
  } = options;
  const canAddService = permissions[GOOD_MANAGE.ADD_SERVICE_GOODS];
  const canAddNormal = permissions[GOOD_MANAGE.ADD_NORMAL_GOODS];
  const canTakeawayService = permissions[GOOD_MANAGE.ADD_TAKEAWAY_GOODS];
  // const canTakeawayService = true
  const basicRef = useRef(null);
  const stockRef = useRef(null);
  const settingRef = useRef(null);
  const picturesRef = useRef(null);
  const settleOtrRef = useRef(null);
  const attrRef = useRef(null);
  const takeawayRef = useRef(null);

  const [pageId, setPageId] = useState(null);
  const [categoryIds, setCategoryIds] = useState([]); // 商品品类ID
  const [isEdit, setIsEdit] = useState(false); // 是否是编辑状态
  const [isUseCache, setIsUseCache] = useState(false); // 是否使用缓存
  let ptype = canAddService ? 4 : 5;
  ptype = canAddNormal ? 1 : ptype;
  const [productType, setProductType] = useState(ptype); // 商品状态
  const [pageLoading, setPageLoading] = useState(false); // 页面加载状态
  const [afterAddressList, setAfterAddressList] = useState([]); // 售后地址
  const [supplierIdList, setSupplierIdList] = useState([]); // 适用们店列表

  const [brandList, setBrandList] = useState([]); // 获取商品牌
  const [specList, setSpecList] = useState([]); // 规格列表
  const [editData, setEditData] = useState({}); // 编辑保存数据
  const [newCategoryList, setNewCategoryList] = useState({});
  const [takeawayEditData, setTakeawayEditData] = useState({}); // 外卖编辑保存数据
  const [groupShopData, setGroupShopData] = useState(''); // 从分组进入创建
  const [visibleCacheEdit, setVisibleCacheEdit] = useState(false); // 显示有缓存未保存提示
  const [takeawayInfoMation, setTakeawayInfoMation] = useState({});
  const [checkFormList] = useState([
    basicRef,
    attrRef,
    stockRef,
    settingRef,
    settleOtrRef,
    picturesRef,
    takeawayRef,
  ]);

  const [specKeyList, setSpecKeyList] = useState([]); // 记录一级规格key字段

  const resetForm = () => clearCurrent(checkFormList).forEach(({ current }) => current.reset());

  const onValuesChange = e => {
    if (!isEdit) {
      const typeObj = {
        type: productType,
      };
      if (visibleCacheEdit) {
        setVisibleCacheEdit(false);
        localStorage.remove(localAutoSaveKey);
        onAutoSaveValue(typeObj, !0);
      }
      onAutoSaveValue(Object.assign(typeObj, e));
    }
    if (productType === 5) {
      setTakeawayInfoMation(e);
      if (visibleCacheEdit) {
        setVisibleCacheEdit(false);
        localStorage.remove(localAutoSaveKey);
      }
      // onAutoSaveValue(Object.assign({ type: 5 }, e));
    }
  };

  const productChange = task => {
    setProductType(task.type);
    setPageLoading(true);
    setCategoryIds([]);
    setVisibleCacheEdit(false);
    resetForm();
    const timer = setTimeout(() => {
      setPageLoading(false);
      resetForm();
      clearTimeout(timer);
      onAutoSaveValue(
        {
          type: task.type,
        },
        !0,
      );
      stockRef.current && stockRef.current.onFinish();
    }, 1000);
  };
  // 查询外卖商品详情
  const querGetShopDetail = async params => {
    const { spuId, shopId, skuId } = params;
    const temp = {
      id: spuId,
      shopId,
      skuId,
    };
    const { data } = await apiGetShopDetail(temp);
    const {
      name,
      storageRackIds,
      firstCategoryId,
      secondCategoryId,
      thirdCategoryId,
      commonImageList,
    } = data;
    const categoryId = [firstCategoryId, secondCategoryId, thirdCategoryId].filter(item => !!item);
    const editInfoMation = {
      infoMation: {
        name,
        productRefShopId: `${shopId}`,
        commonImageList,
        categoryId,
        storageRackIds,
        productType: 5,
      },
    };
    setEditData(editInfoMation);
    setTakeawayEditData(data);
    setIsEdit(true);
    setPageLoading(false);
  };
  const onResetData = refresh => {
    setPageId(null);
    setIsEdit(false);
    setProductType(ptype);
    setEditData({});
    setSpecKeyList([]);
    resetForm();
    options.onChange(false, refresh);
  };

  const refreshPageList = (refresh, sendData) => {
    onResetData(refresh);
    // 新增外卖商品 关闭之后列表到跳转对应分组的下
    if (
      !isEdit &&
      sendData &&
      +sendData.type === 5 &&
      sendData.storageRackIds &&
      sendData.storageRackIds.length > 0
    ) {
      PubSub.publish('refreshTakeAway', {
        groupId: sendData.storageRackIds[0],
      });
    }
  };

  const handleCancel = (refresh, sendData) => {
    const info = localStorage.get(localAutoSaveKey);
    if (info && Object.keys(info).length > 1) {
      Modal.confirm({
        title: '确认提示',
        content: '商品信息还未保存，确认关闭弹窗？',
        onOk() {
          refreshPageList(refresh, sendData);
        },
      });
    } else {
      refreshPageList(refresh, sendData);
    }
  };

  // 获取商品牌数据
  const getMerchantBrandList = async () => {
    if (!brandList.length) {
      const result = await merchantBrandList();
      setBrandList(result.data || []);
    }
  };
  // 获取规格列表
  const getMerchantSpecList = async () => {
    if (!specList.length) {
      const result = await merchantSpecList();
      setSpecList(result.data || []);
    }
  };
  const getAfterSalesAddrsPage = async () => {
    if (!afterAddressList.length) {
      const result = await afterSalesAddrsPage();
      setAfterAddressList(result.data.records);
    }
  };

  const sendMerchantProductHttpRequest = async sendData => {
    try {
      setPageLoading(true);
      const sendAsyncHttpRequest = isEdit ? merchantProductEdit : merchantProductAdd;
      const addResponse = await sendAsyncHttpRequest(sendData);
      if (addResponse.data) {
        message.success(`${isEdit ? '修改' : '添加'}成功!`);
        localStorage.remove(localAutoSaveKey);
        handleCancel(true, sendData);
      }
      setPageLoading(false);
    } catch (error) {
      console.log(error);
      setPageLoading(false);
    }
  };

  const shopGetBySupplierIdResponse = async () => {
    if (!supplierIdList.length) {
      const result = await shopGetBySupplierId(3);
      setSupplierIdList(result.data);
    }
  };

  const shopGetByProductType = async type => {
    if (!newCategoryList[type]?.length) {
      const result = await getByProductType(type);
      console.log('result :>> ', result);
      setNewCategoryList({
        ...newCategoryList,
        [type]: result.data || [],
      });
    }
  };
  // 保存商品
  const submitEvent = async () => {
    const checkPromiseList = clearCurrent(checkFormList).map(({ current }) => current.onCheck());
    const resuslt = await Promise.all(checkPromiseList);
    console.log('resuslt :>> ', resuslt);
    if (!resuslt.includes(null)) {
      const params = resuslt.reduce((origin, item) => {
        const { temp, ...other } = item;
        origin[temp] = other;
        return origin;
      }, {});
      const sendData = filterSendData(productType, params);
      if (options.isDraft) {
        sendData.productDraftId = SourceData.id;
      }
      if (productType === 5) {
        if (+sendData?.repertoryType === 2 && sendData?.items?.length < 2) {
          message.error('最少生成2个sku');
          return;
        }
        sendMerchantProductHttpRequest(sendData);
        return;
      }
      if (isEdit) {
        sendData.id = pageId;
      }
      // if (options.isDraft) {
      //   sendData.productDraftId = SourceData.id;
      // }
      console.log('sendData :>> ', sendData);
      sendMerchantProductHttpRequest(sendData);
    }
  };

  const getMerchantgetJdPicList = async params => {
    const result = await merchantgetJdPicList(params);
    if (result) {
      const { detailImageList, imageList } = picturesRef.current.getFieldsValue();
      const detailList = result.detailList || [];
      const newImageList = imageList[result.firstSpecValue];
      const carouseList = result.carouseList || [];
      imageList[result.firstSpecValue] =
        (newImageList ? [...newImageList, ...carouseList] : carouseList) || [];
      picturesRef.current.setFieldsValue({
        imageList,
        detailImageList: [...detailImageList, ...detailList],
      });
    }
  };

  const onSetData = info => {
    if (info.serviceItem) {
      const ptime = info.serviceItem.purchaseTime;
      const utime = info.serviceItem.useTime;
      if (ptime && ptime.length === 2) {
        ptime[0] = moment(ptime[0]);
        ptime[1] = moment(ptime[1]);
      }
      if (utime && utime.length === 2) {
        utime[0] = moment(utime[0]);
        utime[1] = moment(utime[1]);
      }
    }
    setProductType(info.type);
    setEditData(info);
    if (info.infoMation && info.infoMation.categoryId && info.infoMation.categoryId.length) {
      setCategoryIds(info.infoMation.categoryId);
    }
  };

  // 继续编辑(使用缓存数据)
  const onContinueEdit = () => {
    setVisibleCacheEdit(false);
    setIsUseCache(true);
    const info = localStorage.get(localAutoSaveKey);
    if (info && info.type !== 5) {
      onSetData(info);
    }
  };

  useEffect(() => {
    (async () => {
      if (!options.visible) {
        return;
      }
      setPageLoading(true);
      await shopGetBySupplierIdResponse();
      await getMerchantBrandList();
      await getAfterSalesAddrsPage();
      await getMerchantSpecList();
      if (Object.keys(SourceData).length) {
        // 从编辑草稿进入 执行以下代码
        if (options.isDraft) {
          setIsUseCache(true);
          setVisibleCacheEdit(false);
          onSetData(SourceData);
          onValuesChange(SourceData);
          // 外卖类型---
          if (SourceData && SourceData?.type === 5) {
            setTakeawayEditData(SourceData);
            setIsUseCache(true);
          }
        } else {
          setEditData(SourceData);
          setPageId(SourceData.id);
          setProductType(SourceData.productType);
          setCategoryIds(SourceData.infoMation.categoryId || []);
          setIsEdit(true);
        }
      } else {
        // 默认生成一条规格数据
        stockRef.current && stockRef.current.onFinish();
      }
      setPageLoading(false);
    })();
  }, [SourceData]);

  useEffect(() => {
    if (options.visible) {
      shopGetByProductType(productType);
    }
  }, [productType, options.visible]);

  useEffect(() => {
    if (options.visible && !isEdit) {
      const info = localStorage.get(localAutoSaveKey);
      if (info && info.type !== 5) {
        setVisibleCacheEdit(true);
        return;
      }
    }
    setVisibleCacheEdit(false);
  }, [isEdit, options.visible]);

  useEffect(() => {
    setProductType(ptype);
  }, [canAddNormal]);

  const onSpecCommonImgEvent = useCallback(
    keys => {
      setSpecKeyList(keys);
    },
    [specKeyList],
  );
  useEffect(() => {
    // 外卖类型
    if (Object.keys(takeAway)?.length) {
      const { spuId = '', groupId = '' } = takeAway;
      if (spuId) {
        querGetShopDetail(takeAway);
      }
      if (groupId) {
        setGroupShopData(takeAway);
      }
      setProductType(5);
    }
  }, [takeAway]);

  const onEventBus = (event, params) => {
    if (event === 'cloneImg') {
      if (!isUrl(params.skuLink)) {
        notification.open({
          message: '提示',
          description: '请输入正确的URL！',
        });
        return;
      }
      getMerchantgetJdPicList({
        firstSpecId: params.firstSpecId,
        firstSpecValue: params.firstSpecValue,
        secondSpecId: params.secondSpecId,
        secondSpecValue: params.secondSpecValue,
        skuLink: params.skuLink,
        jdSkuInfoUrl: params.skuLink,
      });
    }
  };
  // 切换类目
  const onCategoryChange = e => {
    setCategoryIds(e);
  };

  // 保存草稿
  const onSaveDraft = async () => {
    const info = localStorage.get(localAutoSaveKey);
    if (
      !info ||
      !info.infoMation ||
      !info.infoMation.name ||
      !info.infoMation.categoryId
      // info.infoMation.categoryId.length !== 3 // 不能限制长度必须为3
    ) {
      message.warning('请添加商品类目和名称');
      return;
    }
    Modal.confirm({
      title: '确认提示',
      content: '确定将商品信息保存至草稿箱？',
      onOk: async () => {
        info.type = productType;
        let arr = newCategoryList[info.type];
        const first = arr.find(item => item.id === info.infoMation.categoryId[0]);
        let second = '';
        let third = '';
        if (arr.length) {
          arr = first?.children;
          second = arr?.find(item => item.id === info.infoMation.categoryId[1]) || '';
          arr = second?.children;
          third = arr?.find(item => item.id === info.infoMation.categoryId[2]) || '';
        }
        const params = {
          productName: info.infoMation.name,
          productType: info.type,
          firstCategoryId: info.infoMation.categoryId[0],
          firstCategoryName: first?.name,
          secondCategoryId: info.infoMation.categoryId[1],
          secondCategoryName: second?.name || '',
          thirdCategoryId: info.infoMation.categoryId[2],
          thirdCategoryName: third?.name || '',
          content: JSON.stringify(info),
        };
        console.log('params :>> ', params);
        setPageLoading(true);
        let api = apiCreateDraft;
        if (options.isDraft) {
          params.id = SourceData.id;
          api = apiEditDraft;
        }
        await api(params);
        localStorage.remove(localAutoSaveKey);
        setPageLoading(false);
        message.success('草稿保存成功！');
        handleCancel(true);
      },
    });
  };
  const providerValue = {
    pageId,
    isEdit,
    productType,
    canAddService, // 是否可以添加服务商品(电子卡券)
    canAddNormal, // 是否可以添加实物商品
    canTakeawayService, // 是否可以添加外卖商品
    isCard: productType === 4,
    isTakeawayService: productType === 5,
    // 0, "商品删除" 1, "新建" 2, "提交审核" 3, "待审核" 4, "驳回" 5, "未上架" 6, "已上架" 7, "已下架"
    isNormal: SourceData.state && SourceData.state !== 4, // 商品不是驳回状态
    // 当商品进行编辑 & 类型不为电子卡券 & 商品状态不为驳回 禁用当前功能
    isDisabled: isEdit && productType !== 4 && SourceData.state && SourceData.state !== 4,
    isJDGoods: isEdit && SourceData.pageProductType && +SourceData.pageProductType !== 1,
    isUseCache, // 是否使用缓存数据
    onEventBus,
  };

  return (
    <Modal
      title={isEdit ? '修改商品' : '新增商品'}
      visible={options.visible}
      onCancel={() => handleCancel()}
      destroyOnClose
      width={1050}
      maskClosable={false}
      keyboard={false}
      footer={[
        !isEdit && (
          <Button key="draft" type="primary" ghost loading={pageLoading} onClick={onSaveDraft}>
            保存草稿
          </Button>
        ),
        <Button key="submit" type="primary" loading={pageLoading} onClick={submitEvent}>
          提交
        </Button>,
        <Button key="back" onClick={() => handleCancel()}>
          返回
        </Button>,
      ]}
    >
      <Spin tip="正在加载..." spinning={pageLoading} delay={100}>
        <WrapperContainer>
          {visibleCacheEdit && (
            <div className={styles.draftBox}>
              有未保存内容。是否
              <span className={styles.conEdit} onClick={onContinueEdit}>
                继续编辑
              </span>
            </div>
          )}
          <ServiceContext.Provider value={providerValue}>
            <Title title="商品类型" />
            <TaskTypeSelect
              productType={productType}
              takeAway={takeAway}
              onChange={productChange}
            />

            <Title title="商品基本信息编辑" />
            <FormInformationBasic
              ref={basicRef}
              editData={editData.infoMation}
              groupShopData={groupShopData}
              newCategoryList={newCategoryList}
              shopGetByProductType={shopGetByProductType}
              categoryList={categoryList}
              virtualCategoryList={virtualCategoryList}
              brandList={brandList}
              afterAddressList={afterAddressList}
              specListData={specListData}
              onCategoryChange={onCategoryChange}
              onValuesChange={onValuesChange}
              // queryShopList={queryShopList}
            />

            {[1, 2].includes(productType) && [
              <Title title="商品属性" key="attrtitle" />,
              <FormAttr
                key="attr"
                ref={attrRef}
                categoryIds={categoryIds}
                initData={editData}
                onValuesChange={onValuesChange}
              />,
            ]}
            {productType !== 5 && (
              <>
                <Title title="价格与库存" />
                <FormPriceOrStock
                  ref={stockRef}
                  specList={specList}
                  onSpecChange={onSpecCommonImgEvent}
                  editData={editData.infoSpecData}
                  skuList={editData.skuList}
                  onValuesChange={onValuesChange}
                />
              </>
            )}
            {productType !== 5 && (
              <>
                <Title title="规则设置" />
                {productType === 4 && (
                  <FormRuleSetting
                    ref={settingRef}
                    editData={editData.serviceItem}
                    supplierIdList={supplierIdList}
                    onValuesChange={onValuesChange}
                  />
                )}
              </>
            )}
            {productType !== 5 && (
              <>
                <FormRuleVPictures
                  ref={picturesRef}
                  specKeyItem={specKeyList}
                  editData={editData.infoImageData}
                  onValuesChange={onValuesChange}
                />
              </>
            )}

            {productType === 4 && (
              <FormSettlementOthers
                ref={settleOtrRef}
                editData={editData.settlementItem}
                onValuesChange={onValuesChange}
              />
            )}
            {productType === 5 && (
              <>
                <FormTakeaway
                  ref={takeawayRef}
                  takeAway={takeAway}
                  editData={takeawayEditData}
                  takeawayInfoMation={takeawayInfoMation}
                  supplierIdList={supplierIdList}
                  onValuesChange={onValuesChange}
                />
              </>
            )}
          </ServiceContext.Provider>
        </WrapperContainer>
      </Spin>
    </Modal>
  );
};

export default ServiceGoods;
