import 'dart:convert';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:base/consts/color.dart';
import 'package:base/consts/route_category_front_component_const.dart';
import 'package:base/consts/toast_message.dart';
import 'package:base/model/route_model.dart';
import 'package:base/services/application.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:base/utils/app_theme.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/dialog/select_reason.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../routes/routes.dart';
import '../services/offline_plan_inspection_services.dart';

GlobalKey<_EquipmentAddListContentState> childKey = GlobalKey();

class OfflineAddFireAgentConfirm extends StatelessWidget {
  final RouteModel routeModel;

  const OfflineAddFireAgentConfirm({this.routeModel});

  @override
  Widget build(BuildContext context) {
    return AddFireAgentConfirmContent(
      key: childKey,
      routeModel: routeModel,
    );
  }
}

class AddFireAgentConfirmContent extends StatefulWidget {
  final RouteModel routeModel;

  const AddFireAgentConfirmContent({Key key, this.routeModel}) : super(key: key);

  @override
  _EquipmentAddListContentState createState() => _EquipmentAddListContentState();
}

class _EquipmentAddListContentState extends State<AddFireAgentConfirmContent> {
  final List _addItems = [];
  String category;
  String item;
  String position;
  String theme = '';

  List getAddItems() {
    return _addItems;
  }

  @override
  void initState() {
    super.initState();
    category = RouteCategoryFrontComponentConst.fireExtinguishingAgent;
    item = widget.routeModel.item;
    position = widget.routeModel.extension['position'];
    _addItems.addAll(widget.routeModel.extension['extension']);
    initThemeConfig();
  }

