
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'package:bot_toast/bot_toast.dart';

import 'package:twong/api/index.dart';
import 'package:twong/utils/index.dart';
import 'package:twong/config/style.dart';
import 'package:twong/models/address.dart';
import 'package:twong/widgets/app_bar.dart';
import 'package:twong/providers/address.dart';
import 'package:twong/widgets/address_selecter.dart';
import 'package:twong/widgets/circle_check_box.dart';

class EditAddressPage extends StatefulWidget {
  final Address data;

  EditAddressPage(this.data);

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

class _EditAddressPageState extends State<EditAddressPage> {
  bool _isAdd = true;
  Address _address = Address();
  TextEditingController _nameController = TextEditingController();
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _detailController = TextEditingController();

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

    if(widget.data != null) {
      _isAdd = false;
      _address = widget.data;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: DColors.back,
      appBar: DAppBar(_isAdd ? "添加收货地址" : "编辑收货地址",
        actions: _isAdd ? null : [
          InkWell(
            onTap: _delClick,
            highlightColor: Colors.transparent,
            child: Container(
              margin: EdgeInsets.only(right: 12.px),
              alignment: Alignment.center,
              child: Text("删除地址"),
            ),
          )
        ]),
      body: SafeArea(
        child: Container(
          margin: EdgeInsets.all(12.px),
          child: ListView(
            physics: ClampingScrollPhysics(),
            children: [
              _buildName(),
              Divider(),
              _buildPhone(),
              Divider(),
              _buildAddress(),
              Divider(),
              _buildDetail(),
              Divider(),
              _buildDefault(),
              Divider(),
              FlatButton(
                color: DColors.Main,
                shape: StadiumBorder(),
                child: Text("立即保存", style: TextStyle(color: Colors.white)),
                onPressed: _saveClick,
              )
            ],
          ),
        ),
      ),
    );
  }

  _delClick() {
    Utils.loading();
    Network.inst.delAddress(_address.id).then((res) {
      Utils.closeLoading();
      Provider.of<AddressModel>(context, listen: false)
          .delete(_address.id);
      BotToast.showText(text: "删除成功");
      Navigator.pop(context);
    }).catchError((err) {
      Utils.closeLoading();
      Log.e(err);
    });
  }

  _saveClick () {
    _address.id = widget.data?.id;
    // _address.is_default = _default ? 1 : 0;
    _address.real_name = _nameController.text;
    _address.phone = _phoneController.text;
    _address.detail = _detailController.text;
    // var areas = _area.split(" ");
    // _address.province = areas[0];
    // _address.city = areas[1];
    // _address.district = areas[2];

    Utils.loading();
    Network.inst.editAddress(_address).then((value) {
      Utils.closeLoading();
      if(value["id"] != null) {
        _address.id = num.parse(value["id"].toString());
      }
      Provider.of<AddressModel>(context, listen: false)
          .update(_address.id, _address);
      BotToast.showText(text: "保存成功");
      Navigator.pop(context);
    }).catchError((err, stack) {
      Log.e(err.toString() + stack.toString());
    });
  }

  Widget _buildName() {
    if(_address.real_name != null) {
      _nameController.text = _address.real_name;
    }

    return Container(
        height: 38.px,
        child: Row(
          children: [
            Container(
              width: 64.px,
              child: Text("收货人"),
            ),
            Expanded(child: TextField(
              controller: _nameController,
              style: TextStyle(fontSize: 13.px),
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "收货人"
              ),
            ))
          ],
        ));
  }

  Widget _buildPhone() {
    if(_address.phone != null) {
      _phoneController.text = _address.phone;
    }

    return Container(
        height: 38.px,
        child: Row(
          children: [
            Container(
              width: 64.px,
              child: Text("联系电话"),
            ),
            Expanded(child: TextField(
              controller: _phoneController,
              style: TextStyle(fontSize: 13.px),
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "联系电话"
              ),
            ))
          ],
        ));
  }

  Widget _buildAddress() {
    var _area = _address.province == null ? "所在区域" :
      "${_address.province} ${_address.city} ${_address.district}";

    return Container(
        height: 38.px,
        child: Row(
          children: [
            Container(
              width: 64.px,
              child: Text("所在区域"),
            ),
            Expanded(child: InkWell(
              highlightColor: Colors.transparent,
              onTap: _choiceAddressDialog,
              child: Text(_area, style: TextStyle(color: _address.province ==
                  null ? Colors.grey : Colors.black)),
            )),
            Icon(Icons.chevron_right, color: Colors.grey)
          ],
        ));
  }

  void _choiceAddressDialog() {
    FocusScope.of(context).requestFocus(new FocusNode());
    showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.only(
            topLeft: Radius.circular(45.px), topRight: Radius.circular(12.px)
        )),
        builder: (BuildContext context) {
          return AddressSelecter(
              onSelected: (province, city, county, code) {
                _address.province = province;
                _address.city = city;
                _address.district = county;
                _address.city_id = code;
                setState(() {});
              },
              title: '选择地址',
              selectedColor: Colors.red,
              unselectedColor: Colors.black);
        }
    );
  }

  Widget _buildDetail() {
    if(_address.detail != null) {
      _detailController.text = _address.detail;
    }

    return Container(
        height: 64.px,
        child: Row(
          children: [
            Container(
              width: 64.px,
              alignment: Alignment.topLeft,
              margin: EdgeInsets.only(top: 6.px),
              child: Text("详细地址"),
            ),
            Expanded(child: TextField(
              maxLines: 2,
              style: TextStyle(fontSize: 13.px),
              controller: _detailController,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "详细地址：如道路、门牌号、小区、楼栋号、单元室等",
              ),
            ))
          ],
        ));
  }

  Widget _buildDefault() {
    return Container(
        height: 38.px,
        child: Row(
          children: [
            Expanded(child: Text("设为默认收货地址")),
            Container(
              margin: EdgeInsets.only(right: 6.px),
              child: CircleCheckBox((value) {
                setState(() {
                  _address.is_default = value ? 1 : 0;
                });
              }, initValue: _address.is_default == 1),
            )
          ],
        ));
  }
}