import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/exchange_order.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/icon_text.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/my_tab.dart';
import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ExchangeHistoryPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ExchangeHistoryPage();
  }
}

class _ExchangeHistoryPage extends State<ExchangeHistoryPage>
    with SingleTickerProviderStateMixin {
  List<Widget> tabs;
  List<Widget> _pages;
  TabController tabcontroller;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (tabcontroller == null)
      tabcontroller = TabController(length: 3, vsync: this);
    tabs = [
      MyTab(
        text: S.of(context).quanbuduihuan,
      ),
      MyTab(
        text: S.of(context).weiwancheng,
      ),
      // MyTab(
      //   text: S.of(context).keshiyong,
      // ),
      MyTab(
        text: S.of(context).yiwancheng,
      )
    ];
    _pages = [
      ExchangeHistoryList(0),
      ExchangeHistoryList(1),
      ExchangeHistoryList(2),
      // ExchangeHistoryList(3)
    ];
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: MyAppBar(
          title: S.of(context).duihuanlishi,
          titleColor: Colors.black,
          titleSize: 18.sp,
          background: Color(0xFFFFFFFF),
          leadingColor: Colors.black,
          toolbarHeight: kToolbarHeight + MediaQuery.of(context).padding.top,
          bottom: PreferredSize(
            preferredSize: Size(double.infinity, 38.h),
            child: TabBar(
              controller: tabcontroller,
              indicatorWeight: 2,
              indicatorColor: Color(0xFF39B54A),
              indicatorSize: TabBarIndicatorSize.label,
              indicatorPadding: EdgeInsets.only(top: 3),
              unselectedLabelStyle: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.normal,
              ),
              labelStyle: TextStyle(
                  color: Colors.black,
                  fontSize: 16.sp,
                  fontWeight: MyFontWeight.semi_bold),
              labelColor: Colors.black,
              tabs: tabs,
            ),
          ),
        ),
        body: TabBarView(
          children: _pages,
          controller: tabcontroller,
        ),
      ),
    );
  }
}

class ExchangeHistoryList extends StatefulWidget {
  final int orderStatus;

  ExchangeHistoryList(this.orderStatus);

  @override
  State<StatefulWidget> createState() {
    return _ExchangeHistoryList();
  }
}

