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/external_assets_package_key.dart';
import 'package:base/consts/http_config.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/utils/request.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/loading_dialog.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:http_parser/http_parser.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../model/scrap_detail_list_model.dart';
import '../model/scrap_vehicle_detail_list_model.dart';
import '../routes/routes.dart';

GlobalKey<_ScrapPostBillContentState> childKey = GlobalKey();

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

  const ScrapPostBill({this.routeModel});

  @override
  Widget build(BuildContext context) {
    return ScrapPostBillContent(
      routeModel: routeModel,
    );
  }
}

class ScrapPostBillContent extends StatefulWidget {
  final RouteModel routeModel;

  const ScrapPostBillContent({this.routeModel});

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

class _ScrapPostBillContentState extends State<ScrapPostBillContent> {
  List<Asset> images = [];
  List<dynamic> data = [];
  List<String> imageUrls = [];
  bool isEmpty = false;
  String category;
  String item;
  String theme = '';

  @override
  void initState() {
    super.initState();
    category = widget.routeModel.category;
    item = widget.routeModel.item;
    getScrapDetailList();
    initThemeConfig();
  }

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

  // 获取报废列表
  void getScrapDetailList() {
    final scrapId = widget.routeModel.extension['id'];
    if (scrapId == null) return;
    final scrap = {
      'scrapId': scrapId,
    };
    final params = {
      'pageNum': 0,
      //'scrapDetail':scrap,
      'scrapId': scrapId,
      'pageSize': HttpConfig.pageSize
    };
    HttpRequest.scrapDetailList(params: params).then((res) {
      if (res['status'] == 200) {
        List records = res['result']['records'];
        List items = [];
        if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
          for (final json in records) {
            items.add(ScrapDetailListModel.fromJson(json));
          }
        } else if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
          for (final json in records) {
            items.add(ScrapVehicleDetailListModel.fromJson(json));
          }
        } else if (category == RouteCategoryFrontComponentConst.equipment) {
          for (final json in records) {
            items.add(ScrapDetailListModel.fromJson(json));
          }
        }
        if (items.isNotEmpty) {
          setState(() {
            data = items;
          });
        } else {
          setState(() {
            isEmpty = true;
          });
        }
      }
    }).catchError((err) {
      print(err);
      Navigator.of(context).pop();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            widget.routeModel?.title,
          ),
          centerTitle: true,
          leading: LeadingButton(
            theme: 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: Stack(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(bottom: 50.px),
                  child: Column(
                    children: <Widget>[buildTitleAndImage(context), buildBillList(context)],
                  ),
                ),
                buildBottom(context)
              ],
            )));
  }

  /// 标题和头部
  Widget buildTitleAndImage(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          width: double.infinity,
          color: Colors.white,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.px, vertical: 12.px),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _buildRow('单据类型：', '待报废单据'),
                _buildRow('单据编号：', widget.routeModel.extension['billCode'] ?? ''),
                const SizedBox(
                  height: 10,
                ),
                _buildRow('添加凭据：', ''),
              ],
            ),
          ),
        ),
        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.isNotEmpty) {
                  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 = <Asset>[];
              try {
                resultList = await MultiImagePicker.pickImages(
                  maxImages: 3,
                  enableCamera: true,
                  selectedAssets: images,
                  cupertinoOptions: const CupertinoOptions(takePhotoIcon: 'chat'),
                  materialOptions: const MaterialOptions(
                    actionBarColor: '#abcdef',
                    allViewTitle: '所有图片',
                    useDetailsView: false,
                    selectCircleStrokeColor: '#000000',
                  ),
                );
                setState(() {
                  images = resultList;
                });
                // 上传图片
                uploadImage(context);
              } on Exception catch (e) {
                AmosToast.show(e.toString(), context);
              }
            },
            child: Image.asset(
              'assets/images/icon_image_placeholder.png',
              package: ExternalAssetsPackageKey.BASE,
              width: 60.px,
              height: 60.px,
            )));
  }

  /// 上传图片
  Future<void> uploadImage(context) async {
    showDialog(
        context: context,
        builder: (ctx) {
          return LoadingDialog(
            barrierDismissible: true,
          );
        });
    bool uoloadSucess = true;
    for (int i = 0; i < images.length; 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});
      // 使用 dio 上传图片
      var response = await HttpRequest.uploadImage(data: formData);
      if (response['status'] == 200) {
        imageUrls.add(response['result']['url']);
      } else {
        uoloadSucess = false;
        break;
      }
    }

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

  /// 底部按钮
  Widget buildBottom(context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 50.px,
        width: double.infinity,
        child: RaisedButton(
          color: Theme.of(context).primaryColor,
          child: const Text(
            '报废',
            style: TextStyle(color: Colors.white),
          ),
          onPressed: () => clickScrap(context),
        ),
      ),
    );
  }

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

  Widget getListViewContent() {
    // 灭火药剂
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      return Expanded(
        child: ListView.separated(
            padding: const EdgeInsets.only(top: 1),
            itemCount: data.length,
            itemBuilder: (ctx, index) {
              ScrapDetailListModel it = data[index];
              return Container(
                color: Colors.white,
                height: 200,
                padding: const EdgeInsets.all(10),
                child: Column(
                  children: <Widget>[
                    it.img != null
                        ? Image.network(
                            it.img,
                            width: 80.px,
                          )
                        : Image.asset(
                            'assets/images/icon_default.png',
                            package: ExternalAssetsPackageKey.BASE,
                            width: 80.px,
                          ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(
                            height: 18.px,
                          ),
                          _buildRow(it.stockDetail.equipmentDetail.name, ''),
                          _buildRow(
                              '批次：',
                              (it.createDate != null || it.createDate != 'null')
                                  ? it.createDate.toString().substring(0, 10)
                                  : ''),
                          _buildRow('数量：', it.amount.toString()),
                          _buildRow('报废原因：', it.reason ?? '无'),
                          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: const EdgeInsets.only(top: 1),
            itemCount: data.length,
            itemBuilder: (ctx, index) {
              ScrapVehicleDetailListModel it = data[index];
              return Container(
                color: Colors.white,
                height: 200,
                padding: const EdgeInsets.all(10),
                child: Column(
                  children: <Widget>[
                    it.img != null
                        ? Image.network(
                            it.img,
                            width: 80.px,
                          )
                        : Image.asset(
                            'assets/images/icon_default.png',
                            package: ExternalAssetsPackageKey.BASE,
                            width: 80.px,
                          ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          _buildRow(it.car.carNum, ''),
                          _buildRow('标  识  码：', it.car.qrCode),
                          _buildRow('车辆编码：', it.car.carNum),
                          _buildRow('报废原因：', it.reason ?? '无'),
                          SizedBox(
                            height: 20.px,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
            separatorBuilder: (ctx, index) {
              return Container(
                height: 1,
                color: AppTheme.backgroundColor,
              );
            }),
      );
    }
    // 器材
    else {
      return Expanded(
        child: ListView.separated(
            padding: const EdgeInsets.only(top: 1),
            itemCount: data.length,
            itemBuilder: (ctx, index) {
              ScrapDetailListModel it = data[index];
              return Container(
                color: Colors.white,
                height: 200,
                padding: const EdgeInsets.all(10),
                child: Column(
                  children: <Widget>[
                    it.img != null
                        ? Image.network(
                            it.img,
                            width: 80.px,
                          )
                        : Image.asset(
                            'assets/images/icon_default.png',
                            package: ExternalAssetsPackageKey.BASE,
                            width: 80.px,
                          ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(
                            height: 18.px,
                          ),
                          _buildRow(it.stockDetail.equipmentDetail.name, ''),
                          _buildRow('标  识  码：', it.stockDetail.qrCode),
                          _buildRow('报废原因：', it.reason),
                          SizedBox(
                            height: 20.px,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
            separatorBuilder: (ctx, index) {
              return Container(
                height: 1,
                color: AppTheme.backgroundColor,
              );
            }),
      );
    }
  }

  Row _buildRow(String title, String value) {
    return Row(
      children: [
        Text(title, style: TextStyle(fontSize: 14.px, color: const Color(0xFF666666))),
        Expanded(
          flex: 3,
          child: Text(
            value ?? '',
            style: TextStyle(fontSize: 14.px, color: const Color(0xFF666666)),
          ),
        ),
      ],
    );
  }

  /// 点击报废
  void clickScrap(BuildContext context) {
    if (data.isEmpty) {
      FlutterToast.toastCenter('数据为空!');
      return;
    }
    if (imageUrls.isEmpty) {
      FlutterToast.toastCenter('请上传凭证!');
      return;
    }
    showDialog(
        context: context,
        builder: (ctx) {
          return LoadingDialog(
            barrierDismissible: true,
          );
        });
    String att = imageUrls.join(',');
    final scrapId = widget.routeModel.extension['id'];
    final params = {'id': scrapId, 'attachment': att};
    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.submitSuccess, params: params);
      }
    }).catchError((err) {
      Navigator.of(context).pop();
    });
  }
}
