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/address.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/border_text.dart';
import 'package:huixiang/view_widget/icon_text.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class ManageAddressPage extends StatefulWidget {
  final Map<String, dynamic> arguments;

  ManageAddressPage({this.arguments});

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

class _ManageAddressPage extends State<ManageAddressPage> {
  ApiService apiService;

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

    SharedPreferences.getInstance().then((value) => {
          apiService = ApiService(Dio(),
              context: context, token: value.getString('token')),
          queryMemberAddress(),
        });
  }

  List<Address> addressList;

  queryMemberAddress() async {
    BaseData<List<Address>> baseData = await apiService.queryMemberAddress();
    if (baseData != null && baseData.isSuccess) {
      checkIndex = 0;
      addressList = baseData.data;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        title: S.of(context).shouhuodizhi1,
        titleColor: Colors.black,
        titleSize: 18.sp,
        background: Color(0xFFF7F7F7),
        leadingColor: Colors.black,
      ),
      body: Column(
        children: [
          Expanded(
            child: (addressList == null || addressList.length == 0)
                ? NoDataView(
                    isShowBtn: false,
                    text: "目前暂无送货地址,请添加",
                    fontSize: 16.sp,
                    margin: EdgeInsets.only(top: 120.h),
                  )
                : ListView.builder(
                    itemCount: addressList == null ? 0 : addressList.length,
                    physics: BouncingScrollPhysics(),
                    itemBuilder: (context, position) {
                      return InkWell(
                        onTap: () {
                          if (widget.arguments["isSelector"]) {
                            Navigator.of(context).pop({
                              "id": "${addressList[position].id}",
                              "address": "${addressList[position].address}",
                            });
                          }
                        },
                        child:
                            buildAddressItem(addressList[position], position),
                      );
                    },
                  ),
            flex: 1,
          ),
          InkWell(
            onTap: () {
              addAddress();
            },
            child: Container(
              color: Color(0xFF32A060),
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.all(16),
              alignment: Alignment.center,
              child: Text(
                "新增地址",
                style: TextStyle(
                  fontWeight: MyFontWeight.semi_bold,
                  fontSize: 16.sp,
                  color: Colors.white,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  addAddress({Address address}) async {
    if (address != null) {
      await Navigator.of(context)
          .pushNamed('/router/address_edit_page', arguments: address.toJson());
    } else {
      await Navigator.of(context).pushNamed('/router/address_edit_page');
    }
    queryMemberAddress();
  }

  Widget buildAddressItem(Address address, position) {
    return Container(
      margin: EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 8),
      padding: EdgeInsets.only(left: 6, right: 16, top: 16, bottom: 8),
      decoration: BoxDecoration(
        boxShadow: [
          BoxShadow(
            color: Color(0x000000).withAlpha(25),
            offset: Offset(0, 1),
            blurRadius: 12.0,
          ),
        ],
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 10.w),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  address.username,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: MyFontWeight.semi_bold,
                    color: Colors.black,
                  ),
                ),
                SizedBox(
                  height: 16.h,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: IconText(
                        address.phone,
                        leftImage: "assets/image/icon_address_call.png",
                        iconSize: 16.sp,
                      ),
                    ),
                    InkWell(
                      child: Image.asset(
                        "assets/image/icon_address_edit.png",
                        width: 24,
                        height: 24,
                      ),
                      onTap: () {
                        addAddress(address: address);
                      },
                    ),
                  ],
                ),
                SizedBox(
                  height: 4.h,
                ),
                IconText(
                  "${address.address}",
                  isMax: true,
                  textAxisAlignment: CrossAxisAlignment.start,
                  textStyle: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: MyFontWeight.regular,
                    color: Color(0xFF353535),
                  ),
                  leftIcon: Icons.location_on,
                  iconColor: Color(0xFF32A060),
                  iconSize: 16,
                ),
                SizedBox(
                  height: 10.h,
                ),
                Container(
                  height: 1.h,
                  color: Color(0xFFF2F2F2),
                )
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // Checkbox(
              //   value: address.isDefault,
              //   onChanged: (value) {
              //     changeCheck(value, position);
              //   },
              //   checkColor: Color(0xFFFFFFFF),
              //   fillColor: MaterialStateProperty.all(
              //       address.isDefault ? Color(0xFF39B54A) : Color(0xFFA29E9E)),
              //   materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              //   shape: CircleBorder(),
              // ),
              Expanded(
                child: Text(
                  "",
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: MyFontWeight.regular,
                    color: address.isDefault
                        ? Color(0xFF39B54A)
                        : Color(0xFFA29E9E),
                  ),
                ),
              ),
              InkWell(
                child: Padding(
                  padding: EdgeInsets.only(
                    top: 5.h,
                  ),
                  child: Text(
                    "删除",
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: MyFontWeight.regular,
                      color: Colors.black,
                    ),
                  ),
                ),
                onTap: () {
                  showDeleteDialog(position);
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  ///删除地址弹窗
  showDeleteDialog(position) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Container(
            width: MediaQuery.of(context).size.width - 84,
            height: 110.h,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  "您确定要删除收货地址吗?",
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
                SizedBox(
                  height: 30.h,
                ),
                Row(
                  children: [
                    Expanded(
                      child: InkWell(
                        child: BorderText(
                          text: "取消",
                          textColor: Color(0xFF32A060),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                          borderColor: Color(0xFF32A060),
                          radius: 4,
                          padding: EdgeInsets.all(12),
                          borderWidth: 1,
                        ),
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                      ),
                      flex: 1,
                    ),
                    SizedBox(
                      width: 16.w,
                    ),
                    Expanded(
                      child: InkWell(
                        child: RoundButton(
                          text: "确定",
                          textColor: Colors.white,
                          radius: 4,
                          padding: EdgeInsets.all(12),
                          backgroup: Color(0xFF32A060),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                        ),
                        onTap: () {
                          deleteAddress(position);
                          Navigator.of(context).pop();
                        },
                      ),
                      flex: 1,
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }

  int checkIndex = 0;

  deleteAddress(position) async {
    BaseData baseData =
        await apiService.deleteAddress(addressList[position].toJson());
    if (baseData != null && baseData.isSuccess) {
      queryMemberAddress();
    }
  }

  changeCheck(value, position) async {
    if (value) {
      addressList[checkIndex].isDefault = false;
      checkIndex = position;
      addressList[position].isDefault = true;
      BaseData baseData =
          await apiService.updateAddress(addressList[position].toJson());
      if (baseData != null && baseData.isSuccess) {}
      setState(() {});
    }
  }
}