  Future<void> initThemeConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            '${widget.routeModel.title}',
            style: const TextStyle(color: Colors.black),
          ),
          leading: LeadingButton(
            theme: theme,
            onWillScope: true,
            onWillPop: () {
              Navigator.of(context).pop(childKey.currentState.getAddItems());
            },
          ),
          centerTitle: true,
        ),
        body: Stack(
          children: <Widget>[buildEquipList(context), buildBottom(context)],
        ));
  }

  // 顶部导航条
  Widget buildTopBar(context) {
    return Align(
      alignment: Alignment.topCenter,
      child: Container(
        height: 40.px,
        color: Colors.white,
        padding: EdgeInsets.only(left: 16.px, right: 5.px),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              '已添加:  ${_addItems.length}',
              style: Theme.of(context).textTheme.headline6,
            ),
            FlatButton(
              padding: EdgeInsets.zero,
              onPressed: () => continueAdd(context),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '继续添加',
                    style: Theme.of(context).textTheme.headline6,
                  ),
                  Icon(
                    Icons.keyboard_arrow_right,
                    color: GetConfig.getColor(theme),
                    size: 30.px,
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  // 底部按钮
  Widget buildBottom(context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 48.px,
        width: double.infinity,
        child: RaisedButton(
          color: GetConfig.getColor(theme),
          child: Text(
            '提交',
            style: Theme.of(context).textTheme.headline2,
          ),
          onPressed: () => submit(context),
        ),
      ),
    );
  }

  // 装备列表
  Widget buildEquipList(context) {
    return Column(
      children: <Widget>[
        buildTopBar(context),
        Expanded(
          child: ListView.builder(
              padding: EdgeInsets.only(bottom: 48.px, left: 5.px, right: 5.px, top: 5.px),
              itemCount: _addItems.length,
              itemBuilder: (ctx, index) {
                final it = _addItems[index];
                return buildContentCard(it);
              }),
        ),
      ],
    );
  }

  // 选择不同的展示列表Card
  Widget buildContentCard(it) {
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.inStock) {
      return FireAgentAddCard(
        item: it,
        position: position,
        deleteConfirm: (item) {
          print(item);
          int index = _addItems.indexOf(item);
          _addItems.removeAt(index);
          setState(() {});
        },
      );
    } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.extinguishWastage) {
      return WasteFireAgentCard(
          item: it,
          deleteConfirm: (item) {
            print(item);
            int index = _addItems.indexOf(item);
            _addItems.removeAt(index);
            setState(() {});
          });
    } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.extinguishLoad) {
      return LoadCard(
          item: it,
          deleteConfirm: (item) {
            print(item);
            int index = _addItems.indexOf(item);
            _addItems.removeAt(index);
            setState(() {});
          });
    } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.scraped) {
      return ScrapCard(
        theme: theme,
        item: it,
        deleteConfirm: (item) {
          print(item);
          int index = _addItems.indexOf(item);
          _addItems.removeAt(index);
          setState(() {});
        },
        selectReasonCallBack: () {
          setState(() {});
        },
      );
    } else {
      return Container();
    }
  }

  // 继续添加
  void continueAdd(context) {
    Navigator.of(context).pop(_addItems);
  }

  // 提交
  void submit(context) {
    if (_addItems.isEmpty) {
      FlutterToast.toastCenter(ToastMessage.listEmpty);
      return;
    }

    String _description = widget.routeModel.extension['description'];

    // 灭火药剂入账
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (item == RouteItemFrontComponentConst.extinguishWastage) {
        List params = [];
        for (final item in _addItems) {
          params.add({
            'amount': double.parse(item['amount']),
            'equipmentDetailId': item['equipmentDetailId'],
            'total': item['model']['amount'],
            'carId': item['model']['car_id']
          });
        }
        getInStockEquipment(params, '33').then((value) {
          if (value) {
            final param = {
              'title': widget.routeModel.title,
              'category': category,
              'item': item,
            };
            Application.navigateToPath(context, Routes.offlineSubmitSuccess, params: param);
          }
        });
      } else if (item == RouteItemFrontComponentConst.extinguishLoad) {
        List params = [];
        for (final item in _addItems) {
          double count = double.parse(item['model']['amount']) - double.parse(item['amount']);
          var pame = widget.routeModel.extension;
          params.add({
            'zamount': count.toString(),
            'amount': double.parse(item['amount']),
            'stockDetailId': item['model']['id'],
            'equipmentDetailId': item['model']['equipmentDetailId'],
            'warehouseStructureId': item['model']['warehouseStructureId'],
            'carId': pame['extension'][0]['car_id'],
            'equipmentSpecificId': item['model']['equipmentDetail']['id']
          });
        }
        getInStockEquipment(params, '32').then((value) {
          if (value) {
            final param = {
              'title': widget.routeModel.title,
              'category': category,
              'item': item,
            };
            Application.navigateToPath(context, Routes.offlineSubmitSuccess, params: param);
          }
        });
      } else if (item == RouteItemFrontComponentConst.scraped) {
        // 报废
        List params = [];
        bool hasReason = true;
        for (final item in _addItems) {
          if (item['reason'] == null) {
            hasReason = false;
            break;
          }
          var amout = double.parse(item['model']['amount'].toString()) - double.parse(item['amount']);
          params.add({
            'amount': double.parse(item['amount']),
            'stockDetailId': item['model']['id'],
            'equipmentDetailId': item['model']['equipmentDetailId'],
            'warehouseStructureId': item['model']['warehouseStructureId'],
            'departmentName': item['model']['departmentName'],
            'reason': item['reason'],
            'bfamout': amout.toString()
          });
        }

        if (!hasReason) {
          FlutterToast.toastCenter('请选择原因!');
          return;
        }
        getInStockEquipment(params, '34').then((value) {
          if (value) {
            final param = {
              'title': widget.routeModel.title,
              'category': category,
              'item': item,
              'extension': json.encode({'list': json.encode(_addItems), 'createDate': DateTime.now().toString()})
            };
            Application.navigateToPath(context, Routes.offlineScrapPostBill, params: param);
          }
        });
      }
    }
  }
}

// 灭火药剂入账展示
class FireAgentAddCard extends StatelessWidget {
  final item;
  final ValueChanged<Map> deleteConfirm;
  final String position;

  const FireAgentAddCard({this.item, this.deleteConfirm, this.position});

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: const Color(0xFF455b63).withOpacity(0.08),
      child: Stack(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: Image.asset(
                  'assets/images/defule.png',
                  width: 70.px,
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text('${item['model']['equipmentDetail']['name']}',
                        style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 17.px)),
                    SizedBox(
                      height: 5.px,
                    ),
                    Text(
                      '入库数量: ${item['amount']}${item['model']['equipmentDetail']['unitName']}',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                    ),
                    Text(
                      '库存:   ${item['model']['amount']}${item['model']['equipmentDetail']['unitName']}',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    position != null
                        ? Text(
                            '位置:   $position',
                            style: Theme.of(context).textTheme.headline3.copyWith(fontSize: 13.px),
                          )
                        : Container(),
                    SizedBox(
                      height: 10.px,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child: SvgButton(
              size: 40.px,
              src: 'assets/images/icon_clear.svg',
              onTap: () {
                if (deleteConfirm != null) {
                  deleteConfirm(item);
                }
              },
            ),
          )
        ],
      ),
    );
  }
}

