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 } from 'react-router-dom';
import { baseInfoType } from './components/baseInfo';
import { InterDataType, InterReqType } from '~/api/interface';
import { addMallGoodsType, skuUnitType } from '~/api/interface/goodsType';
import GoodsAPI from '~/api/modules/goodsAPI';

//商品sku规格类型
type goodsSpecType = InterReqType<addMallGoodsType>['goodsSpecList'][0];
//单位返回类型
type unitType = InterDataType<skuUnitType>;

const GoodsAddOrEditOrDetail = () => {
  const baseInfoRef = useRef<any>();
  const navigate = useNavigate();

  //单位列表
  const [skuUnitList, setSkuUnitList] = useState<unitType>([]);
  const [tabSelectKeys, setTabSelectKeys] = useState<string>('1');
  //新增、编辑sku弹窗
  const [addOrEditSkuModalShow, setAddOrEditSkuModalShow] = useState<boolean>(false);
  //当前编辑sku
  const [currentSku, setCurrentSku] = useState<goodsSpecType>();
  //基本信息暂存
  const [baseInfo, setBaseInfo] = useState<baseInfoType>();
  //skuTable数据
  const [skuTable, setSkuTable] = useState<goodsSpecType[]>([]);

  //新增、编辑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 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 />,
    },
  ];

  //tab 切换
  const tabSelectChange = (key: string) => {
    setTabSelectKeys(key);
  };
  //下一步
  const toNextStep = () => {
    switch (tabSelectKeys) {
      case '1':
        baseInfoRef.current
          .getForm()
          .validateFields()
          .then((value: baseInfoType) => {
            setBaseInfo(value);
            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 || []);
    });
  };

  useEffect(() => {
    getSkuUnit();
  }, []);

  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>
        ) : (
          <Button type='primary'>保存</Button>
        )}
      </div>
      <div className='back-btn'>
        <Button type='primary' onClick={backRoute}>
          返回
        </Button>
      </div>
      {/*新增、编辑sku弹窗*/}
      <SkuAddOrEditModal
        open={addOrEditSkuModalShow}
        onCancel={addOrEditSkuModalCancel}
        onOk={addOrEditSkuModalOk}
        skuUnitList={skuUnitList}
        currentSku={currentSku}
      />
    </div>
  );
};
export default GoodsAddOrEditOrDetail;
