import React, { useEffect, useState } from 'react';
import { EnvironmentOutlined } from '@ant-design/icons';
import { InputNumber } from 'antd';
import Big from 'big.js';
import dayjs from 'dayjs';
import { useSelector } from 'react-redux';
import styled from 'styled-components';
import { InterDataType } from '@/api/interface';
import { AppMallGoodsDetails } from '@/api/interface/mall';
import ProductSwiperView from '@/components/product-swiper';
import { RootState } from '@/store';
import { AddressState } from '@/store/module/address';

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

const ProductHeadView: React.FC<{ detail: DetailType }> = ({ detail }) => {
  // address
  const address = useSelector(
    (state: RootState) => state.address,
  ) as AddressState;
  // 当前选中的规格
  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`;
  };
  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" key={j}>
            <div className="item-label">{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)}
                >
                  {n.specName}
                </div>
              ))}
            </div>
          </div>
        ))}
        <div className="content-item flex-start">
          <div className="item-label">数量</div>
          <div className="item-content">
            <InputNumber
              min={1}
              max={9999}
              precision={0}
              value={productNum}
              onChange={(e) => setProductNum(e || 1)}
            />
          </div>
        </div>
        <div className="content-action flex-start select-none">
          <div className="action-item">加入购物车</div>
          <div className="action-item">提交意向</div>
          <div className="action-item">确认购买</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: center;
  justify-content: flex-start;
  padding: 0 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: 1rem 0 1rem 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: 2rem;
        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;
      .item-label {
        width: 2rem;
        color: #999999;
        text-align: justify;
        text-align-last: justify;
        margin-right: 1rem;
      }
      .item-content {
        .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: 4rem;
          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;
          &:not(:last-child) {
            margin-right: 0.5rem;
          }
        }
        .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;
      }
    }
  }
`;
