import BaseInfo from '~/components/goods/commonAddOrEdit/baseInfo';
import StockSku from '~/components/goods/commonAddOrEdit/stockSku';
import OtherInfo from '~/components/goods/commonAddOrEdit/otherInfo';
import GoodsIntroduce from '~/components/goods/commonAddOrEdit/goodsIntroduce';
import AddOrEditSkuModal from '~/components/goods/commonAddOrEdit/addOrEditSkuModal';
import { Button, message } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import './index.scss';
import { useEffect, useRef, useState } from 'react';
import { CategoryManageAPI } from '~/api';
import { InterDataType } from '~/api/interface';
import { categoryListType } from '~/api/interface/categoryManage';
import {
  customizeEntity,
  detailGoodsType,
  skuUnitType,
  specEntity,
} from '~/api/interface/goodsType';
import goodsAPI from '~/api/modules/goodsAPI';
import { filterObjAttr } from '~/utils';
import GoodsAPI from '~/api/modules/goodsAPI';
import { UploadFile } from 'antd/es/upload/interface';

//分类返回类型
type categoryType = InterDataType<categoryListType>['list'];
//产品-规格单位返回类型
type unitType = InterDataType<skuUnitType>;
//商品返回类型
type goodsDetailType = InterDataType<detailGoodsType>;

