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 SkuAddOrEditModal from './components/skuAddOrEditModal';
import './index.scss';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { baseInfoType } from './components/baseInfo';
import { InterDataType, InterReqType } from '~/api/interface';
import { addMallGoodsType, mallGoodsDetailsType, skuUnitType } from '~/api/interface/goodsType';
import GoodsAPI from '~/api/modules/goodsAPI';
import { filterObjAttr } from '~/utils';

//商品sku规格类型
type goodsSpecType = Exclude<InterReqType<addMallGoodsType>, undefined>['goodsSpecList'][0];
//单位返回类型
type unitType = InterDataType<skuUnitType>;
//商品详情-返回类型
type goodsDetailType = InterDataType<mallGoodsDetailsType>;

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

  //单位列表
  const [skuUnitList, setSkuUnitList] = useState<unitType>([]);
  const [tabSelectKeys, setTabSelectKeys] = useState<string>('1');
  //新增、编辑sku弹窗
  const [addOrEditSkuModalShow, setAddOrEditSkuModalShow] = useState<boolean>(false);
  //当前编辑sku
  const [currentSku, setCurrentSku] = useState<goodsSpecType>();
  //skuTable数据
  const [skuTable, setSkuTable] = useState<goodsSpecType[]>([]);
  //商品介绍详情
  const [goodsDetails, setGoodsDetails] = useState<string>('');
  //商品id
  const [goodsId, setGoodsId] = useState<number>(0);
  //商品详情
  const [goodsDetailsInfo, setGoodsDetailsInfo] = useState<goodsDetailType>();

  //新增、编辑sku弹窗显示
  const addOrEditSkuClick = (record?: goodsSpecType) => {
    setCurrentSku(record ? { ...record } : undefined);
    setAddOrEditSkuModalShow(true);
  };
  const addOrEditSkuModalCancel = () => {
    setAddOrEditSkuModalShow(false);
  };
  const addOrEditSkuModalOk = (values: goodsSpecType) => {
    setAddOrEditSkuModalShow(false);
    const skuTableIndex: number = skuTable.findIndex((v) => v.id === values.id);
    if (skuTableIndex !== -1) {
      skuTable.splice(skuTableIndex, 1, values);
      setSkuTable([...skuTable]);
    } else {
      setSkuTable([...skuTable, { ...values }]);
    }
  };
  //sku删除
  const deleteSkuClick = (record: goodsSpecType) => {
    const skuIndex: number = skuTable.findIndex((v) => v.id === record.id);
    skuTable.splice(skuIndex, 1);
    setSkuTable([...skuTable]);
  };
  //商品详情获取
  const getIntroduceInfo = (richText: string) => {
    setGoodsDetails(richText);
  };

  const tabItems: TabsProps['items'] = [
    {
      key: '1',
      label: `基础信息`,
      children: <BaseInfo ref={baseInfoRef} />,
    },
    {
      key: '2',
      label: `商品规格`,
      children: (
        <SkuInfo
          addOrEditSkuClick={addOrEditSkuClick}
          skuTableData={skuTable}
          skuUnitList={skuUnitList}
          deleteSkuClick={deleteSkuClick}
          editSkuClick={addOrEditSkuClick}
        />
      ),
    },
    {
      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':
        if (skuTable.length) {
          setTabSelectKeys((Number(tabSelectKeys) + 1).toString());
        } else {
          message.warning('请添加规格');
        }
        break;
      case '3':
        break;
      default:
        break;
    }
  };
  //上一步
  const toBackStep = () => {
    setTabSelectKeys((Number(tabSelectKeys) - 1).toString());
  };
  const backRoute = () => {
    navigate(-1);
  };
  //单位列表
  const getSkuUnit = () => {
    GoodsAPI.getSkuUnit().then(({ result }) => {
      setSkuUnitList(result || []);
    });
  };

  //商品保存
  const saveGoods = () => {
    baseInfoRef.current
      .getForm()
      .validateFields()
      .then((values: baseInfoType) => {
        if (skuTable.length) {
          const skuList = skuTable.map((v) => ({
            ...v,
            id: goodsDetailsInfo
              ? goodsDetailsInfo.goodsSpecList.find((i) => i.id === v.id)?.id
              : undefined,
            goodsSpecValuesList: v.goodsSpecValuesList.map((i) => ({
              ...i,
              id: goodsDetailsInfo
                ? goodsDetailsInfo.goodsSpecList
                    .find((j) => j.id === v.id)
                    ?.goodsSpecValuesList.find((k) => k.id === i.id)?.id
                : undefined,
              goodsSpecId: goodsDetailsInfo
                ? goodsDetailsInfo.goodsSpecList.find((i) => i.id === v.id)?.id
                : undefined,
            })),
          }));
          const addGoodsEditReq = {
            ...filterObjAttr(values, ['mainImgList', 'subImgList', 'videoList', 'categoryId']),
            resourcesList: [
              ...values.mainImgList.map((v) => ({ type: 0, url: v.url })),
              ...(values.subImgList?.map((v) => ({ type: 1, url: v.url })) || []),
              ...(values.videoList?.map((v) => ({ type: 2, url: v.url })) || []),
            ],
            categoryPrimaryId: values.categoryId[0],
            categorySubId: values.categoryId.length === 2 ? values.categoryId[1] : undefined,
            goodsDetails,
            goodsSpecList: skuList,
            id: goodsId || undefined,
          };
          GoodsAPI[goodsId ? 'editMallGoods' : 'addMallGoods'](addGoodsEditReq).then(({ code }) => {
            if (code === '200') {
              message.success(goodsId ? '编辑商城成功' : '新增商品成功');
              navigate(-1);
            }
          });
        } else {
          message.warning('商品规格未添加');
        }
      })
      .catch((error: any) => {
        message.error(error.errorFields[0].errors[0]);
      });
  };
  //商品详情
  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)));
      setSkuTable(result.goodsSpecList);
      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,
      });
      baseInfoRef.current.setLabelShow(!!result.labelShow);
      baseInfoRef.current.mediaData.setMainFileList(mainImgList);
      baseInfoRef.current.mediaData.setSubFileList(subImgList);
      baseInfoRef.current.mediaData.setVideoFileList(videoList);
    });
  };

  useEffect(() => {
    getSkuUnit();
    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>
      {/*新增、编辑sku弹窗*/}
      <SkuAddOrEditModal
        open={addOrEditSkuModalShow}
        onCancel={addOrEditSkuModalCancel}
        onHandleOk={addOrEditSkuModalOk}
        skuUnitList={skuUnitList}
        currentSku={currentSku}
      />
    </div>
  );
};
export default GoodsAddOrEditOrDetail;
