import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../util/api.dart';
import '../../util/models.dart';
import '../../util/util.dart';
import '../../showAlert.dart';
import '../../showLineModal.dart';
class OrderDetailsPage extends StatefulWidget {
  final String orderNo;

  OrderDetailsPage({
    Key key,
    @required this.orderNo
  }): super(key: key);

  _OrderDetailsPageState createState() => _OrderDetailsPageState();
}

class _OrderDetailsPageState extends State < OrderDetailsPage > {

  OrderDetailData orderDetailObj;
  @override
  void initState() {
    super.initState();
    getOrderDetail(widget.orderNo).then((resp){
      if(isNotError(context, resp)){
       OrderDetailObj tempObj = OrderDetailObj.fromJson(resp.data);
       setState(() {
         orderDetailObj =tempObj.data;
       });
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("订单详情", style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(36)), ),
        centerTitle: true,
        backgroundColor: Color.fromRGBO(64, 98, 254, 1),
      ),
      body: Container(
        padding: EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setHeight(20), 0, ScreenUtil.getInstance().setHeight(20)),
        color: Color.fromRGBO(246, 246, 254, 1),
        child:orderDetailObj==null?Center(
          child:_getMoreWidget(),
        ): ListView(
          children: < Widget > [
            _sendInfo(),
            _getInfo(),
            ItemInfoWidget(obj:orderDetailObj),
          ],
        )
      ),
        
      //resizeToAvoidBottomPadding: false //键盘弹出，页面不跟随向上滑动,防止出现溢出错误
    );
  }

  Widget _sendInfo() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setHeight(20)),
      child: Column(
        children: < Widget > [
          titleWidget('lib/images/icon_send.png', '发件信息'),
          underLine(),
          contentWiget('电话', orderDetailObj.senderPhone!=null?orderDetailObj.senderPhone:orderDetailObj.sendCompanyPhone),
          contentWiget('企业编码', orderDetailObj.sendCompanyCode),
          contentWiget('企业名称', orderDetailObj.sendCompanyName),
          contentWiget('城市/区域', '${orderDetailObj.sendCompanyProvinceName}'+' '+'${orderDetailObj.sendCompanyCityName}'+' '+ '${orderDetailObj.sendCompanyAreaName}'),
          lastContentWiget('详细地址', orderDetailObj.sendCompanyAddress)
        ],
      )
    );
  }

  Widget _getInfo() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setHeight(20)),
      child: Column(
        children: < Widget > [
          titleWidget('lib/images/icon_shoujian.png', '收件信息'),
          underLine(),
          contentWiget('企业名称', orderDetailObj.receiptCompanyName),
          contentWiget('电话', orderDetailObj.receiptCompanyPhone),
          contentWiget('城市/区域', '${orderDetailObj.receiptCompanyProvinceName}'+' '+ '${orderDetailObj.receiptCompanyCityName}'+' '+ '${orderDetailObj.receiptCompanyAreaName}'),
          lastContentWiget('详细地址', orderDetailObj.sendCompanyAddress)
        ],
      )
    );
  }
}


class ItemInfoWidget extends StatefulWidget {
  final OrderDetailData obj;
  ItemInfoWidget({
    Key key,
    @required this.obj
  }): super(key: key);

  _ItemInfoWidgetState createState() => _ItemInfoWidgetState();
}

class _ItemInfoWidgetState extends State < ItemInfoWidget > {