class _ExchangeHistoryList extends State<ExchangeHistoryList> {
  ApiService apiService;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) => {
          apiService = ApiService(Dio(),
              showLoading: true,
              context: context, token: value.getString('token')),
          queryHistory(),
        });
  }

  int pageNum = 1;
  List<ExchangeOrder> orders = [];

  queryHistory() async {
    var map = {
      "pageNum": pageNum,
      "pageSize": 10,
      // "state": widget.orderStatus
    };
    if (widget.orderStatus != 0) {
      map["state"] = widget.orderStatus;
    }
    BaseData<PageInfo<ExchangeOrder>> baseData =
        await apiService.creditOrderList(map).catchError((error) {
      _refreshController.loadFailed();
      _refreshController.refreshFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      if (pageNum == 1) {
        orders.clear();
      }
      orders.addAll(baseData.data.list);
      setState(() {
        _refreshController.loadComplete();
        _refreshController.refreshCompleted();
        if (baseData.data.pages == baseData.data.pageNum) {
          _refreshController.loadNoData();
        } else {
          pageNum += 1;
        }
      });
    } else {
      _refreshController.refreshFailed();
      _refreshController.loadFailed();
    }
  }

  _refresh() {
    pageNum = 1;
    queryHistory();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: MyHeader(),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus mode) {
          return MyFooter(mode);
        },
      ),
      controller: _refreshController,
      onRefresh: _refresh,
      onLoading: queryHistory,
      child: orders == null || orders.length == 0
          ? NoDataView(
              src: "assets/image/ding_dan.webp",
              isShowBtn: false,
              text: "暂无已完成的订单",
              fontSize: 16.sp,
              margin: EdgeInsets.only(top: 120.h),
            )
          : ListView.builder(
              itemCount: orders == null ? 0 : orders.length,
              itemBuilder: (context, position) {
                return buildOrder(orders[position]);
              },
            ),
    );
  }

  String orderStatus(state) {
    String orderStatus = "";
    switch (state) {
      case 1:
        orderStatus = S.of(context).weiwancheng;
        break;
      case 2:
        orderStatus = S.of(context).yiwancheng;
        break;
      case 9:
        orderStatus = S.of(context).yiquxiao;
        break;
    }
    return orderStatus;
  }

  Widget buildOrder(ExchangeOrder exchangeOrder) {
    return Container(
      margin: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 8.h),
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withAlpha(12),
              offset: Offset(0, 3),
              blurRadius: 14,
              spreadRadius: 0,
            )
          ]),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                S.of(context).chuangjianshijian(exchangeOrder.createTime),
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: MyFontWeight.semi_bold,
                  fontSize: 14.sp,
                ),
              ),
              Text(
                orderStatus(exchangeOrder.state),
                style: TextStyle(
                  color: Color(0xFFFE951E),
                  fontWeight: MyFontWeight.semi_bold,
                  fontSize: 14.sp,
                ),
              )
            ],
          ),
          SizedBox(
            height: 16.h,
          ),
          exchangeOrder.useTyped == 1 ?
          Container(
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      S.of(context).zitidizhi + " :",
                      style: TextStyle(
                        color: Color(0xFF353535),
                        fontWeight: MyFontWeight.regular,
                        fontSize: 12.sp,
                      ),
                    ),
                    SizedBox(
                      width: 8.w,
                    ),
                    Expanded(
                      child: Text(
                        exchangeOrder.address ?? "",
                        style: TextStyle(
                          color: Colors.black,
                          fontWeight: MyFontWeight.regular,
                          fontSize: 12.sp,
                        ),
                      ),
                    )
                  ],
                ),
                SizedBox(
                  height: 8.h,
                ),
                Row(
                  children: [
                    Text(
                      S.of(context).zitishijian + " :",
                      style: TextStyle(
                        color: Color(0xFF353535),
                        fontWeight: MyFontWeight.regular,
                        fontSize: 12.sp,
                      ),
                    ),
                    SizedBox(
                      width: 8.h,
                    ),
                    Expanded(
                      child: Text(
                        S.of(context).duihuanhouwugegongzuori,
                        style: TextStyle(
                          color: Colors.black,
                          fontWeight: MyFontWeight.regular,
                          fontSize: 12.sp,
                        ),
                      ),
                    )
                  ],
                ),
              ],
            ),
          ):
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                S.of(context).shouhuodi + " :",
                style: TextStyle(
                  color: Color(0xFF353535),
                  fontWeight: MyFontWeight.regular,
                  fontSize: 12.sp,
                ),
              ),
              SizedBox(
                width: 8.w,
              ),
              Expanded(
                child: Text(
                  exchangeOrder.recAddress ?? "",
                  style: TextStyle(
                    color: Colors.black,
                    fontWeight: MyFontWeight.regular,
                    fontSize: 12.sp,
                  ),
                ),
              )
            ],
          ),
          SizedBox(
            height: 16.h,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              MImage(
                (exchangeOrder != null &&
                        exchangeOrder.creditOrderDetailList != null)
                    ? exchangeOrder.creditOrderDetailList[0].goodsMainImg
                    : "",
                errorSrc: "assets/image/default_1.webp",
                fadeSrc: "assets/image/default_1.webp",
                width: 66,
                height: 66,
                fit: BoxFit.cover,
              ),
              SizedBox(
                width: 12.w,
              ),
              Expanded(
                child: SizedBox(
                  height: 66.h,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        exchangeOrder.creditOrderDetailList[0].name,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: MyFontWeight.semi_bold,
                            color: Color(0xFF353535)),
                      ),
                      SizedBox(
                        height: 5.h,
                      ),
                      Text(
                        exchangeOrder.useTyped == 3
                            ? S.of(context).feishiwuduihuanma
                            : exchangeOrder
                                .creditOrderDetailList[0].description,
                        maxLines: 2,
                        style: TextStyle(
                          fontSize: 10.sp,
                          fontWeight: MyFontWeight.regular,
                          color: Color(0xFF727272),
                        ),
                      ),
                    ],
                  ),
                ),
                flex: 1,
              ),
              Text(
                "x${(exchangeOrder.creditOrderDetailList[0].goodsNumber).toString()}",
                style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: MyFontWeight.regular,
                  color: Color(0xFF353535),
                ),
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              // Text(
              //   S.of(context).shangpinjifen(90),
              //   style: TextStyle(
              //     fontSize: 12,
              //     color: Color(0xFFA0A0A0),
              //   ),
              // ),
              // SizedBox(
              //   width: 4,
              // ),
              Text(
                exchangeOrder?.amount == null || exchangeOrder.amount == "0"
                    ? ""
                    : S.of(context).shifujifen((exchangeOrder.amount)) +
                   ( exchangeOrder?.creditOrderDetailList[0]?.money == null ||
                            exchangeOrder?.creditOrderDetailList[0]?.money ==
                                "0.00"
                        ? ""
                        : " + ${double.parse(exchangeOrder?.creditOrderDetailList[0]?.money.toString()) * exchangeOrder?.creditOrderDetailList[0].goodsNumber}元"),
                style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: MyFontWeight.semi_bold,
                  color: Colors.black,
                ),
              ),
            ],
          ),
          SizedBox(
            height: 12.h,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              IconText(
                "${S.of(context).dingdanbianhao}: ${exchangeOrder.orderCode}",
                leftImage: "assets/image/bianhao.webp",
                iconSize: 16,
                textStyle: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: MyFontWeight.regular,
                  color: Color(0xFF353535),
                ),
              ),
              exchangeOrder.useTyped == 1 ?
              GestureDetector(
                onTap: () {
                  // if (exchangeOrder.state == 1) {
                  //   receive2Card(exchangeOrder.id);
                  // } else {
                  //   Navigator.of(context)
                  //       .pushNamed('/router/write_off_page', arguments: {});
                  // }
                  Navigator.of(context).pushNamed(
                      '/router/exchange_write_offPage',
                      arguments: {
                        "exchangeOrder": exchangeOrder.toJson(),
                      });
                },
                child: buildBtnStatus(exchangeOrder.state),
              ):
              GestureDetector(
                onTap: () {
                  setState(() {
                    Navigator.of(context).pushNamed(
                        '/router/logistics_information_page',
                        arguments: {
                          "orderId": exchangeOrder.creditOrderDetailList[0].orderId,
                          "logisticsNum": "",
                          "logisticsName": "",
                          "productNum": exchangeOrder.creditOrderDetailList[0].goodsNumber,
                          "skuImg":exchangeOrder.creditOrderDetailList[0].goodsMainImg
                        });
                  });
                },
                child: buildBtnStatusTow(exchangeOrder.state),
              ),
            ],
          )
        ],
      ),
    );
  }

  receive2Card(id) async {
    BaseData baseData = await apiService.creditOrderReceive(id);
    if (baseData != null && baseData.isSuccess) {
      _refresh();
    }
  }

  Widget buildBtnStatus(state) {
    if (state == 1) {
      return RoundButton(
        padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
        text: S.of(context).chakanhexiaoma,
        textColor: Colors.white,
        fontSize: 12,
        backgroup: Color(0xFF32A060),
        radius: 2,
      );
    } else {
      return Container();
      // return BorderText(
      //   text: S.of(context).shanchudingdan,
      //   textColor: Color(0xFF32A060),
      //   borderWidth: 1,
      //   borderColor: Color(0xFF32A060),
      //   fontSize: 12,
      //   padding: EdgeInsets.fromLTRB(14, 4, 14, 4),
      // );
    }
  }

  Widget buildBtnStatusTow(state) {
    if (state == 1) {
      return RoundButton(
        padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
        text: S.of(context).chakanwuliu,
        textColor: Colors.white,
        fontSize: 12,
        backgroup: Color(0xFF32A060),
        radius: 2,
      );
    } else {
      return Container();
      // return BorderText(
      //   text: S.of(context).shanchudingdan,
      //   textColor: Color(0xFF32A060),
      //   borderWidth: 1,
      //   borderColor: Color(0xFF32A060),
      //   fontSize: 12,
      //   padding: EdgeInsets.fromLTRB(14, 4, 14, 4),
      // );
    }
  }
}