import 'dart:convert';
import 'dart:ui';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';

import 'package:base/consts/color.dart';
import 'package:base/consts/route_category_front_component_const.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/widgets/back_button.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

GlobalKey<_CreateScrapContentState> childkey = GlobalKey();

// 新建报废
class OfflineCreateScrap extends StatelessWidget {
  final RouteModel routeModel;

  OfflineCreateScrap({this.routeModel});

  @override
  Widget build(BuildContext context) {
    // String title = (routeModel.category ==
    //         RouteCategoryFrontComponentConst.fireExtinguishingAgent)
    //     ? "灭火药剂报废"
    //     : (routeModel.category ==
    //             RouteCategoryFrontComponentConst.fireFightingVehicle)
    //         ? "消防车辆报废"
    //         : "消防装备报废";
    // return Scaffold(
    //   backgroundColor: AppTheme.backgroundColor,
    //   appBar: AppBar(
    //     title: Text(
    //       title,
    //       style: TextStyle(color: Colors.black),
    //     ),
    //     centerTitle: true,
    //     leading: LeadingButton(
    //       theme: childkey.currentState.theme,
    //     ),
    //   ),
    //   body:
    return CreateScrapContent(routeModel);
  }
}

class CreateScrapContent extends StatefulWidget {
  final RouteModel routeModel;

  CreateScrapContent(this.routeModel);

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

class _CreateScrapContentState extends State<CreateScrapContent> {
  String category;
  String item;

  List data = [];
  bool isEmpty = false;

  EasyRefreshController _controller = EasyRefreshController();
  String theme = '';

  initThemeConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        this.theme =
            preferences.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

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

    category = widget.routeModel.category;
    item = widget.routeModel.item;
    initThemeConfig();
    getScrapList();
  }