  double afterTransportFee=0.0;//运费
  int afterGoodsNumber=0;//数量
  double afterCollectingFee=0.0;//代收
  bool submitStatus = true;
  String lineId = '-1';
   List<CompanyOfLineList>  lineList = [];
  @override
  void initState() {
    super.initState();
    setState(() {
       afterTransportFee = widget.obj.goodsFreight/100;
       afterGoodsNumber =widget.obj.goodsQuantity;
       afterCollectingFee =widget.obj.goodsAgencyFund/100;
    });
    getLineOfCompanyId(widget.obj.sendCompanyId.toString()).then((resp){
     if(isNotError(context, resp)){
        CompanyOfLine obj = CompanyOfLine.fromJson(resp.data);
        setState(() {
            lineList = obj.data;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: < Widget > [
            titleWidget('lib/images/icon_huowu.png', "货物信息"),
            underLine(),
            contentWiget("货物名称",widget.obj.goods),
            contentWiget("数量", (widget.obj.goodsQuantity).toString()),
            contentWiget("运费", (widget.obj.goodsFreight/100).toString()),
            contentWiget("代收", (widget.obj.goodsAgencyFund/100).toString()),
            contentWiget("保价", widget.obj.goodsPriceProtection.toString()),
            contentWiget("重量", widget.obj.goodsWeight.toStringAsFixed(1)),
            _descWidget(widget.obj.memo),
          ],
        ),
      )
    );
  }

  Widget _inputWidget(String key, num value) {
    return Padding(
      padding: EdgeInsets.only(left: ScreenUtil.getInstance().setWidth(30)),
      child: Column(
        children: < Widget > [
           SizedBox(
              height: ScreenUtil.getInstance().setHeight(89),
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: < Widget > [
                    Text(key, style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: Color.fromRGBO(74, 74, 74, 1)), ),
                    Container(
                      width: ScreenUtil.getInstance().setWidth(300),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: < Widget > [
                          Expanded(
                            //padding: EdgeInsets.only(right: ScreenUtil.getInstance().setWidth(20)),
                            //child: Text(value,style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: Color.fromRGBO(136, 136, 136, 1)), ),
                            child: Center(
                              child: TextField(
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.end,
                                style: TextStyle(
                                  fontSize: ScreenUtil.getInstance().setSp(30),
                                  color: Color.fromRGBO(136, 136, 136, 1)
                                ),
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: value.toString(),
                                  hintStyle: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: Color.fromRGBO(136, 136, 136, 1)),
                                  contentPadding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0, 0, 0),
                                ),
                                onChanged: (value){
                                  if(key=='数量'){
                                    afterGoodsNumber =int.parse(value);
                                  }else if(key=='运费'){
                                    afterTransportFee =double.parse(value);
                                    String temp = afterTransportFee.toStringAsFixed(1);
                                    afterTransportFee = double.parse(temp);
                                  }else if(key=='代收'){
                                    afterCollectingFee =double.parse(value);
                                     String temp = afterCollectingFee.toStringAsFixed(1);
                                     afterCollectingFee = double.parse(temp);
                                  }
                                },
                              ),
                            )
                          ),
                          Icon(Icons.keyboard_arrow_right, color: Color.fromRGBO(199, 199, 204, 1), )
                        ],
                      )
                    )
                  ],
                ),
              )
          ),
          Expanded(
            flex: 0,
            child: underLine()
          )
        ],
      )
    );
  }

  Widget _descWidget(String str) {
    return
    Container(
      padding: EdgeInsets.all(ScreenUtil.getInstance().setWidth(30)),
      child: Text(str, maxLines: 100, style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: Color.fromRGBO(74, 74, 74, 1)), ),
    );
  }

  Widget submitBtn(String orderNo) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(30), ScreenUtil.getInstance().setWidth(50), ScreenUtil.getInstance().setWidth(30), ScreenUtil.getInstance().setWidth(40)),
        height: ScreenUtil.getInstance().setHeight(88),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(4)),
          color: Color.fromRGBO(37, 102, 242, 1),
        ),
        child: Center(
        child:Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
                Offstage(
                  offstage: submitStatus,
                  child: SizedBox(
                    width: ScreenUtil.getInstance().setWidth(45),
                    height: ScreenUtil.getInstance().setHeight(45),
                    child: Image.asset('lib/images/loading.gif'),
                  ),
                ),
                Text('提交', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(36), color: Colors.white)),
            ],
          )
        ),
      ),
      onTap: () {
        if(!submitStatus) return;
         if(lineList.length==1){
            lineId = lineList[0].lineId.toString();
          }else if(lineList.length>1){
            showLineModal(lineList,orderNo);
            return;
        }
          submitOrder(orderNo);
      },
    );
  }
   showLineModal(List<CompanyOfLineList> list,String orderNo){
    showDialog < Null > (
      context: context, //BuildContext对象
      barrierDismissible: false,
      builder: (BuildContext context) {
        return ShowLineModal( 
          lineList: list, childCallback: (val) {
              lineId = val;
             submitOrder(orderNo);
          },
        );
      });
  }
  submitOrder(String orderNo){
     setState(() {
        submitStatus = false;
      });
      updataOrder(lineId,orderNo,afterTransportFee,afterCollectingFee,afterGoodsNumber).then((resp){
        if(isNotError(context, resp)){
          showDialog < Null > (
          context: context, //BuildContext对象
          barrierDismissible: false,
          builder: (BuildContext context) {
            return MyAlertDialog( //调用对话框
              text: '订单修改成功！', childCallback: (val) {
                if(val){
                  Navigator.pop(context,true);
                }
              },
            );
          });
        }else{
          setState(() {
            submitStatus = true;
          });
        }
      });
  }
 
}

Widget titleWidget(String iconUrl, String str) {
  return Container(
    height: ScreenUtil.getInstance().setHeight(90),
    padding: EdgeInsets.only(left: ScreenUtil.getInstance().setWidth(30)),
    child: Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: < Widget > [
          Padding(
            padding: EdgeInsets.only(right: ScreenUtil.getInstance().setHeight(20)),
            child: Image.asset(
              iconUrl,
              width: ScreenUtil.getInstance().setWidth(40),
              height: ScreenUtil.getInstance().setHeight(40),
            )
          ),
          Text(str, style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(32)), )
        ],
      ),
    ),
  );
}

Widget underLine() {
  return Container(
    color: Color.fromRGBO(223, 223, 223, 1),
    height: ScreenUtil.getInstance().setHeight(1),
  );
}

Widget contentWiget(String key, String value) {
  return Padding(
    padding: EdgeInsets.only(left: ScreenUtil.getInstance().setWidth(30)),
    child: Column(
      children: < Widget > [
        Padding(
          padding: EdgeInsets.only(right: ScreenUtil.getInstance().setWidth(30)),
          child: SizedBox(
            height: ScreenUtil.getInstance().setHeight(89),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: < Widget > [
                  Text(key, style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: Color.fromRGBO(74, 74, 74, 1)), ),
                  Text(value, style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: Color.fromRGBO(136, 136, 136, 1)), ),
                ],
              ),
            )
          )
        ),
        Expanded(
          flex: 0,
          child: underLine()
        )
      ],
    )
  );
}

Widget lastContentWiget(String key, String value) {
  return Padding(
    padding: EdgeInsets.only(left: ScreenUtil.getInstance().setWidth(30)),
    child:
    Padding(
      padding: EdgeInsets.only(right: ScreenUtil.getInstance().setWidth(30)),
      child: SizedBox(
        height: ScreenUtil.getInstance().setHeight(89),
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: < Widget > [
              Text(key, style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: Color.fromRGBO(74, 74, 74, 1)), ),
              Text(value, style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: Color.fromRGBO(136, 136, 136, 1)), ),
            ],
          ),
        )
      )
    ),
  );
}

Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: < Widget > [
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            Container(
              width: ScreenUtil.getInstance().setWidth(50),
              height: ScreenUtil.getInstance().setHeight(50),
              child: CircularProgressIndicator()
            )

          ],
        ),
      ),
    );
  }