import 'dart:convert';
import 'dart:typed_data';
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/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:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

GlobalKey<_ScrapPostBillContentState> childKey = GlobalKey();

// 报废上传单据
class OfflineScrapPostBill extends StatelessWidget {
  final RouteModel routeModel;

  OfflineScrapPostBill({this.routeModel});

  @override
  Widget build(BuildContext context) {
    // return Scaffold(
    //   backgroundColor: AppTheme.backgroundColor,
    //   appBar: AppBar(
    //     title: Text(routeModel?.title,style: Theme.of(context).textTheme.headline2,),
    //     centerTitle: true,
    //     leading: LeadingButton(
    //       theme:childKey.currentState.theme ,
    //       onWillPop: (){
    //         Navigator.of(context).popUntil((route) => route.settings.name.startsWith(Routes.createScrap));
    //       },
    //       onWillScope: true,
    //     ),
    //   ),
    //   body: WillPopScope(
    //      onWillPop: (){
    //        Navigator.of(context).popUntil((route) => route.settings.name.startsWith(Routes.createScrap));
    //        return Future.value(false);
    //      },
    //       child:
    return ScrapPostBillContent(
      routeModel: routeModel,
    );
  }
}

class ScrapPostBillContent extends StatefulWidget {
  final RouteModel routeModel;

  ScrapPostBillContent({this.routeModel});

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

class _ScrapPostBillContentState extends State<ScrapPostBillContent> {
  List<Asset> images = [];

  List<dynamic> data = [];
  List imageUrls = [];

  bool isEmpty = false;
  String category;
  String item;

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

    category = widget.routeModel.category;
    item = widget.routeModel.item;

    getScrapDetailList();
    initThemeConfig();
  }

  String theme = '';

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

  // 获取报废列表
  void getScrapDetailList() {
    // final scrapId = widget.routeModel.extension["id"];
    // if(scrapId == null)return;
    // showDialog(
    //     context: context,
    //     builder: (ctx) {
    //       return LoadingDialog(
    //         barrierDismissible: true,
    //       );
    //     });
    // final scrap={
    //   "scrapId":scrapId,
    // };
    // final params = {
    //   "pageNum":0,
    //   //"scrapDetail":scrap,
    //   "scrapId":scrapId,
    //   "pageSize":HttpConfig.pageSize
    // };
    // HttpRequest.scrapDetailList(params:params).then((res){
    //  // Navigator.of(context).pop();
    //    if(res["status"] == 200) {
    List records = json.decode(widget.routeModel.extension['list']);
    //  List items = [];
    //
    // // if(category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
    //
    //  // } else
    //   if(category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
    //    for(var json in records) {
    //      //items.add(ScrapVehicleDetailListModel.fromJson(json['model']));
    //      ScrapVehicleDetailListModel model=ScrapVehicleDetailListModel();
    //      model.createDate=DateTime.now().toString();
    //      model.stockDetailId=json['stockDetailId'];
    //      model.amount=json['amount'];
    //      model.reason=json['reason'];
    //      model.car=Car.fromJson(json['model']);
    //      items.add(model);
    //    }}else {
    //     for(var json in records) {
    //       ScrapDetailListModel model=ScrapDetailListModel();
    //       model.createDate=DateTime.now();
    //       model.stockDetailId=json['stockDetailId'];
    //       model.amount=json['amount'];
    //       model.reason=widget.routeModel.extension["reason"];
    //       model.stockDetail=StockDetail.fromJson(json);
    //       items.add(model);
    //     }
    //   }

    // }}
    // } else if(category == RouteCategoryFrontComponentConst.equipment) {
    //   for(var json in records) {
    //     items.add(ScrapDetailListModel.fromJson(json['model']));
    //   }
    // }
    if (records.length > 0) {
      setState(() {
        data = records;
      });
    } else {
      setState(() {
        isEmpty = true;
      });
    }
    //    }
    // }).catchError((err){
    //   print(err);
    //   //Navigator.of(context).pop();
    // });
  }

  Future getreturn() async {
    await clickScrap(context, '2');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            widget.routeModel?.title,
            style: TextStyle(color: Colors.black),
          ),
          centerTitle: true,
          leading: LeadingButton(
            theme: theme,
            onWillPop: () {
              getreturn();
              // clickScrap(context);
              // Navigator.of(context).popUntil((route) => route.settings.name.startsWith(Routes.main));
            },
            onWillScope: true,
          ),
        ),
        body: WillPopScope(
            onWillPop: () {
              getreturn();
              //     clickScrap(context);
              // Navigator.of(context).popUntil((route) => route.settings.name.startsWith(Routes.main));
              return Future.value(false);
            },
            child: Stack(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(bottom: 50.px),
                  child: Column(
                    children: <Widget>[
                      buildTitleAndImage(context),
                      buildBillList(context)
                    ],
                  ),
                ),
                buildBottom(context)
              ],
            )));
  }

