import React, { useEffect, useState } from 'react';
import { EnvironmentOutlined } from '@ant-design/icons';
import { message } from 'antd';
import Big from 'big.js';
import dayjs from 'dayjs';
import { useRouter } from 'next/router';
import { useDispatch, useSelector } from 'react-redux';
import styled from 'styled-components';
import { InterDataType } from '@/api/interface';
import { AppMallGoodsDetails } from '@/api/interface/mall';
import NumberBox from '@/components/numberBox';
import ProductSwiperView from '@/components/product-swiper';
import { AddressState } from '@/store/module/address';
import { setGlobalData } from '@/store/module/globalData';
import { UserInfoState } from '@/store/module/userInfo';

// 商品详情类型
type DetailType = InterDataType<AppMallGoodsDetails>;

const ProductHeadView: React.FC<{ detail: DetailType }> = ({ detail }) => {
  // 当前的路由数据
  const router = useRouter();
  // store
  const dispatch = useDispatch();
  // address
  const address = useSelector((state: any) => state.address) as AddressState;
  // userInfo
  const userInfo = useSelector((state: any) => state.userInfo) as UserInfoState;
  // 当前选中的规格
  const [selectSpecList, setSelectSpecList] = useState<
    { row: number; index: number }[]
  >([]);
  // 商品的购买数量
  const [productNum, setProductNum] = useState<number>(1);
  // 获取后天的日期
  const getAfterTomorrow = () => {
    return dayjs().add(2, 'day').format('MM月DD日');
  };
  // 判断当前选项是否选中
  const isSelect = (row: number, index: number) => {
    return !!selectSpecList.find((i) => i.row === row && i.index === index);
  };
  // 选中项目
  const handleSelect = (row: number, index: number) => {
    let arr = selectSpecList;
    // 选中列表中是否有当前选项
    if (arr.find((i) => i.row === row && i.index === index)) {
      // 如果有就删除
      setSelectSpecList(arr.filter((i) => i.row !== row || i.index !== index));
      return;
    }
    // 如果是单选，就删除当前组别的所有选项
    arr = arr.filter((i) => i.row !== row);
    // 将当前选项添加到选中列表中
    arr = [...arr, { row, index }].sort((a, b) => a.row - b.row);
    setSelectSpecList(arr);
  };
  // 获取当前最便宜的规格，然后选中
  const getLowerSpec = () => {
    const item = detail?.priceStock
      ?.sort((a, b) => a.salePrice - b.salePrice)
      ?.at(0)?.productSpec;
    const arr = Object.entries(JSON.parse(item || '{}'))?.map((i) => {
      const index = detail?.specAttrList?.findIndex((k) => k.specName === i[0]);
      return {
        row: index,
        index: detail?.specAttrList?.[index]?.specValuesList?.findIndex(
          (k) => k.specName === i[1],
        ),
      };
    });
    setSelectSpecList(arr || []);
  };
  // 获取规格中最低的价格
  const getLowerPrice = () => {
    return detail?.priceStock?.sort((a, b) => a.salePrice - b.salePrice)?.at(0)
      ?.salePrice;
  };
  // 获取当前规格的价格
  const getSpecPrice = () => {
    let price = 0;
    if (selectSpecList?.length !== detail?.specAttrList?.length) {
      price = getLowerPrice() || 0;
    } else {
      const item = selectSpecList?.map((i) => {
        const row = detail?.specAttrList?.[i.row];
        const index = row?.specValuesList?.[i.index];
        return [row?.specName, index?.specName];
      });
      price =
        detail?.priceStock?.find(
          (i) => i.productSpec === JSON.stringify(Object.fromEntries(item)),
        )?.salePrice || 0;
    }
    const money = Big(price).mul(Big(productNum)).toNumber().toLocaleString();
    return money.endsWith('.00') ? money : `${money}.00`;
  };
  // 获取选中规格列表的补充数据
  const getSelectPriceStock = () => {
    const arr =
      selectSpecList.map((i) => [
        detail?.specAttrList?.[i.row]?.specName,
        detail?.specAttrList?.[i.row]?.specValuesList?.[i.index]?.specName,
      ]) || [];
    return Object.fromEntries(arr);
  };
  // 获取规格的选项
  const getSelectPriceStockItem = () => {
    const item = getSelectPriceStock();
    return detail?.priceStock?.find(
      (i) => i.productSpec === JSON.stringify(item),
    );
  };
  // 提交事件
  const handleSubmit = async (type: number) => {
    // 判断是否选择了规格
    if (selectSpecList.length === 0) {
      message.warning('请选择规格');
      return;
    }
    // 去重掉同分组的之后，再判断必选项是否已选
    if (detail?.specAttrList?.length !== selectSpecList.length) {
      const arr =
        detail?.specAttrList
          ?.filter((i, j) => !selectSpecList.map((n) => n.row).includes(j))
          .map((i) => i.specName) || [];
      message.warning(`请选择必选项 ${arr.join(' ')}`);
      return;
    }
    // 判断是否登录
    if (!userInfo?.id) {
      dispatch(
        setGlobalData({
          loginModalVisible: true,
        }),
      );
      return;
    }
    // 当前的规格数据
    const specItem = getSelectPriceStockItem();
    // 立即购买
    if (type !== 3) {
      await router.push(
        `/cart/submit/${detail?.id}?num=${productNum}&specId=${specItem?.id}&type=${type}`,
      );
    }
  };
  // 组件挂载
  useEffect(() => {
    if (!detail) return;
    getLowerSpec();
    // console.log('detail --->', detail);
  }, [detail]);
  return (
    <ProductHeadWrap>
      <div className="product-swiper">
        <ProductSwiperView list={detail?.resourcesList} />
      </div>
      <div className="product-content">
        <div className="content-title">{detail?.tradeName}</div>
        <div className="content-desc">{detail?.description}</div>
        <div className="content-price flex-start">
          <div className="price-label">价格</div>
          <div className="price-money">
            {detail?.priceShow ? (
              <>
                <span className="label">￥</span>
                <span className="num">{getSpecPrice()}</span>
              </>
            ) : (
              <span className="label">咨询报价</span>
            )}
          </div>
        </div>
        <div className="content-item flex-start align-start">
          <div className="item-label">送至</div>
          <div className="item-content">
            <div className="content-address flex-start">
              <EnvironmentOutlined
                style={{ color: '#ff6700', fontSize: '12px' }}
              />
              <span className="text">{address?.province}</span>
              <span className="text">{address?.city}</span>
            </div>
            <div className="content-address">
              现货，今天22:00前下单，最快预计后天（{getAfterTomorrow()}）送达
            </div>
          </div>
        </div>
        <div className="content-item flex-start">
          <div className="item-label">规格</div>
          <div className="item-content">
            共 {detail?.priceStock?.length || 0} 种可选
          </div>
        </div>
        {detail?.specAttrList?.map((i, j) => (
          <div className="content-item flex-start align-start" key={j}>
            <div className="item-label two-line-ellipsis" title={i.specName}>
              {i.specName}
            </div>
            <div className="item-content flex-start ">
              {i.specValuesList?.map((n, m) => (
                <div
                  className={`content-spec cursor-pointer select-none ${
                    isSelect(j, m) && 'spec-active'
                  }`}
                  key={m}
                  onClick={() => handleSelect(j, m)}
                  title={n.specName}
                >
                  {n.specName}
                </div>
              ))}
            </div>
          </div>
        ))}
        <div className="content-item flex-start">
          <div className="item-label">数量</div>
          <div className="item-content">
            <NumberBox
              min={1}
              max={9999}
              precision={0}
              value={productNum}
              onChange={(e) => setProductNum(Number(e))}
            />
          </div>
        </div>
        <div className="content-action flex-start select-none">
          <div className="action-item" onClick={() => handleSubmit(3)}>
            加入购物车
          </div>
          <div className="action-item" onClick={() => handleSubmit(2)}>
            提交意向
          </div>
          <div className="action-item" onClick={() => handleSubmit(1)}>
            确认购买
          </div>
        </div>
      </div>
    </ProductHeadWrap>
  );
};