const GoodsAddOrEditOrDetail = () => {
  const [searchParams] = useSearchParams();
  //基本信息ref
  const baseInfoRef = useRef<any>();

  const navigate = useNavigate();
  //当前目录
  const [currentDesc, setCurrentDesc] = useState<number>(-1);
  //分类
  const [categoryList, setCategoryList] = useState<categoryType>([]);
  //添加、编辑库存规格弹窗
  const [addOrEditSkuModalShow, setAddOrEditSkuModalShow] = useState(false);
  //库存规格数据
  const [specData, setSpecData] = useState<specEntity[]>([]);
  const [goodsSpecCopy, setGoodsSpecCopy] = useState<specEntity[]>([]);
  //产品规格-单位
  const [skuUnitList, setSkuUnitList] = useState<unitType>([]);
  //其它服务
  const [otherService, setOtherService] = useState<number[]>([]);
  // 当前操作行数据
  const [curtRowData, setCurtRowData] = useState<Partial<specEntity>>({});
  //商品详情
  const [goodsDetail, setGoodsDetail] = useState<goodsDetailType>();
  //产品介绍
  const [productIntroduce, setProductIntroduce] = useState<string>('');
  //是否商品详情
  const [isDetail, setIsDetail] = useState<boolean>(false);

  //添加、编辑规格
  const addOrEditSkuShowEvent = (record?: specEntity) => {
    const baseInfoForm = baseInfoRef.current.baseInform;
    setCurrentDesc(baseInfoForm.getFieldValue('directoryId') || -1);
    if (!baseInfoForm.getFieldValue('directoryId')) {
      return message.warning('请先选择目录');
    }
    if (record) {
      setCurtRowData({ ...record });
    }
    setAddOrEditSkuModalShow(true);
  };
  //删除规格
  const deleteSkuEvent = (record: specEntity) => {
    const index = specData.findIndex((v) => v.id === record.id);
    specData.splice(index, 1);
    setSpecData(specData);
  };
  const addOrEditSkuModalCancel = () => {
    setAddOrEditSkuModalShow(false);
  };
  const addOrEditSkuModalOk = (data: specEntity) => {
    if (Object.keys(curtRowData).length != 0) {
      const index: number = specData.findIndex((i) => i.id === data.id);
      specData.splice(index, 1, data);
      setSpecData([...specData]);
    } else {
      setSpecData([...specData, data]);
    }
    setAddOrEditSkuModalShow(false);
  };
  //根据目录获取分类列表
  const getCategoryList = (directoryId: number) => {
    CategoryManageAPI.getCategoryList({ directoryId, type: 2, pageSize: 9999, pageNo: 1 }).then(
      ({ result }) => {
        setCategoryList(result.list || []);
      },
    );
  };
  //产品-单位
  const getSkuUnit = () => {
    goodsAPI.getSkuUnit().then(({ result }) => {
      setSkuUnitList(result || []);
    });
  };
  //其它服务选择
  const otherServiceSelect = (ids: number[]) => {
    setOtherService(ids);
  };
  //获取产品详情
  const getRichText = (html?: string) => {
    setProductIntroduce(html || '');
  };
  //商品详情
  const getGoodsDetail = (goodsInfoId: number) => {
    GoodsAPI.getGoodsDetail({ goodsInfoId, type: 1, leaseTerm: 0 }).then(({ result }) => {
      setGoodsDetail(result);
      getCategoryList(result.directoryId);
      const specList: specEntity[] = result.goodsSpec.reduce((pre: any, cur: specEntity) => {
        // 自定义
        if (cur.flag === 1) {
          const cusList: customizeEntity[] =
            cur.productSpecList &&
            cur.productSpecList.reduce((preProd: any, curProd: customizeEntity, index: number) => {
              const obj: UploadFile = {
                uid: `img${index}`,
                status: 'done',
                url: curProd.specImage,
                name: 'image',
              };
              preProd.push({ ...curProd, fileList: [obj] });
              return preProd;
            }, []);
          cur.customizeInfo = cusList;
        } else {
          const specId: number[] =
            result.directoryId === 2
              ? cur.industrySpecList &&
                cur.industrySpecList.map((curIndu: any) => {
                  return {
                    mallSpecId: curIndu.industrySpecId,
                    specName: curIndu.specName,
                    partNo: curIndu.partNo,
                    id: curIndu.id,
                  };
                })
              : cur.productSpecList &&
                cur.productSpecList.map((item: any) => {
                  return {
                    mallSpecId: item.productSpec,
                    specName: item.specName,
                    partNo: item.partNo,
                    id: item.id,
                  };
                });
          cur.specIds = specId;
        }
        pre.push({ ...cur, productName: cur.skuName });
        return pre;
      }, []);
      setGoodsSpecCopy(result.goodsSpec);
      setSpecData(specList);
    });
  };
  //保存
  const saveSubmit = () => {
    const baseInfoForm = baseInfoRef.current.baseInform;
    baseInfoForm.validateFields().then((values: any) => {
      if (specData.length === 0) {
        return message.warning('清添加库存规格');
      }
      //主图
      values.images = [
        {
          imgType: 0,
          imgUrl: values.mainImg[0].url,
          id: goodsDetail ? values.mainImg[0].id : undefined,
        },
      ];
      //副图
      if (values.subImg) {
        values.images.push(
          ...values.subImg.map((v: any) => ({
            imgType: 1,
            imgUrl: v.url,
            id: goodsDetail
              ? goodsDetail.images.some((i) => i.id === v.id)
                ? v.id
                : undefined
              : undefined,
          })),
        );
      }
      //分类
      values.categoryByOne = values.masterTypeId[0];
      values.categoryByTne = values.masterTypeId[1] || undefined;
      // 过滤对象属性
      const goodsSpecVO: specEntity[] = specData.reduce((pre: any, cur: specEntity) => {
        cur.customizeInfo = cur.customizeInfo?.reduce((cusPre: any, cusCur: customizeEntity) => {
          const bol: boolean = goodsSpecCopy.some((i: specEntity) => {
            return i.customizeInfo?.some((i: customizeEntity) => i.id === cusCur.id);
          });
          cusPre = [
            ...cusPre,
            bol ? filterObjAttr(cusCur, ['fileList']) : filterObjAttr(cusCur, ['id', 'fileList']),
          ];
          return cusPre;
        }, []);
        // 存在对象属性改变！
        cur.specIds = cur.specIds?.reduce((preSpec: any, curSpec: any) => {
          preSpec = [...preSpec, filterObjAttr(curSpec, ['specName', 'partNo'])];
          return preSpec;
        }, []);
        // 是否新增
        const isAdd: boolean = goodsSpecCopy.every((i: specEntity) => i.id != cur.id);
        // 是否修改了某一条
        const isEdit: boolean = goodsSpecCopy.every(
          (i: specEntity) => i.categoryId != cur.categoryId,
        );
        pre = [
          ...pre,
          !isAdd
            ? isEdit
              ? filterObjAttr(cur, ['industrySpecList', 'productSpecList', 'skuName', 'id'])
              : filterObjAttr(cur, ['industrySpecList', 'productSpecList', 'skuName'])
            : filterObjAttr(cur, ['id', 'skuName']),
        ];
        return pre;
      }, []);
      goodsAPI[goodsDetail ? 'editGoods' : 'addGoods']({
        ...filterObjAttr(values, ['mainImg', 'subImg', 'video', 'masterTypeId', 'id', 'goodsDesc']),
        productSpec: goodsSpecVO,
        goodsType: 1,
        goodsDetailVO: { goodsDesc: values.goodsDesc, productDesc: productIntroduce },
        otherService: otherService,
        id: goodsDetail ? goodsDetail.id : undefined,
      }).then(({ code }) => {
        if (code === '200') {
          message.success(goodsDetail ? '编辑成功' : '新增成功');
          navigate(-1);
        }
      });
    });
  };
  //返回
  const backRoute = () => {
    navigate(-1);
  };
  useEffect(() => {
    if (searchParams.get('id')) {
      getGoodsDetail(Number(searchParams.get('id')));
    }
    setIsDetail(!!searchParams.get('isDetail'));
    getSkuUnit();
  }, []);
  return (
    <div className='goods-info'>
      {/*  基本信息*/}
      <BaseInfo
        ref={baseInfoRef}
        categoryList={categoryList}
        getCategoryList={getCategoryList}
        goodsDetail={goodsDetail}
        isDetail={isDetail}
        goodsType={1}
      />
      {/* 库存规格*/}
      <StockSku
        addOrEditSku={addOrEditSkuShowEvent}
        specData={specData}
        categoryList={categoryList}
        skuUnitList={skuUnitList}
        deleteSku={deleteSkuEvent}
        isDetail={isDetail}
      />
      {/*其它信息*/}
      <OtherInfo
        otherServiceSelect={otherServiceSelect}
        goodsDetail={goodsDetail}
        isDetail={isDetail}
      />
      {/*产品介绍图*/}
      <GoodsIntroduce getRichText={getRichText} goodsDetail={goodsDetail} isDetail={isDetail} />
      {/*库存规格，添加、编辑弹窗*/}
      <AddOrEditSkuModal
        currentDesc={currentDesc}
        open={addOrEditSkuModalShow}
        handleCancel={addOrEditSkuModalCancel}
        handleOk={addOrEditSkuModalOk}
        categoryList={categoryList}
        skuUnitList={skuUnitList}
        curtRowData={curtRowData}
        goodsType={1}
      />
      <div className='goods-info-operate'>
        {!isDetail && (
          <Button type='primary' onClick={saveSubmit}>
            保存
          </Button>
        )}
        <Button onClick={backRoute}>返回</Button>
      </div>
    </div>
  );
};
export default GoodsAddOrEditOrDetail;
