import 'dart:convert';
import 'dart:ui';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.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/request.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:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:amos_iot_login_tpl/const/global_config.dart';

import '../../model/scrap_bill_model.dart';
import '../../routes/routes.dart';

GlobalKey<_CreateScrapContentState> childkey = GlobalKey();

///新建报废
///装备页面入口
class CreateScrap extends StatelessWidget {
  RouteModel routeModel;
  PlatformMenu platformMenu;

  ///修改时间：2021年10月13日14:23:14
  ///将RouteModel参数转化成GexX的arguments
  CreateScrap({this.routeModel}) {
    platformMenu = Get.arguments;
    if (routeModel == null && platformMenu != null) {
      routeModel = RouteModel(
          category: platformMenu.parentFrontComponent ?? '',
          title: platformMenu.permissionName,
          item: platformMenu.frontComponent);
    }
  }

  @override
  Widget build(BuildContext context) {
    return CreateScrapContent(routeModel);
  }
}

class CreateScrapContent extends StatefulWidget {
  final RouteModel routeModel;

  const CreateScrapContent(this.routeModel);

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

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

  List<ScrapBillModel> data = [];
  bool isEmpty = false;
  int _currentPage = 1;
  int _total = 1;
  final EasyRefreshController _controller = EasyRefreshController();
  String theme = '';
  String imageUrl = '';

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

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

    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
    initThemeConfig();
    getScrapList();
  }

  // 获取最新数据
  void getScrapList() {
    // 灭火药剂
    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 = int.parse(res['result']['pages']);
            for (final json in items) {
              models.add(ScrapBillModel.fromJson(json));
            }
            if (items.isNotEmpty) {
              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 = int.parse(res['result']['pages']);
            List<ScrapBillModel> models = [];
            for (final json in items) {
              models.add(ScrapBillModel.fromJson(json));
            }
            if (items.isNotEmpty) {
              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 = int.parse(res['result']['pages']);
          List<ScrapBillModel> models = [];
          for (final json in items) {
            models.add(ScrapBillModel.fromJson(json));
          }
          if (items.isNotEmpty) {
            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 (final 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 (final 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: const TextStyle(color: Colors.white),
          ),
          centerTitle: true,
          leading: LeadingButton(
            theme: theme,
          ),
        ),
        body: Stack(
          children: <Widget>[buildEquipList(context), buildBottom(context)],
        ));
  }

  Widget buildBottom(context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Row(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0),
              child: RaisedButton(
                color: Theme.of(context).primaryColor,
                child: const Text(
                  '新建报废',
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () => onTap(context),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildEquipList(context) {
    if (isEmpty) {
      return const Center(
        child: Text('当前数据为空'),
      );
    } else if (data.isEmpty) {
      return const Center(
        child: CupertinoActivityIndicator(),
      );
    } else {
      return EasyRefresh(
        controller: _controller,
        footer: MaterialFooter(),
        header: MaterialHeader(),
        onRefresh: () async {
          _currentPage = 1;
          _total = 1;
          _controller.finishLoad(noMore: false);
          getScrapList();
        },
        onLoad: () async {
          if (_currentPage >= _total) {
            _controller.finishLoad(noMore: true);
            return Future.value(false);
          }
          getMoreScrapList();
        },
        child: ListView.builder(
            padding: EdgeInsets.only(bottom: 10.px, left: 10.px, right: 10.px, top: 5.px),
            itemCount: data.length,
            itemBuilder: (ctx, index) {
              return AddDetailCard(
                  theme: theme,
                  model: data[index],
                  routeModel: widget.routeModel,
                  imageUrl:imageUrl,
                  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.fireAgentInStock, 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.equipWareHousing, 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.equipWareHousing, params: params).then((value) {
          getScrapList();
        });
      }
    }
  }
}

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

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

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: const Color(0xFF455b63).withOpacity(0.08),
      child: Row(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(15.px, 15.px, 18.px, 15.px),
            child: Image.network(
              imageUrl + (model?.img ?? 'assets/images/equip_cap.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: Colors.black),
                      children: [
                        ...model.billCode.runes.map((rune) {
                          return WidgetSpan(
                              child: Text(
                            String.fromCharCode(rune),
                          ));
                        }),
                      ]),
                ),
                SizedBox(
                  height: 5.px,
                ),
                const Text(
                  '待报废',
                ),
                SizedBox(
                  height: 1.px,
                ),
                Text(
                  '数量:   ${model.detailCount}',
                ),
                SizedBox(
                  height: 8.px,
                ),
                Text(
                  '${model.createDate}',
                ),
                SizedBox(
                  height: 20.px,
                ),
              ],
            ),
          ),
          InkWell(
            onTap: () => addScrap(context, model),
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 20.px, horizontal: 20.px),
              child: Column(
                children: const <Widget>[
                  Text(
                    '报',
                  ),
                  Text(
                    '废',
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  /// 点击报废
  void addScrap(BuildContext context, ScrapBillModel model) {
    final result = {'billCode': model.billCode, 'id': model.id};
    final params = {
      'title': routeModel.title,
      'category': routeModel.category,
      'item': routeModel.item,
      'extension': json.encode(result)
    };

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