export default ProductHeadView;

// 样式
const ProductHeadWrap = styled.div`
  position: relative;
  width: calc((100% - 0.83rem) / 10 * 7.5);
  min-height: 28rem;
  background: #ffffff;
  border: 0.04rem solid #e3e3e3;
  box-sizing: border-box;
  margin-right: 0.83rem;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 2rem 1rem 2rem 1rem;
  .product-swiper {
    position: relative;
    width: 22rem;
    height: 26rem;
    box-sizing: border-box;
  }
  .product-content {
    position: relative;
    width: calc(100% - 22rem);
    height: 100%;
    box-sizing: border-box;
    padding: 0 0 0 1rem;
    //background: lightblue;
    .content-title {
      width: 100%;
      font-size: 24px;
      font-weight: 500;
      color: #212121;
      margin-bottom: 0.71rem;
      // 双行省略
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
    }
    .content-desc {
      font-weight: 400;
      color: #666666;
      margin-bottom: 0.71rem;
    }
    .content-price {
      position: relative;
      width: 100%;
      background: #f3f3f3;
      box-sizing: border-box;
      padding: 0.8rem;
      margin-bottom: 1rem;
      align-items: baseline;
      .price-label {
        width: 2.5rem;
        color: #999999;
        text-align: justify;
        text-align-last: justify;
        margin-right: 1rem;
        transform: translateY(-0.1rem);
      }
      .price-money {
        font-size: 24px;
        //line-height: 1;
        color: #ff6700;
        .label {
          font-size: 18px;
        }
      }
    }
    .content-item {
      margin-bottom: 1rem;
      padding: 0 0.8rem;
      //flex-wrap: nowrap;
      .item-label {
        width: 2.5rem;
        color: #999999;
        text-align: justify;
        text-align-last: justify;
        margin-right: 1rem;
      }
      .item-content {
        width: calc(100% - 3.5rem);
        .content-address {
          font-size: 12px;
          &:first-child {
            margin-bottom: 0.3rem;
            .text {
              color: #8e8e8e;
            }
          }
          .text {
            margin-left: 0.3rem;
            font-weight: 400;
          }
        }
        .content-spec {
          //min-width: max-content;
          height: 2rem;
          background: #f2f2f2;
          border-radius: 0.08rem;
          text-align: center;
          line-height: 2rem;
          font-weight: 400;
          box-sizing: border-box;
          padding: 0 1rem;
          border: 0.04rem solid #f2f2f2;
          margin: 0 0.5rem 0.5rem 0;
          &:last-child {
            margin-right: 0;
          }
        }
        .spec-active {
          background: #ffede8;
          border: 0.04rem solid #ff552d;
          color: #ff552d;
        }
      }
    }
    .content-action {
      //position: absolute;
      //left: 1rem;
      //bottom: 0;
      position: relative;
      width: 100%;
      margin-top: 2rem;
      .action-item {
        width: 8.63rem;
        height: 2.33rem;
        background: #fff0e5;
        border: 0.04rem solid #ff552d;
        text-align: center;
        line-height: 2.33rem;
        font-size: 13px;
        font-weight: 400;
        color: #ff552d;
        cursor: pointer;
        &:hover,
        &:active {
          filter: brightness(0.95);
        }
      }
      .action-item:not(:last-child) {
        margin-right: 0.8rem;
      }
      .action-item:last-child {
        background: #ff552d;
        color: #fff;
      }
    }
  }
`;