  // 获取最新数据
  void getScrapList() async {
    List item = [];
    String type = '15';
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      type = '34';
    } else if (category ==
        RouteCategoryFrontComponentConst.fireFightingVehicle) {
      type = '26';
    } else {
      type = '15';
    }
    StringBuffer sql = new StringBuffer();
    sql.write("select * from scrapPostBill where type=$type;");
    var lstTask = await dbAccess().queryData(sql.toString());
    for (var dit in lstTask) {
      if (dit['imageUrl'].toString().length == 0 ||
          dit['imageUrl'].toString() == '[]') {
        item.add(dit);
      }
    }
    setState(() {
      data = item;
    });
    // 灭火药剂
    // if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
    //   // 报废
    //   if (item == RouteItemFrontComponentConst.scraped) {
    //     final params = {"pageNum": 1, "billType": 3};
    //     HttpRequest.checkScrapList(params: params).then((res) {
    //       if (res["status"] == 200) {
    //         List items = res["result"]["records"];
    //         List<ScrapBillModel> models = [];
    //         _total = res["result"]["pages"];
    //         for (var json in items) {
    //           models.add(ScrapBillModel.fromJson(json));
    //         }
    //         if (items.length > 0) {
    //           setState(() {
    //             data = models;
    //           });
    //         } else {
    //           setState(() {
    //             isEmpty = true;
    //           });
    //         }
    //       }
    //     }).catchError((err) {});
    //   }
    // }
    // // 消防车辆
    // else if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
    //   if (item == RouteItemFrontComponentConst.scraped) {
    //     final params = {"pageNum": 1, "billType": 2};
    //     HttpRequest.checkScrapList(params: params).then((res) {
    //       if (res["status"] == 200) {
    //         List items = res["result"]["records"];
    //         _total = res["result"]["pages"];
    //         List<ScrapBillModel> models = [];
    //         for (var json in items) {
    //           models.add(ScrapBillModel.fromJson(json));
    //         }
    //         if (items.length > 0) {
    //           setState(() {
    //             data = models;
    //           });
    //         } else {
    //           setState(() {
    //             isEmpty = true;
    //           });
    //         }
    //       }
    //     }).catchError((err) {});
    //   }
    // }
    // else {
    //   final params = {"pageNum": 1, "billType": 1};
    //   HttpRequest.checkScrapList(params: params).then((res) {
    //     if (res["status"] == 200) {
    //       List items = res["result"]["records"];
    //       _total = res["result"]["pages"];
    //       List<ScrapBillModel> models = [];
    //       for (var json in items) {
    //         models.add(ScrapBillModel.fromJson(json));
    //       }
    //       if (items.length > 0) {
    //         setState(() {
    //           data = models;
    //         });
    //       } else {
    //         setState(() {
    //           isEmpty = true;
    //         });
    //       }
    //     }
    //   }).catchError((err) {});
    // }
  }

  // 获取更多数据
  // void getMoreScrapList() {
  //   _currentPage++;
  //   print("当前请求的是第$_currentPage页");
  //   // 灭火药剂
  //   if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
  //     // 报废
  //     if (item == RouteItemFrontComponentConst.scraped) {
  //       final params = {"pageNum": _currentPage, "billType": 3};
  //       HttpRequest.checkScrapList(params: params).then((res) {
  //         if (res["status"] == 200) {
  //           List items = res["result"]["records"];
  //           List<ScrapBillModel> models = [];
  //           for (var json in items) {
  //             models.add(ScrapBillModel.fromJson(json));
  //           }
  //           setState(() {
  //             data.addAll(models);
  //           });
  //         }
  //       }).catchError((err) {
  //         _currentPage--;
  //       });
  //     }
  //   }
  //   // 消防车辆
  //   else if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
  //     if (item == RouteItemFrontComponentConst.scraped) {
  //       final params = {"pageNum": _currentPage, "billType": 2};
  //       HttpRequest.checkScrapList(params: params).then((res) {
  //         if (res["status"] == 200) {
  //           List items = res["result"]["records"];
  //           List<ScrapBillModel> models = [];
  //           for (var json in items) {
  //             models.add(ScrapBillModel.fromJson(json));
  //           }
  //           setState(() {
  //             data.addAll(models);
  //           });
  //         }
  //       }).catchError((err) {
  //         _currentPage--;
  //       });
  //     }
  //   } else {
  //     final params = {"pageNum": _currentPage, "billType": 1};
  //     HttpRequest.checkScrapList(params: params).then((res) {
  //       if (res["status"] == 200) {
  //         List items = res["result"]["records"];
  //         List<ScrapBillModel> models = [];
  //         for (var json in items) {
  //           models.add(ScrapBillModel.fromJson(json));
  //         }
  //
  //         setState(() {
  //           data.addAll(models);
  //         });
  //       }
  //     }).catchError((err) {
  //       _currentPage--;
  //     });
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    String title = (widget.routeModel.category ==
            RouteCategoryFrontComponentConst.fireExtinguishingAgent)
        ? "灭火药剂报废"
        : (widget.routeModel.category ==
                RouteCategoryFrontComponentConst.fireFightingVehicle)
            ? "消防车辆报废"
            : "消防装备报废";
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            title,
            style: TextStyle(color: Colors.black),
          ),
          centerTitle: true,
          leading: LeadingButton(
            theme: theme,
          ),
        ),
        body: Stack(
          children: <Widget>[buildEquipList(context), buildBottom(context)],
        ));
  }

  Widget buildBottom(context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 50.px,
        width: double.infinity,
        child: RaisedButton(
          color: GetConfig.getColor(theme),
          child: Text(
            "新建报废",
            style: Theme.of(context).textTheme.headline2,
          ),
          onPressed: () => onTap(context),
        ),
      ),
    );
  }

  Widget buildEquipList(context) {
    // if (isEmpty) {
    //   return Center(
    //     child: Text("当前数据为空"),
    //   );
    // } else
    if (data.length == 0) {
      return Center(
        child: Text("当前数据为空"),
      );
    } else {
      return SingleChildScrollView(
        child: ListView.builder(
            padding: EdgeInsets.only(
                bottom: 10.px, left: 10.px, right: 10.px, top: 5.px),
            itemCount: data.length,
            // padding: EdgeInsets.only(left: 5, right: 5),
            physics: const NeverScrollableScrollPhysics(),
            key: PageStorageKey('data'),
            // itemCount: basicList.length,
            shrinkWrap: true,
            itemBuilder: (ctx, index) {
              return AddDetailCard(
                  theme: theme,
                  model: data[index],
                  routeModel: widget.routeModel,
                  callback: () {
                    setState(() {
                      data = [];
                    });
                    getScrapList();
                  });
            }),
      );
    }
  }

  void onTap(context) {
    // 灭火药剂报废和车辆器材跳转不一样

    String category = widget.routeModel.category;

    // 灭火药剂
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (item == RouteItemFrontComponentConst.scraped) {
        final params = {
          "title": widget.routeModel.title,
          "category": widget.routeModel.category,
          "item": widget.routeModel.item
        };
        Application.navigateToPath(context, Routes.offlineFireAgentInStock,
                params: params)
            .then((value) {
          getScrapList();
        });
      }
    }
    // 车辆
    else if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
      if (item == RouteItemFrontComponentConst.scraped) {
        final params = {
          "title": widget.routeModel.title,
          "category": widget.routeModel.category,
          "item": widget.routeModel.item
        };
        Application.navigateToPath(context, Routes.offlineEquipWareHousing,
                params: params)
            .then((value) {
          getScrapList();
        });
      }
    }
    // 器材
    else if (category == RouteCategoryFrontComponentConst.equipment) {
      if (item == RouteItemFrontComponentConst.scraped) {
        final params = {
          "title": widget.routeModel.title,
          "category": widget.routeModel.category,
          "item": widget.routeModel.item
        };
        Application.navigateToPath(context, Routes.offlineEquipWareHousing,
                params: params)
            .then((value) {
          getScrapList();
        });
      }
    }
  }
}