//  Image.asset("assets/images/icon_image_placeholder.png",),
  // 标题和头部
  Widget buildTitleAndImage(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          width: double.infinity,
          color: Colors.white,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.px, vertical: 12.px),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                RichText(
                  text: TextSpan(children: [
                    TextSpan(
                        text: "单据类型",
                        style: Theme.of(context).textTheme.headline3),
                    WidgetSpan(
                        child: SizedBox(
                      width: 12.px,
                    )),
                    TextSpan(
                        text: "待报废单据",
                        style: Theme.of(context).textTheme.headline4),
                  ]),
                ),
                // RichText(
                //   text: TextSpan(
                //       children: [
                //         TextSpan(text: "单据编号",style: Theme.of(context).textTheme.headline3),
                //         WidgetSpan(child: SizedBox(width: 12.px,)),
                //         TextSpan(text: "${ widget.routeModel.extension["billCode"]}",style: Theme.of(context).textTheme.headline4),
                //       ]
                //   ),
                // ),
                Padding(
                  padding: EdgeInsets.only(top: 12.px),
                  child: Text("添加凭据",
                      style: Theme.of(context).textTheme.headline4),
                )
              ],
            ),
          ),
        ),
        Container(
          height: 100.px,
          padding: EdgeInsets.fromLTRB(16.px, 0, 16.px, 22.px),
          color: Colors.white,
          child: GridView.builder(
              itemCount: images.length + 1,
              scrollDirection: Axis.horizontal,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 1,
                mainAxisSpacing: 5.px,
              ),
              itemBuilder: (ctx, index) {
                if (images.length > 0) {
                  if (index < images.length) {
                    Asset asset = images[index];
                    return Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.center,
                          child: AssetThumb(
                            asset: asset,
                            width: 70,
                            height: 70,
                          ),
                        ),
                        Positioned(
                          right: -5,
                          top: -5,
                          child: SvgButton(
                            onTap: () {
                              images.removeAt(index);
                              // imageUrls.removeAt(index);
                              setState(() {});
                            },
                            src: "assets/images/icon_image_clear.svg",
                          ),
                        )
                      ],
                    );
                  } else {
                    return buildPlaceholderContainer();
                  }
                } else {
                  return buildPlaceholderContainer();
                }
              }),
        )
      ],
    );
  }

  Widget buildPlaceholderContainer() {
    return Center(
        child: InkWell(
            onTap: () async {
              List<Asset> resultList = List<Asset>();
              String error = 'No Error Dectected';
              try {
                resultList = await MultiImagePicker.pickImages(
                  maxImages: 3,
                  enableCamera: true,
                  selectedAssets: images,
                  cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
                  materialOptions: MaterialOptions(
                    actionBarColor: "#abcdef",
                    allViewTitle: "所有图片",
                    useDetailsView: false,
                    selectCircleStrokeColor: "#000000",
                  ),
                );
                setState(() {
                  images = resultList;
                });
              } on Exception catch (e) {
                error = e.toString();
              }
            },
            child: Image.asset(
              "assets/images/icon_image_placeholder.png",
              width: 60.px,
              height: 60.px,
            )));
  }

  // 上传图片
  void uploadImage(context) async {
    if (images.length == 0) {
      FlutterToast.toastCenter("请上传凭证!");
      return;
    }
    // showDialog(context: context,builder: (ctx){
    //   return LoadingDialog(
    //     barrierDismissible: true,
    //   );
    // });
    // bool uoloadSucess = true;
    for (int i = 0; i < images.length; i++) {
      // imageUrls.add(json.encode(images[i]));

      //   // 获取 ByteData
      ByteData byteData = await images[i].getByteData(quality: 30);
      List<int> imageData = byteData.buffer.asUint8List();
      //
      //   MultipartFile multipartFile = MultipartFile.fromBytes(
      //     imageData,
      //     // 文件名
      //     filename: images[i].name,
      //     // 文件类型
      //     contentType: MediaType("image", "jpg"),
      //   );
      //   FormData formData = FormData.fromMap({
      //     "files": multipartFile
      //   });
      imageUrls.add(imageData);
      // 使用 dio 上传图片
      // var response = await HttpRequest.uploadImage(data: formData);
      // if(response["status"] == 200) {
      //   imageUrls.add(response["result"]["url"]);
      // } else {
      //   uoloadSucess = false;
      //   break;
      // }
      clickScrap(context, '1');
    }

    // Navigator.of(context).pop();
    // if(uoloadSucess) {
    //   FlutterToast.toastCenter("图片上传成功!");
    // } else {
    //   FlutterToast.toastCenter("上传图片失败!");
    //   setState(() {
    //     images = [];
    //   });
    // }
  }

  // 底部按钮
  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: () => uploadImage(context),
        ),
      ),
    );
  }

  // 内容列表
  Widget buildBillList(context) {
    if (isEmpty) {
      return Expanded(
        child: Center(
          child: Text("当前数据为空"),
        ),
      );
    } else if (data.length == 0) {
      return Expanded(
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      return getListViewContent();
    }
  }

  Widget getListViewContent() {
    // 灭火药剂
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      return Expanded(
        child: ListView.separated(
            padding: EdgeInsets.only(top: 1),
            itemCount: data.length,
            itemBuilder: (ctx, index) {
              dynamic it = data[index];
              return Container(
                color: Colors.white,
                child: Row(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.fromLTRB(23.px, 15.px, 25.px, 15.px),
                      child: Image.asset(
                        "assets/images/icon_default.png",
                        width: 80.px,
                      ),
                    ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(
                            height: 18.px,
                          ),
                          Text(
                            "${it['model']['departmentName']}",
                            style: Theme.of(context)
                                .textTheme
                                .headline4
                                .copyWith(fontSize: 16.px),
                          ),
                          SizedBox(
                            height: 8.px,
                          ),
                          RichText(
                            text: TextSpan(
                                text: "批次",
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .copyWith(
                                        fontSize: 14.px,
                                        color: Color(0xFF666666)),
                                children: [
                                  WidgetSpan(
                                    child: SizedBox(
                                      width: 20.px,
                                    ),
                                  ),
                                  TextSpan(
                                      text: widget.routeModel
                                              .extension["createDate"]
                                              .toString()
                                              .substring(0, 10) ??
                                          "",
                                      style:
                                          Theme.of(context).textTheme.headline4)
                                ]),
                          ),
                          RichText(
                            text: TextSpan(
                                text: "数量",
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .copyWith(
                                        fontSize: 14.px,
                                        color: Color(0xFF666666)),
                                children: [
                                  WidgetSpan(
                                    child: SizedBox(
                                      width: 20.px,
                                    ),
                                  ),
                                  TextSpan(
                                      text: (it['amount'].toString() ?? "") +
                                          ' 吨',
                                      style:
                                          Theme.of(context).textTheme.headline4)
                                ]),
                          ),
                          RichText(
                            text: TextSpan(
                                text: "报废原因",
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .copyWith(
                                        fontSize: 14.px,
                                        color: Color(0xFF666666)),
                                children: [
                                  WidgetSpan(
                                    child: SizedBox(
                                      width: 10.px,
                                    ),
                                  ),
                                  TextSpan(
                                      text: "${it['reason'] ?? ""}",
                                      style:
                                          Theme.of(context).textTheme.headline6)
                                ]),
                          ),
                          SizedBox(
                            height: 20.px,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
            separatorBuilder: (ctx, index) {
              return Container(
                height: 1,
                color: AppTheme.backgroundColor,
              );
            }),
      );
    }
    // 车辆
    else if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
      return Expanded(
        child: ListView.separated(
            padding: EdgeInsets.only(top: 1),
            itemCount: data.length,
            itemBuilder: (ctx, index) {
              dynamic it = data[index];
              return Container(
                color: Colors.white,
                child: Row(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.fromLTRB(23.px, 15.px, 25.px, 15.px),
                      child: Image.asset(
                        "assets/images/icon_default.png",
                        width: 80.px,
                      ),
                    ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(
                            height: 18.px,
                          ),
                          Text(
                            "${it['carNum']}",
                            style: Theme.of(context)
                                .textTheme
                                .headline4
                                .copyWith(fontSize: 16.px),
                          ),
                          SizedBox(
                            height: 8.px,
                          ),
                          RichText(
                            text: TextSpan(
                                text: "标识码",
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .copyWith(
                                        fontSize: 14.px,
                                        color: Color(0xFF666666)),
                                children: [
                                  WidgetSpan(
                                    child: SizedBox(
                                      width: 20.px,
                                    ),
                                  ),
                                  TextSpan(
                                      text: it['qrCode'] ?? "",
                                      style:
                                          Theme.of(context).textTheme.headline4)
                                ]),
                          ),
                          RichText(
                            text: TextSpan(
                                text: "车辆编码",
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .copyWith(
                                        fontSize: 14.px,
                                        color: Color(0xFF666666)),
                                children: [
                                  WidgetSpan(
                                    child: SizedBox(
                                      width: 20.px,
                                    ),
                                  ),
                                  TextSpan(
                                      text: it['carNum'] ?? "",
                                      style:
                                          Theme.of(context).textTheme.headline4)
                                ]),
                          ),
                          RichText(
                            text: TextSpan(
                                text: "报废原因",
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .copyWith(
                                        fontSize: 14.px,
                                        color: Color(0xFF666666)),
                                children: [
                                  WidgetSpan(
                                    child: SizedBox(
                                      width: 10.px,
                                    ),
                                  ),
                                  TextSpan(
                                      text:
                                          "${widget.routeModel.extension["reason"]}",
                                      style:
                                          Theme.of(context).textTheme.headline6)
                                ]),
                          ),
                          SizedBox(
                            height: 20.px,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
            separatorBuilder: (ctx, index) {
              return Container(
                height: 1,
                color: AppTheme.backgroundColor,
              );
            }),
      );
    }
    // 器材
    else {
      return Expanded(
        child: ListView.separated(
            padding: EdgeInsets.only(top: 1),
            itemCount: data.length,
            itemBuilder: (ctx, index) {
              dynamic it = data[index];
              return Container(
                color: Colors.white,
                child: Row(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.fromLTRB(23.px, 15.px, 25.px, 15.px),
                      child: Image.asset(
                        "assets/images/icon_default.png",
                        width: 80.px,
                      ),
                    ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(
                            height: 18.px,
                          ),
                          Text(
                            "${it['equipName']}",
                            style: Theme.of(context)
                                .textTheme
                                .headline4
                                .copyWith(fontSize: 16.px),
                          ),
                          SizedBox(
                            height: 8.px,
                          ),
                          RichText(
                            text: TextSpan(
                                text: "标识码",
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .copyWith(
                                        fontSize: 14.px,
                                        color: Color(0xFF666666)),
                                children: [
                                  WidgetSpan(
                                    child: SizedBox(
                                      width: 20.px,
                                    ),
                                  ),
                                  TextSpan(
                                      text: it['qrCode'] ?? "",
                                      style:
                                          Theme.of(context).textTheme.headline4)
                                ]),
                          ),
                          RichText(
                            text: TextSpan(
                                text: "报废原因",
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .copyWith(
                                        fontSize: 14.px,
                                        color: Color(0xFF666666)),
                                children: [
                                  WidgetSpan(
                                    child: SizedBox(
                                      width: 10.px,
                                    ),
                                  ),
                                  TextSpan(
                                      text:
                                          "${widget.routeModel.extension["reason"] ?? ""}",
                                      style:
                                          Theme.of(context).textTheme.headline6)
                                ]),
                          ),
                          SizedBox(
                            height: 20.px,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
            separatorBuilder: (ctx, index) {
              return Container(
                height: 1,
                color: AppTheme.backgroundColor,
              );
            }),
      );
    }
  }

  // 点击报废
  Future clickScrap(BuildContext context, String asd) async {
    //await uploadImage(context);
    if (data.length == 0) {
      FlutterToast.toastCenter("数据为空!");
      return;
    }

    // showDialog(context: context,builder: (ctx){
    //   return LoadingDialog(
    //     barrierDismissible: true,
    //   );
    // });
    //
    // String att = imageUrls.join(",");
    // final scrapId = widget.routeModel.extension["id"];
    String type = '15';
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      type = '34';
    } else if (category ==
        RouteCategoryFrontComponentConst.fireFightingVehicle) {
      type = '26';
    } else {
      type = '15';
    }

    final params = {
      "parame": json.encode(data),
      "scrapId": '',
      "imageUrls": json.encode(imageUrls),
      "reason": widget.routeModel.extension["reason"],
      "createDate": widget.routeModel.extension["createDate"],
      // "equipmentDetailId":
    };
    getScrapPostBill(params, type).then((value) {
      if (value) {
        final param = {
          "title": widget.routeModel.title,
          "category": category,
          "item": item,
          //  "extension":json.encode({"list":_addItems})
        };
        if (asd == '1') {
          Application.navigateToPath(context, Routes.offlineSubmitSuccess,
              params: param);
        } else {
          Navigator.of(context).popUntil((route) =>
              route.settings.name.startsWith(Routes.offlineCreateScrap));
        }
      }
    });
    // HttpRequest.scrapExec(params:params).then((res){
    //   Navigator.of(context).pop();
    //   if(res["status"] == 200) {
    //
    //     final params = {
    //       "category":category,
    //       "item":item,
    //       "title":widget.routeModel.title,
    //       "extension":json.encode(res["result"])
    //     };
    //     Application.navigateToPath(context, Routes.offlineSubmitSuccess,params: params);
    //   }
    // }).catchError((err){
    //    Navigator.of(context).pop();
    // });
  }
}
