import 'package:electronic_assistant/base/base_page.dart';
import 'package:electronic_assistant/data/bean/payment_way.dart';
import 'package:electronic_assistant/resource/assets.gen.dart';
import 'package:electronic_assistant/resource/colors.gen.dart';
import 'package:electronic_assistant/router/app_pages.dart';
import 'package:electronic_assistant/utils/expand.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../data/bean/store_item.dart';
import '../../data/consts/Constants.dart';
import '../../widget/shimmer_effect.dart';
import 'controller.dart';

enum StoreFromType { home, mine, analyse }

class StorePage extends BasePage<StoreController> {
  const StorePage({super.key});

  static start({StoreFromType? fromType}) {
    Get.toNamed(RoutePath.store, arguments: {'fromType': fromType});
  }

  @override
  Color backgroundColor() {
    return "#071935".color;
  }

  @override
  Color navigationBarColor() {
    return "#283B58".color;
  }

  @override
  bool statusBarDarkFont() {
    return false;
  }

  @override
  bool immersive() {
    return true;
  }

  //47.67

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        SingleChildScrollView(
          child: _buildStoreContent(),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: _buildBottomButton(),
        ),
        Positioned(
          left: 0,
          right: 0,
          child: AppBar(
            backgroundColor: Colors.transparent,
            scrolledUnderElevation: 0,
            leading: IconButton(
              color: Colors.white,
              icon: const Icon(Icons.arrow_back_ios_new_rounded),
              onPressed: () {
                Get.back();
              },
            ),
            actions: [_buildElectricBalance()],
          ),
        ),
      ],
    );
  }

  _buildElectricBalance() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.w),
      margin: EdgeInsets.only(right: 12.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(100.w),
          border: Border.all(
            color: "#7688B1".toColor(),
            width: 1.w,
          )),
      child: Row(
        children: [
          Assets.images.iconStoreLogo.image(width: 20.w, height: 20.w),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 3.w),
            child: Text("电量",
                style: TextStyle(color: Colors.white, fontSize: 12.w)),
          ),
          Obx(() {
            return Text('${controller.userInfo?.memberInfo?.electric ?? '0'}',
                style: TextStyle(color: Colors.white, fontSize: 12.w));
          }),
        ],
      ),
    );
  }

  _buildStoreContent() {
    return Stack(
      children: [
        _buildTopBanner(),
        Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 315.w),
              height: 154.w,
              child: Obx(() => ListView.builder(
                    itemBuilder: _buildStoreItem,
                    itemCount: controller.storeItems.length,
                    scrollDirection: Axis.horizontal,
                  )),
            ),
            Container(
              margin: EdgeInsets.only(left: 12.w, right: 12.w, top: 18.w),
              alignment: Alignment.centerLeft,
              child: Obx(() => Text(
                  " · ${controller.currentSelectedStoreItem.value?.itemDesc}",
                  style: TextStyle(
                      fontSize: 10.sp,
                      color: "#AFAFAF".color,
                      fontWeight: FontWeight.bold))),
            ),
            _buildPaymentWays(),
            _buildService(),
            _buildRule(),
            SizedBox(height: 80.w)
          ],
        ),
      ],
    );
  }

  _buildTopBanner() {
    return Stack(alignment: AlignmentDirectional.bottomStart, children: [
      Assets.images.bgStoreTop.image(),
      Container(
          margin: EdgeInsets.only(left: 12.w, bottom: 73.33.w),
          child: Assets.images.iconStoreDescripe.image(width: 268.w))
    ]);
  }

  Widget _buildStoreItem(BuildContext context, int index) {
    StoreItem storeItem = controller.storeItems[index];
    return GestureDetector(
      onTap: () => controller.onStoreItemClick(storeItem),
      child: Container(
        margin: EdgeInsets.only(
            left: index == 0 ? 12.w : 10.w,
            right: index == controller.storeItems.length - 1 ? 12.w : 0),
        child: Stack(
          children: [
            Obx(() =>
                controller.currentSelectedStoreItem.value?.id == storeItem.id
                    ? _buildSelectedItemContent(storeItem)
                    : _buildUnselectedItemContent(storeItem)),
            Visibility(
              visible: storeItem.popular,
              child: Container(
                padding: EdgeInsets.only(
                    left: 8.w, right: 8.w, top: 2.w, bottom: 10.w),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: Assets.images.iconStoreGoodTag.provider(),
                    fit: BoxFit.fill,
                  ),
                ),
                child: Text("最多人购买",
                    style: TextStyle(
                        color: "#703D27".color,
                        fontSize: 12.sp,
                        fontWeight: FontWeight.bold)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSelectedItemContent(StoreItem storeItem) {
    return Container(
      width: 132.w,
      margin: EdgeInsets.only(top: 9.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.w),
        gradient: LinearGradient(
          colors: ['#9075FF'.color, '#4366FF'.color],
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          stops: const [0.0, 1.0],
        ),
      ),
      child: Container(
        margin: EdgeInsets.all(2.w),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: ['#DADBFF'.color, '#FFF3F6'.color],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
            stops: const [0.0, 1.0],
          ),
          borderRadius: BorderRadius.circular(12.w),
        ),
        child: _buildItemContent(storeItem, true),
      ),
    );
  }

  Widget _buildUnselectedItemContent(StoreItem storeItem) {
    return Container(
      width: 132.w,
      margin: EdgeInsets.only(top: 9.w),
      padding: EdgeInsets.all(2.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.w), color: "#40567D".color),
      child: _buildItemContent(storeItem, false),
    );
  }

  Widget _buildItemContent(StoreItem storeItem, bool isSelect) {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(top: 14.w),
          child: Text(storeItem.name,
              style: TextStyle(
                  color: isSelect ? "#6177F2".color : Colors.white,
                  fontSize: 13.sp,
                  fontWeight: FontWeight.bold)),
        ),
        Container(
          margin: EdgeInsets.only(top: 10.w),
          child: RichText(
              text: TextSpan(
            children: [
              TextSpan(
                text: "¥",
                style: TextStyle(
                  color: isSelect ? "#6177F2".color : Colors.white,
                  fontSize: 16.sp,
                ),
              ),
              TextSpan(
                text: storeItem.amountText,
                style: TextStyle(
                  color: isSelect ? "#6177F2".color : Colors.white,
                  fontSize: 39.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          )),
        ),
        Text("¥${storeItem.originalAmountText}",
            style: TextStyle(
                color: "#AFAFAF".color,
                fontSize: 14.sp,
                decoration: TextDecoration.lineThrough,
                decorationColor: "#AFAFAF".color)),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.w),
          decoration: isSelect
              ? BoxDecoration(
                  gradient: LinearGradient(
                    colors: ['#9075FF'.color, '#4366FF'.color],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    stops: const [0.0, 1.0],
                  ),
                  borderRadius: BorderRadius.circular(12.w),
                )
              : BoxDecoration(
                  color: "#7688B1".toColor(),
                  borderRadius: BorderRadius.circular(12.w),
                ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: 16.w,
                height: 16.w,
                child: Assets.images.iconStoreGoodFlash.image(),
              ),
              Text(
                "${storeItem.authValue}电量",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 13.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildPaymentWays() {
    return Container(
      margin: EdgeInsets.only(top: 10.w),
      child: ExpansionTile(
        initiallyExpanded: true,
        onExpansionChanged: (value) {
          controller.isPaymentWayExpanded.value = value;
        },
        title: Padding(
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          child: Row(
            children: [
              Text("支付方式",
                  style: TextStyle(color: Colors.white, fontSize: 14.sp)),
              const Spacer(),
              Obx(() =>
                  controller.currentSelectedPaymentWay.value?._icon ??
                  Container()),
              Container(
                margin: EdgeInsets.only(left: 6.w, right: 4.w),
                child: Obx(() => Text(
                    controller.currentSelectedPaymentWay.value?.title ?? "",
                    style: TextStyle(color: Colors.white, fontSize: 14.sp))),
              ),
              Obx(() => controller.isPaymentWayExpanded.value
                  ? Assets.images.iconArrowUpWhite
                      .image(width: 16.w, height: 16.w)
                  : Assets.images.iconArrowDownWhite
                      .image(width: 16.w, height: 16.w)),
            ],
          ),
        ),
        showTrailingIcon: false,
        shape: const RoundedRectangleBorder(
          side: BorderSide(color: Colors.transparent),
        ),
        collapsedShape: const RoundedRectangleBorder(
          side: BorderSide(color: Colors.transparent),
        ),
        minTileHeight: 15.w,
        tilePadding: EdgeInsets.zero,
        children: [
          Obx(() => ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                itemBuilder: _buildPaymentWayItem,
                itemCount: controller.paymentWays.length,
                scrollDirection: Axis.vertical,
              )),
        ],
      ),
    );
  }

  Widget _buildPaymentWayItem(BuildContext context, int index) {
    PaymentWay paymentWay = controller.paymentWays[index];
    return GestureDetector(
      onTap: () => controller.onPaymentWayItemClick(paymentWay),
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 6.w),
        child: Row(
          children: [
            paymentWay._icon,
            Expanded(
              child: Container(
                margin: EdgeInsets.only(left: 8.w),
                child: Text(controller.paymentWays[index].title,
                    style: TextStyle(color: Colors.white, fontSize: 14.sp)),
              ),
            ),
            Obx(() => SizedBox(
                width: 20.w,
                height: 20.w,
                child: controller.currentSelectedPaymentWay.value?.id ==
                        paymentWay.id
                    ? Assets.images.iconSelectTrue.image()
                    : Assets.images.iconSelectFalse.image())),
          ],
        ),
      ),
    );
  }

  Widget _buildService() {
    return Container(
      margin: EdgeInsets.only(left: 12.w, right: 12.w, top: 30.w),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                width: 4.w,
                height: 16.h,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(2),
                  gradient: LinearGradient(
                    colors: [
                      '#357AFF'.toColor(),
                      '#E389FF'.toColor(),
                      '#ffffff'.toColor()
                    ],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    stops: const [0.0, 0.5, 1.0],
                  ),
                ),
              ),
              SizedBox(
                width: 6.w,
              ),
              Text(
                "多种专属服务·高效辅助办公",
                style: TextStyle(
                  fontSize: 15.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: 16.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildServiceItem(
                  Assets.images.iconStoreServiceSum.image(),
                  "智能谈话总结",
                ),
                _buildServiceItem(
                  Assets.images.iconStoreServiceRemain.image(),
                  "待办任务处理",
                ),
                _buildServiceItem(
                  Assets.images.iconStoreServiceAdvice.image(),
                  "专业工作建议",
                ),
                _buildServiceItem(
                  Assets.images.iconStoreServiceDeal.image(),
                  "处理交代事宜",
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildServiceItem(Image icon, String title) {
    return Column(
      children: [
        SizedBox(
          width: 32.w,
          child: icon,
        ),
        SizedBox(
          height: 2.h,
        ),
        Text(
          title,
          style: TextStyle(
            color: ColorName.white.withOpacity(0.8),
            fontSize: 11.sp,
          ),
        ),
      ],
    );
  }

  Container _buildRule() {
    return Container(
      margin: EdgeInsets.only(top: 26.w, left: 12.w, right: 12.w),
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      decoration: BoxDecoration(
        color: "#40567D".toColor().withOpacity(0.2),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "扣电规则",
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Colors.white.withOpacity(0.6),
            ),
          ),
          SizedBox(
            height: 6.h,
          ),
          Text(
            "1、小听每听5分钟扣1电量，不满5分钟按5分钟算。",
            style: TextStyle(
              fontSize: 12,
              color: Colors.white.withOpacity(0.6),
            ),
          ),
          Text(
            "2、大文件、超大文件生成新的总结，每次扣1电量。",
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Colors.white.withOpacity(0.6),
            ),
          ),
          Text(
            "3、用大文件和小听对话，每次对话扣1电量。",
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Colors.white.withOpacity(0.6),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomButton() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
      decoration: BoxDecoration(
        color: "#283B58".color,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(12.w),
          topRight: Radius.circular(12.w),
        ),
      ),
      child: GestureDetector(
        onTap: () => controller.onBuyClick(),
        child: ShimmerEffect(
          child: Container(
            height: 48.w,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: ['#9075FF'.color, '#4366FF'.color],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                stops: const [0.0, 1.0],
              ),
              borderRadius: BorderRadius.circular(8.w),
            ),
            child: _buildBuyButton(),
          ),
        ),
      ),
    );
  }

  Widget _buildBuyButton() {
    return Obx(() => Text(
          "立即购买  ￥${controller.currentSelectedStoreItem.value?.amountText ?? ''}",
          style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16.sp,
              color: Colors.white),
        ));
  }
}

extension on PaymentWay {
  get _icon {
    switch (payMethod) {
      case PayMethod.alipay:
        return Assets.images.iconStoreAlipay.image(width: 20.w, height: 20.w);
      case PayMethod.wechat:
        return Assets.images.iconStoreWechatPay
            .image(width: 20.w, height: 20.w);
      default:
        return Container();
    }
  }
}
