import { useSearchParams, useNavigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import GoodsAPI from '~/api/modules/goodsAPI';
import { InterDataType, InterReqType } from '~/api/interface';
import { addMallGoodsType, mallGoodsDetailsType } from '~/api/interface/goodsType';
import { Badge, Button, Descriptions, Image, Table } from 'antd';
import { CategoryManageAPI } from '~/api';
import { categoryListRespType } from '~/api/interface/categoryManage';
import './index.scss';

//详情返回类型
type detailType = InterDataType<mallGoodsDetailsType>;
//分类返回类型
type categoryType = InterDataType<categoryListRespType>['list'];
//规格表格类型
type skuTableType = Exclude<InterReqType<addMallGoodsType>, undefined>['priceStock'][0] & {
  fileList: {
    id: number;
    name: string;
    uid: number;
    url: string;
  }[];
};
//规格表单数据类型
type specificationFormListType = {
  optionList: { label: string; value: string }[];
  id: number;
  name: string;
  addSpecificationValueShow: boolean;
  specificationValueList: { name: string; id: number; specificationName: string }[];
};

const GoodsDetails = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  //分类列表
  const [categoryList, setCategoryList] = useState<categoryType>([]);

  //表格数据
  const [tableData, setTableData] = useState<(skuTableType & { [key: string]: string })[]>([]);
  const [goodsInfoDetails, setGoodsInfoDetails] = useState<detailType>();
  const [tableColumns, setTableColumns] = useState<any>([
    {
      title: '商品规格',
      align: 'center',
      dataIndex: 'specName',
      children: [],
    },
    {
      title: '图片',
      align: 'center',
      dataIndex: 'skuImage',
      render: (text: string) => <Image src={text} width={50} height={50} alt='暂无图片' />,
    },
    {
      title: 'sku编号',
      align: 'center',
      dataIndex: 'skuNo',
    },
    {
      title: '销售价',
      align: 'center',
      dataIndex: 'salePrice',
    },
    {
      title: '渠道价',
      align: 'center',
      dataIndex: 'channelPrice',
    },
    {
      title: '库存',
      align: 'center',
      dataIndex: 'stock',
    },
  ]);
  const getGoodsDetails = (id: number) => {
    GoodsAPI.getMallGoodsDetails({ id }).then(({ result }) => {
      setGoodsInfoDetails(result);
      //转化数据
      const covertSpecAttrList = result.specAttrList.map((v, index) => ({
        id: v.id,
        name: 'specName' + index,
        optionList: [{ label: v.specName, value: v.specName }],
        specificationValueList: v.specValuesList.map((i) => ({
          id: i.id,
          name: i.specName,
          specificationName: v.specName,
        })),
        addSpecificationValueShow: false,
      }));
      mergeTableRow(covertSpecAttrList);
      const tableDataList: (skuTableType & { [key: string]: string })[] = result.priceStock.map(
        (v) => ({
          id: v.id,
          salePrice: v.salePrice,
          skuImage: v.skuImage,
          skuNo: v.skuNo,
          stock: v.stock,
          channelPrice: v.channelPrice,
          fileList: v.skuImage
            ? [{ id: Math.random(), uid: Math.random(), url: v.skuImage, name: '规格图片' }]
            : [],
          ...Object.getOwnPropertyNames(JSON.parse(v.productSpec)).reduce(
            (pre: any, cur, currentIndex) => {
              pre['name' + (currentIndex + 1)] = JSON.parse(v.productSpec)[cur];
              pre['specificationName' + (currentIndex + 1)] = cur;
              return pre;
            },
            {},
          ),
        }),
      );
      setTableData(tableDataList);
    });
  };
  //表头拆分及合并列
  const mergeTableRow = (filterSpecificationFormList: specificationFormListType[]) => {
    const columns = filterSpecificationFormList.map((v, index) => ({
      title: v.optionList[0].value,
      dataIndex: 'name' + (index + 1),
      align: 'center',
      onCell: (_: any, i: number) => {
        //合并列
        if (index < filterSpecificationFormList.length - 1) {
          const count: number = filterSpecificationFormList
            .slice(index + 1, filterSpecificationFormList.length)
            .reduce((pre: number, cur) => {
              return pre * cur.specificationValueList.length;
            }, 1);
          return {
            rowSpan: count !== 1 ? ((i + 1) % count === 1 ? count : 0) : 1,
          };
        } else {
          return {
            rowSpan: 1,
          };
        }
      },
    }));
    tableColumns[0].children = columns;
    setTableColumns([...tableColumns]);
  };
  //分类列表
  const getCategoryList = () => {
    CategoryManageAPI.getCategoryRespList({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      setCategoryList(result.list || []);
    });
  };
  //返回
  const backRoute = () => {
    navigate(-1);
  };

  useEffect(() => {
    getGoodsDetails(Number(searchParams.get('id')));
    getCategoryList();
  }, []);
  return (
    <div className='goods-detail'>
      <div className='goods-detail-info'>
        <Descriptions title='基本信息' bordered>
          <Descriptions.Item label='商品名称'>{goodsInfoDetails?.tradeName}</Descriptions.Item>
          <Descriptions.Item label='商品副图'>
            {goodsInfoDetails?.resourcesList
              .filter((v) => v.type === 1)
              .map((v) => (
                <Image src={v.url} width={50} height={50} key={v.id} />
              ))}
          </Descriptions.Item>
          <Descriptions.Item label='商品主图'>
            {goodsInfoDetails?.resourcesList
              .filter((v) => v.type === 0)
              .map((v) => (
                <Image src={v.url} width={50} height={50} key={v.id} />
              ))}
          </Descriptions.Item>
          <Descriptions.Item label='商品标签'>
            {goodsInfoDetails?.goodsLabel || '暂无'}
          </Descriptions.Item>
          <Descriptions.Item label='商品分类'>
            {categoryList
              .reduce((pre: string[], cur) => {
                if (cur.id === goodsInfoDetails?.categoryPrimaryId) {
                  pre.push(cur.name);
                  if (goodsInfoDetails?.categorySubId) {
                    pre.push(
                      cur.subDTOList.find((v) => v.id === goodsInfoDetails?.categorySubId)?.name ||
                        '',
                    );
                  }
                }
                return pre;
              }, [])
              .join('/')}
          </Descriptions.Item>
          <Descriptions.Item label='商品状态'>
            <Badge
              status={goodsInfoDetails?.shelfStatus ? 'processing' : 'default'}
              text={goodsInfoDetails?.shelfStatus ? '上架中' : '已下架'}
            />
          </Descriptions.Item>
          <Descriptions.Item label='商品视频' span={1}>
            {goodsInfoDetails?.resourcesList
              .filter((v) => v.type === 2)
              .map((v) => (
                <video
                  src={v.url}
                  key={v.id}
                  style={{ width: '200px', height: '200px' }}
                  controls
                />
              ))}
          </Descriptions.Item>
          <Descriptions.Item label='商品描述'>{goodsInfoDetails?.description}</Descriptions.Item>
        </Descriptions>
      </div>
      <div className='goods-detail-sku'>
        <div className='sku-title'>商品规格</div>
        <Table
          bordered
          columns={tableColumns}
          dataSource={tableData}
          rowKey='id'
          pagination={false}
        ></Table>
      </div>
      <div className='goods-detail-introduce'>
        <div className='introduce-title'>商品详情</div>
        <div
          className='introduce-content'
          dangerouslySetInnerHTML={{ __html: goodsInfoDetails?.goodsDetails || '' }}
        ></div>
      </div>
      <div className='goods-detail-operate'>
        <Button type='primary' onClick={backRoute}>
          返回
        </Button>
      </div>
    </div>
  );
};
export default GoodsDetails;