// 损耗展示列表
class WasteFireAgentCard extends StatelessWidget {
  final item;
  final ValueChanged<Map> deleteConfirm;

  const WasteFireAgentCard({this.item, this.deleteConfirm});

  @override
  Widget build(BuildContext context) {
    print(item);
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: const Color(0xFF455b63).withOpacity(0.08),
      child: Stack(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: Image.asset(
                  'assets/images/defule.png',
                  width: 70.px,
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text('${item['model']['equipmentName']}',
                        style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 17.px)),
                    SizedBox(
                      height: 5.px,
                    ),
                    // Row(
                    //   children: <Widget>[
                    Text(
                      '原有存量: ${item['model']['amount']}${item['model']['unitName']}',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    Text(
                      '现有存量:   ${item['amount']}${item['model']['unitName']}',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                    ),
                    //   ],
                    // ),
                    SizedBox(
                      height: 5.px,
                    ),
                    Text(
                      '损耗量:  ${(item['model']['amount'] - double.parse(item['amount']) as double).toStringAsFixed(1)}${item['model']['unitName']}',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                    ),
                    SizedBox(
                      height: 10.px,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child: SvgButton(
              size: 40.px,
              src: 'assets/images/icon_clear.svg',
              onTap: () {
                if (deleteConfirm != null) {
                  deleteConfirm(item);
                }
              },
            ),
          )
        ],
      ),
    );
  }
}

// 报废
class ScrapCard extends StatelessWidget {
  final item;
  final ValueChanged<Map> deleteConfirm;
  final Function selectReasonCallBack;
  final String theme;

  const ScrapCard({this.item, this.deleteConfirm, this.selectReasonCallBack, this.theme});

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: const Color(0xFF455b63).withOpacity(0.08),
      child: Stack(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: Image.asset(
                  'assets/images/defule.png',
                  width: 70.px,
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text('${item['model']['equipmentDetail']['name']}',
                        style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 16.px)),
                    SizedBox(
                      height: 5.px,
                    ),
                    // Row(
                    //   children: <Widget>[
                    Text(
                      '报废数量: ${item['amount']}${item['model']['equipmentDetail']['unitName']}   ',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    Text(
                      '库存:   ${item['model']['amount']}${item['model']['equipmentDetail']['unitName']}',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                    ),
                    SizedBox(
                      height: 10.px,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          '报废原因:',
                          style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                        ),
                        InkWell(
                          onTap: () => selectReason(context, item, theme),
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: 140.px,
                                child: Text(
                                  '${item['reason'] ?? ''}',
                                  textAlign: TextAlign.end,
                                  style: Theme.of(context).textTheme.headline3,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              const Icon(
                                Icons.keyboard_arrow_right,
                                size: 30,
                                color: Color(0xFF999999),
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 12.px,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child: SvgButton(
              size: 40.px,
              src: 'assets/images/icon_clear.svg',
              onTap: () {
                if (deleteConfirm != null) {
                  deleteConfirm(item);
                }
              },
            ),
          )
        ],
      ),
    );
  }

  void selectReason(BuildContext context, Map it, String theme) {
    showModalBottomSheet(
        enableDrag: false,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.px)),
        context: context,
        builder: (BuildContext context) {
          return SelectReasonDialog(
            theme: theme,
            callback: (str) {
              it['reason'] = str;
              selectReasonCallBack();
            },
          );
        });
  }
}

// 装载
class LoadCard extends StatelessWidget {
  final item;
  final ValueChanged<Map> deleteConfirm;

  const LoadCard({this.item, this.deleteConfirm});

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: const Color(0xFF455b63).withOpacity(0.08),
      child: Stack(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: Image.asset(
                  'assets/images/defule.png',
                  width: 70.px,
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text('${item['model']['equipmentDetail']['name']}',
                        style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 16.px)),
                    SizedBox(
                      height: 5.px,
                    ),
                    Row(
                      children: <Widget>[
                        Text(
                          '库存: ${item['model']['amount']}${item['model']['equipmentDetail']['unitName']}',
                          style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                        ),
                        Text(
                          '  装载数量:   ${item['amount']} ${item['model']['equipmentDetail']['unitName']}',
                          style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 10.px,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child: SvgButton(
              size: 40.px,
              src: 'assets/images/icon_clear.svg',
              onTap: () {
                if (deleteConfirm != null) {
                  deleteConfirm(item);
                }
              },
            ),
          )
        ],
      ),
    );
  }
}