class AddDetailCard extends StatelessWidget {
  final dynamic model;
  final RouteModel routeModel;
  final Function callback;
  final String theme;

  AddDetailCard({this.model, this.routeModel, this.callback, this.theme});

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: Color(0xFF455b63).withOpacity(0.08),
      child: Row(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(15.px, 15.px, 18.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,
                ),
                // RichText(
                //   text: TextSpan(
                //       text: "单据编号  ",
                //       style: Theme.of(context)
                //           .textTheme
                //           .subtitle2
                //           .copyWith(fontSize: 14.px, color: Color(0xFF666666)),
                //       children: [
                //         ...model.billCode.runes.map((rune) {
                //           return WidgetSpan(
                //               child: Text(
                //             String.fromCharCode(rune),
                //             style: Theme.of(context).textTheme.headline4,
                //           ));
                //         }),
                //       ]),
                // ),
                SizedBox(
                  height: 5.px,
                ),
                Text(
                  "待报废",
                  style: Theme.of(context)
                      .textTheme
                      .headline4
                      .copyWith(color: GetConfig.getColor(theme)),
                ),
                SizedBox(
                  height: 1.px,
                ),
                // Text(
                //   "数量:   ${model.detailCount}个",
                //   style: Theme.of(context)
                //       .textTheme
                //       .subtitle2
                //       .copyWith(fontSize: 13.px),
                // ),
                SizedBox(
                  height: 8.px,
                ),
                Text(
                  "${model['createDate'].toString().substring(0, 19)}",
                  style: Theme.of(context)
                      .textTheme
                      .subtitle2
                      .copyWith(fontSize: 15.px),
                ),
                SizedBox(
                  height: 20.px,
                ),
              ],
            ),
          ),
          InkWell(
            onTap: () => addScrap(context, model),
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 20.px, horizontal: 20.px),
              child: Column(
                children: <Widget>[
                  Text(
                    "报",
                    style: Theme.of(context)
                        .textTheme
                        .headline4
                        .copyWith(color: GetConfig.getColor(theme)),
                  ),
                  Text(
                    "废",
                    style: Theme.of(context)
                        .textTheme
                        .headline4
                        .copyWith(color: GetConfig.getColor(theme)),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  // 点击报废
  void addScrap(BuildContext context, dynamic model) {
    //final result = {"billCode": model[''], "id": model.id};

    final params = {
      "title": routeModel.title,
      "category": routeModel.category,
      "item": routeModel.item,
      "extension": json.encode({
        "reason": model["reason"],
        "list": model['jsonString'],
        "createDate": model['createDate']
      }),
    };

    Application.navigateToPath(context, Routes.offlineScrapPostBill,
            params: params)
        .then((value) {
      callback();
    });
  }
}
