import { Button, message, Tabs, TabsProps } from 'antd';
import { useEffect, useRef, useState } from 'react';
import BaseInfo from './components/baseInfo';
import SkuInfo from './components/skuInfo';
import IntroduceInfo from './components/introduceInfo';
import './index.scss';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { InterDataType } from '~/api/interface';
import { mallGoodsDetailsType } from '~/api/interface/goodsType';
import GoodsAPI from '~/api/modules/goodsAPI';
import { filterObjAttr } from '~/utils';
import { isArray } from 'lodash';

//商品详情-返回类型
type goodsDetailType = InterDataType<mallGoodsDetailsType>;

const GoodsAddOrEditOrDetail = () => {
  const baseInfoRef = useRef<any>();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const skuInfoRef = useRef<any>();

  const [tabSelectKeys, setTabSelectKeys] = useState<string>('1');
  //商品介绍详情
  const [goodsDetails, setGoodsDetails] = useState<string>('');
  //商品id
  const [goodsId, setGoodsId] = useState<number>(0);
  //商品详情
  const [goodsDetailsInfo, setGoodsDetailsInfo] = useState<goodsDetailType>();

  //商品详情获取
  const getIntroduceInfo = (richText: string) => {
    setGoodsDetails(richText);
  };

  const tabItems: TabsProps['items'] = [
    {
      key: '1',
      label: `基础信息`,
      children: <BaseInfo ref={baseInfoRef} />,
    },
    {
      key: '2',
      label: `商品规格`,
      children: <SkuInfo ref={skuInfoRef} goodsDetailsInfo={goodsDetailsInfo} />,
    },
    {
      key: '3',
      label: `商品详情`,
      children: <IntroduceInfo onChange={getIntroduceInfo} introduceInfo={goodsDetails} />,
    },
  ];

  //tab 切换
  const tabSelectChange = (key: string) => {
    setTabSelectKeys(key);
  };
  //下一步
  const toNextStep = () => {
    switch (tabSelectKeys) {
      case '1':
        baseInfoRef.current
          .getForm()
          .validateFields()
          .then(() => {
            setTabSelectKeys((Number(tabSelectKeys) + 1).toString());
          })
          .catch((error: any) => {
            message.error(error.errorFields[0].errors[0]);
          });
        break;
      case '2':
        skuInfoRef.current
          .submitSku()
          .then(() => {
            setTabSelectKeys((Number(tabSelectKeys) + 1).toString());
          })
          .catch((error: any) => {
            message.warning(error?.errorFields?.[0].errors[0] || error);
          });
        break;
      case '3':
        break;
      default:
        break;
    }
  };
  //上一步
  const toBackStep = () => {
    setTabSelectKeys((Number(tabSelectKeys) - 1).toString());
  };
  const backRoute = () => {
    navigate(-1);
  };

  //商品保存
  const saveGoods = () => {
    Promise.all([
      baseInfoRef.current.getForm().validateFields(),
      skuInfoRef.current ? skuInfoRef.current.submitSku() : getDefaultSku(),
    ])
      .then((values: any) => {
        const addGoodsEditReq = {
          ...filterObjAttr(values[0], ['mainImgList', 'subImgList', 'videoList', 'categoryId']),
          resourcesList: [
            ...values[0].mainImgList.map((v: any) => ({ type: 0, url: v.url })),
            ...(values[0].subImgList?.map((v: any) => ({ type: 1, url: v.url })) || []),
            ...(values[0].videoList?.map((v: any) => ({ type: 2, url: v.url })) || []),
          ],
          categoryPrimaryId: values[0].categoryId[0],
          categorySubId: values[0].categoryId.length === 2 ? values[0].categoryId[1] : undefined,
          goodsDetails,
          ...values[1],
          priceStock: values[1].priceStock?.map((v: any) => ({
            ...v,
            skuImage: isArray(v.skuImage) ? v.skuImage?.[0]?.url : v.skuImage,
          })),
          id: goodsId || undefined,
        };
        // console.log('addGoodsEditReq ===>', addGoodsEditReq);
        GoodsAPI[goodsId ? 'editMallGoods' : 'addMallGoods'](addGoodsEditReq).then(({ code }) => {
          if (code === '200') {
            message.success(goodsId ? '编辑商品成功' : '新增商品成功').then();
            navigate(-1);
          }
        });
      })
      .catch((error: any) => {
        baseInfoRef.current
          .getForm()
          .validateFields()
          .then(() => {
            setTabSelectKeys('2');
          })
          .catch(() => {
            setTabSelectKeys('1');
          });
        message.error(error?.errorFields?.[0].errors[0] || error);
      });
  };
  //商品详情
  const getMallGoodsDetails = (id: number) => {
    GoodsAPI.getMallGoodsDetails({ id }).then(({ result }) => {
      const mainImgList = result.resourcesList
        .filter((v) => v.type === 0)
        .map((v) => ({ id: v.id, name: 'mainImg', uid: v.id, url: v.url }));
      const subImgList = result.resourcesList
        .filter((v) => v.type === 1)
        .map((v) => ({ id: v.id, name: 'subImg', uid: v.id, url: v.url }));
      const videoList = result.resourcesList
        .filter((v) => v.type === 2)
        .map((v) => ({ id: v.id, name: 'video', uid: v.id, url: v.url }));
      setGoodsDetailsInfo(JSON.parse(JSON.stringify(result)));
      setGoodsDetails(result.goodsDetails || '');
      baseInfoRef.current.getForm().setFieldsValue({
        tradeName: result.tradeName,
        description: result.description || undefined,
        mainImgList,
        subImgList: subImgList.length ? subImgList : undefined,
        videoList: videoList.length ? videoList : undefined,
        categoryId: result.categorySubId
          ? [result.categoryPrimaryId, result.categorySubId]
          : [result.categoryPrimaryId],
        shelfStatus: result.shelfStatus,
        labelShow: result.labelShow,
        goodsLabel: result.goodsLabel || undefined,
        priceShow: result.priceShow,
        recommend: result.recommend,
      });
      baseInfoRef.current.setLabelShow(!!result.labelShow);
      baseInfoRef.current.mediaData.setMainFileList(mainImgList);
      baseInfoRef.current.mediaData.setSubFileList(subImgList);
      baseInfoRef.current.mediaData.setVideoFileList(videoList);
    });
  };
  //编辑未点击规格时数据处理
  const getDefaultSku = () => {
    return new Promise((resolve, reject) => {
      if (goodsDetailsInfo) {
        resolve({
          priceStock: goodsDetailsInfo.priceStock,
          specAttrList: goodsDetailsInfo.specAttrList,
        });
      } else {
        reject('请上传商品规格');
      }
    });
  };

  useEffect(() => {
    if (searchParams.get('id')) {
      setGoodsId(Number(searchParams.get('id')));
      getMallGoodsDetails(Number(searchParams.get('id')));
    }
  }, []);

  return (
    <div className='goods-operate-wrap'>
      <Tabs items={tabItems} activeKey={tabSelectKeys} onChange={tabSelectChange}></Tabs>
      <div className='next-step'>
        {tabSelectKeys !== '1' ? <Button onClick={toBackStep}>上一步</Button> : ''}
        {tabSelectKeys !== '3' ? (
          <Button type='primary' onClick={toNextStep}>
            下一步
          </Button>
        ) : (
          ''
        )}
      </div>
      <div className='back-btn'>
        <Button type='primary' onClick={saveGoods} style={{ marginRight: '10px' }}>
          保存
        </Button>
        <Button type='default' onClick={backRoute}>
          返回
        </Button>
      </div>
    </div>
  );
};
export default GoodsAddOrEditOrDetail;
