import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/logistics.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LogisticsInformationPage extends StatefulWidget {
  final arguments;

  LogisticsInformationPage({this.arguments});

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

class _LogisticsInformationPage extends State<LogisticsInformationPage> {
  ApiService apiService;
  RefreshController _refreshController;

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController();

    SharedPreferences.getInstance().then((value) {
      apiService =
          ApiService(Dio(), context: context, token: value.getString("token"));
      getShippingTrace(widget.arguments["shipperCode"] ?? "",
          widget.arguments["logisticsNum"] ?? "");
    });
  }

  List<TracesBean> logistics = [];
  String shipStatus = "";

  getShippingTrace(String shipperCode, String logisticCode) async {
    BaseData<Logistics> baseData = await apiService
        .shippingTrace(shipperCode, logisticCode)
        .catchError((error) {
      _refreshController.refreshFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      Logistics lgs = baseData.data;
      logistics.clear();
      logistics.addAll(lgs.traces.reversed);
      setState(() {
        shipStatus = logisticsStatus(lgs.state);
        if (logistics.length > 0) logistics[0].acceptStation += shipStatus;
        _refreshController.refreshCompleted();
      });
    } else {
      _refreshController.refreshFailed();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        background: Color(0xFFF7F7F7),
        title: S.of(context).wuliuxinxi,
        titleColor: Colors.black,
        leadingColor: Colors.black,
      ),
      body: Container(
        child: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: Column(
            children: [
              _orderInformation(),
              SizedBox(
                height: 16.h,
              ),
              Container(
                margin: EdgeInsets.symmetric(
                  vertical: 8.h,
                  horizontal: 16.w,
                ),
                padding: EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(
                    top: Radius.circular(8.w),
                    bottom: Radius.circular(4.w),
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withAlpha(12),
                      offset: Offset(0, 2),
                      blurRadius: 14,
                      spreadRadius: 0,
                    )
                  ],
                ),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(bottom: 32.h),
                        child: Text(
                          S.of(context).dingdangenzong,
                          style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.bold,
                              color: Color(0xff353535)),
                        ),
                      ),
                      SizedBox(
                        height: 500.h,
                        child: (logistics != null && logistics.length > 0)
                            ? ListView.builder(
                                itemCount:
                                    logistics != null ? logistics.length : 0,
                                itemBuilder: (context, position) {
                                  return orderTrackItem(logistics[position],
                                      position, logistics.length);
                                })
                            : NoDataView(
                                isShowBtn: false,
                                text: "暂无物流信息~",
                                fontSize: 16.sp,
                                margin: EdgeInsets.only(top: 120),
                              ),
                      ),
                    ]),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _orderInformation() {
    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w),
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha(12),
            offset: Offset(0, 2),
            blurRadius: 14,
            spreadRadius: 0,
          )
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Stack(
                alignment: Alignment.bottomCenter,
                children: [
                  if (widget.arguments["skuImg"] != null)
                    Image.network(
                      widget.arguments["skuImg"],
                      width: 95.w,
                      height: 95.h,
                      fit: BoxFit.cover,
                    )
                  else
                    Image.asset(
                      "assets/image/default_1.png",
                      width: 95.w,
                      height: 95.h,
                      fit: BoxFit.cover,
                    ),
                  Container(
                    padding: EdgeInsets.only(
                        left: 32.w, right: 32.w, top: 5.h, bottom: 5.h),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(0),
                        bottomLeft: Radius.circular(4),
                        topRight: Radius.circular(0),
                        bottomRight: Radius.circular(4),
                      ),
                      color: Color(0x53000000),
                    ),
                    child: Text.rich(
                      TextSpan(
                        children: [
                          TextSpan(
                            text: S.of(context).gong,
                            style: TextStyle(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400,
                              color: Colors.white,
                            ),
                          ),
                          TextSpan(
                            text:
                                widget.arguments["productNum"].toString() ?? "",
                            style: TextStyle(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400,
                              color: Colors.white,
                            ),
                          ),
                          TextSpan(
                            text: S.of(context).jian,
                            style: TextStyle(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(
                width: 12.w,
              ),
              Expanded(
                flex: 1,
                child: Container(
                  height: 95.h,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            S.of(context).wuliuzhuangtai,
                            style: TextStyle(
                                color: Color(0xff353535),
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w400),
                          ),
                          Text(
                            shipStatus,
                            style: TextStyle(
                                color: Color(0xFF32A060),
                                fontSize: 14.sp,
                                fontWeight: FontWeight.bold),
                          )
                        ],
                      ),
                      SizedBox(
                        height: 8.h,
                      ),
                      Row(
                        children: [
                          Text(
                            S.of(context).wuliugongsi,
                            style: TextStyle(
                              color: Color(0xff353535),
                              fontSize: 14.sp,
                            ),
                          ),
                          Text(
                            widget.arguments["logisticsName"] ?? "",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w400),
                          )
                        ],
                      ),
                      SizedBox(
                        height: 8.h,
                      ),
                      Row(
                        children: [
                          Text(
                            S.of(context).wuliudanhao,
                            style: TextStyle(
                                color: Color(0xff353535),
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w400),
                          ),
                          Text(
                            widget.arguments["logisticsNum"] ?? "",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w400),
                          )
                        ],
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    );
  }

  Widget orderTrackItem(TracesBean logistics, var position, var size) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          // mainAxisAlignment: MainAxisAlignment.start,
          // crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              logistics.acceptTime.split(" ")[0],
              style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: MyFontWeight.medium,
                  color: Color(0xff353535)),
            ),
            SizedBox(
              height: 5.h,
            ),
            Text(
              logistics.acceptTime.split(" ")[1],
              style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: MyFontWeight.medium,
                  color: Color(0xff868686)),
            ),
          ],
        ),
        SizedBox(
          width: 28.w,
        ),
        Column(
          children: [
            Image.asset(
              tripStatus(logistics.acceptStation),
              width: 24.w,
              height: 24.h,
            ),
            if (position != size - 1)
              Container(
                width: 1.w,
                height: 75.h,
                decoration: new BoxDecoration(
                  color: Color(0xffE1E1E1),
                ),
              )
          ],
        ),
        SizedBox(
          width: 28.w,
        ),
        Expanded(
          flex: 1,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (logisticsTripStatus(logistics.acceptStation) != "")
                Text(
                  logisticsTripStatus(logistics.acceptStation),
                  style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: MyFontWeight.medium,
                      color: Colors.black),
                ),
              SizedBox(
                height: 10.h,
              ),
              Text(
                logistics.acceptStation,
                style: TextStyle(
                    fontSize: 12.sp,
                    fontWeight: MyFontWeight.regular,
                    color: Color(0xff353535)),
              ),
            ],
          ),
        ),
      ],
    );
  }

  String logisticsStatus(state) {
    String logisticsStatus = "";
    switch (state) {
      case 2:
        logisticsStatus = "运输中";
        break;
      case 3:
        logisticsStatus = "已签收";
        break;
      case 4:
        logisticsStatus = "问题件";
        break;
    }
    return logisticsStatus;
  }

  String tripStatus(String type) {
    String tripStatus = "assets/image/icon_sign.png";
    if (type.contains("已签收")) {
      tripStatus = "assets/image/icon_sign.png";
    } else if (type.contains("派送中")) {
      tripStatus = "assets/image/icon_delivery.png";
    } else if (type.contains("运输中") || type.contains("发往")) {
      tripStatus = "assets/image/icon_transport.png";
    } else if (type.contains("已发货") || type.contains("分配")) {
      tripStatus = "assets/image/icon_deliver_goods.png";
    } else if (type.contains("已下单")) {
      tripStatus = "assets/image/icon_place_ order.png";
    }
    return tripStatus;
  }

  String logisticsTripStatus(String state) {
    String logisticsTripStatus = "";
    if (state.contains("已签收")) {
      logisticsTripStatus = "已签收";
    } else if (state.contains("派送中")) {
      logisticsTripStatus = "派送中";
    } else if (state.contains("运输中") || state.contains("发往")) {
      logisticsTripStatus = "运输中";
    } else if (state.contains("已发货") || state.contains("分配")) {
      logisticsTripStatus = "已发货";
    } else if (state.contains("已下单")) {
      logisticsTripStatus = "已下单";
    }
    return logisticsTripStatus;
  }
}