import 'package:base/consts/color.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_nfc_tools/flutter_nfc_tools.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/offline_plan_list_output.dart';
import '../../services/offline_plan_inspection_services.dart';
import '../../view/CheckExecute/checkexec_inspection.dart';
import '../../view/plan_inspection/offline_qr_page.dart';
import '../../view/plan_inspection/qr_page_new.dart';

class OfflinePlanListContent extends StatefulWidget {
  final OfflinePlanListOutput planListOutput;

  const OfflinePlanListContent(this.planListOutput);

  @override
  State<StatefulWidget> createState() => _OfflinePlanListContent(planListOutput);
}

class _OfflinePlanListContent extends State<OfflinePlanListContent> with AutomaticKeepAliveClientMixin {
  OfflinePlanListOutput planListOutput;

  // 构造方法
  _OfflinePlanListContent(this.planListOutput);

  @override
  bool get wantKeepAlive => true;

  bool isAnimating = false;

  final EasyRefreshController _controllers = EasyRefreshController();
  OfflinePlanListOutput initData;

  Future<void> initPlatformState() async {
    try {
      FlutterNfcTools.ndefEventsStream.listen((m) {
        if (m['ndefMessage'] == null) {
          shortMessage(
            '标签无内容',
          );
          return;
        }

        print(m['ndefMessage'][0]['payload']);

        List<int> payload = m['ndefMessage'][0]['payload'].sublist(3).cast<int>().toList();
        String content = FlutterNfcTools.bytesToString(payload);
        if (content.isNotEmpty) {
          getContent(content);
        } else {
          shortMessage(
            '标签内容无法识别！',
          );
        }
      });
    } on PlatformException {
      shortMessage(
        '内容读取失败！',
      );
    }

    if (!mounted) return;
  }

  String theme = '';

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

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

    initPlatformState();
    loadData();
    initThemeConfig();
  }

  void loadData() async {
    setState(() {
      isAnimating = true;
    });
    await getOfflinePlanListOutputById(planListOutput.planTaskId).then((data) {
      setState(() {
        initData = data;
        isAnimating = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (initData == null) {
      return Scaffold(
          appBar: AppBar(
        title: const Text(
          "",
          style: TextStyle(color: Colors.black, fontSize: 19),
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
        backgroundColor: KColorConstant.topBarColor,
        leading: Container(
          child: GestureDetector(
            onTap: () => Navigator.pop(context),
            child: Icon(Icons.keyboard_arrow_left, color: GetConfig.getColor(theme), size: 32),
          ),
        ),
      ));
    }
    return Scaffold(
        appBar: AppBar(
          title: Text(
            initData.taskName ?? '',
            style: const TextStyle(color: Colors.black, fontSize: 19),
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
          backgroundColor: KColorConstant.topBarColor,
          leading: Container(
            child: GestureDetector(
              onTap: () => Navigator.pop(context),
              child: Icon(Icons.keyboard_arrow_left, color: GetConfig.getColor(theme), size: 32),
            ),
          ),
          actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.crop_free,
                color: GetConfig.getColor(theme),
              ),
              onPressed: () {
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return
                    NewQrPage(
                      planTaskId: initData.planTaskId,
                    );
                })).then((result) {
                  loadData();
                });
              },
            ),
            IconButton(
              icon: Icon(
                Icons.autorenew,
                color: GetConfig.getColor(theme),
              ),
              onPressed: () {
                loadData();
              },
            )
          ],
        ),
        body: ModalProgressHUD(
          child: Container(
            child: Column(
              children: <Widget>[
                Expanded(
                  child: Container(
                      width: 300,
                      child: Stack(
                        children: <Widget>[
                          charts.PieChart(_createSampleData(initData),
                              animate: false,
                              defaultRenderer: charts.ArcRendererConfig(
                                  arcWidth: 20, arcRendererDecorators: [charts.ArcLabelDecorator()])),
                          Positioned(
                            top: 70,
                            left: 120,
                            child: Column(
                              children: <Widget>[
                                Text(
                                  initData.taskPlanNum.toString(),
                                  style: const TextStyle(fontSize: 18),
                                ),
                                const Text("计划巡检")
                              ],
                            ),
                          )
                        ],
                      )),
                  flex: 2,
                ),
                Expanded(
                    child: Container(
                        padding: const EdgeInsets.only(left: 10, right: 10, top: 20),
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Text(
                                  "计划状态：" + getStatus(initData.finishStatus),
                                  style: TextStyle(color: getBgColor(initData.finishStatus)),
                                ),
                                const Padding(
                                  padding: EdgeInsets.only(left: 50),
                                ),
                                const Text("按序巡检：", style: TextStyle(color: Colors.grey)),
                                Text(initData.inOrder == "0" ? "否" : "是", style: TextStyle(color: Colors.grey)),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  '时间：' + initData.beginTime + " - " + initData.endTime,
                                  style: TextStyle(color: Colors.grey),
                                ),
                              ],
                            )
                          ],
                        )),
                    flex: 1),
                Expanded(
                  child: EasyRefresh(
                    enableControlFinishRefresh: false,
                    enableControlFinishLoad: true,
                    controller: _controllers,
                    footer: MaterialFooter(),
                    header: MaterialHeader(),
                    child: ListView.builder(
                      //ListView的Item
                      itemCount: initData.points.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Container(
                            height: 70.0,
                            margin: const EdgeInsets.only(left: 10, right: 10),
                            child: GestureDetector(
                              child: Card(
                                  elevation: 0.2,
                                  child: Row(
                                    children: <Widget>[
                                      Container(
                                        width: 7,
                                        height: 110,
                                        decoration: BoxDecoration(
                                            borderRadius: const BorderRadius.only(
                                                topLeft: Radius.circular(4), bottomLeft: Radius.circular(4)),
                                            color: getPointColor(initData.points[index].status)),
                                      ),
                                      Container(
                                        padding: const EdgeInsets.only(left: 10, top: 5),
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(
                                              initData.points[index].name,
                                              style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
                                            ),
                                            const Padding(
                                              padding: EdgeInsets.only(top: 5),
                                            ),
                                            Row(
                                              children: <Widget>[
                                                Text('编号:' + initData.points[index].pointNO),
                                                const Padding(
                                                  padding: EdgeInsets.only(left: 36),
                                                ),
                                                Text(
                                                  getPointStatus(initData.points[index].status),
                                                  style: TextStyle(color: getPointColor(initData.points[index].status)),
                                                )
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  )),
                              onTap: () {
                                if (initData.points[index].isFixed == "1") {
                                } else {
                                  // 直接去填写页面
                                  if (initData.points[index].status == "0") {
                                    Navigator.push(context, MaterialPageRoute(builder: (context) {
                                      return CheckExecInspection(initData.points[index], null);
                                    })).then((v) {
                                      loadData();
                                    });
                                  } else {}
                                }
                              },
                            ));
                      },
                    ),
                  ),
                  flex: 4,
                ),
              ],
            ),
          ),
          inAsyncCall: false,
          // demo of some additional parameters
          opacity: 0.7,
          progressIndicator: CircularProgressIndicator(),
        ));
  }

  List<charts.Series<LinearSales, String>> _createSampleData(OfflinePlanListOutput initData) {
    int uncheck = initData.taskPlanNum - initData.finshNum;

    int checked = initData.finshNum;

    var data = [
      LinearSales("未巡检", uncheck, charts.MaterialPalette.gray.shadeDefault),
      LinearSales("已巡检", checked, charts.MaterialPalette.green.shadeDefault),
    ];
    return [
      charts.Series<LinearSales, String>(
        id: 'Sales',
        colorFn: (LinearSales data, _) => data.color,
        domainFn: (LinearSales data, _) => data.year,
        measureFn: (LinearSales data, _) => data.sales,
        data: data,
        // Set a label accessor to control the text of the arc label.
        labelAccessorFn: (LinearSales row, _) => '${row.year}: ${row.sales}',
      )
    ];
  }

  Color getBgColor(int finishStatus) {
    if (finishStatus == 0) {
      // 未开始
      return Colors.grey;
    } else if (finishStatus == 1) {
      // 进行中
      return Colors.orange;
    } else if (finishStatus == 2) {
      // 已结束
      return Colors.red[800];
    } else if (finishStatus == 3) {
      // 已超时
      return Colors.redAccent;
    } else {
      return Colors.white;
    }
  }

  String getStatus(int finishStatus) {
    if (finishStatus == 0) {
      // 未完成
      return "未执行";
    } else if (finishStatus == 1) {
      // 进行中
      return "执行中";
    } else if (finishStatus == 2) {
      // 未开始
      return "已执行";
    } else if (finishStatus == 3) {
      // 已超时
      return "已超时";
    } else {
      return '';
    }
  }

  Color getPointColor(String pointStatus) {
    if (pointStatus == "0") {
      return Colors.grey;
    } else if (pointStatus == "1") {
      return Colors.green;
    } else {
      return Colors.white;
    }
  }

  String getPointStatus(String pointStatus) {
    if (pointStatus == "0") {
      return "未巡检";
    } else if (pointStatus == "1") {
      return "已巡检";
    } else {
      return "";
    }
  }

  Future<void> getContent(String pointNo) async {
    // 获取点信息
    Point chkPoint;
    for (var point in initData.points) {
      if (point.pointNO == pointNo) {
        chkPoint = point;
        break;
      }
    }

    if (chkPoint == null) {
      shortMessage(
        '没有对应的巡检点！',
      ).then((v) {
        return;
      });
      return;
    }

    // 已巡检
    if (chkPoint.status == "1") {
      shortMessage(
        '当前点已提交巡检记录！',
      ).then((v) {
        return;
      });
      return;
    }

    if (initData.inOrder == "1") {
      num lastOrder = chkPoint.orderNo - 1;
      if (lastOrder < 1) {
        // 本次扫描的点就是第一个点
      } else {
        Point _lastPoint;
        for (var _point in initData.points) {
          if (_point.orderNo == lastOrder) {
            _lastPoint = _point;
            break;
          }
        }

        // check data
        if (_lastPoint.status == '1') {
          // 已完成 ok
        } else {
          shortMessage('此巡检为按序巡检,请按顺序进行巡检任务！').then((v) {
            return;
          });
          return;
        }
      }
    }

    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return CheckExecInspection(chkPoint, "NFC");
    })).then((v) {
      // 刷新页面数据
      loadData();
    });
  }
}

class LinearSales {
  final String year;
  final int sales;
  final charts.Color color;

  LinearSales(this.year, this.sales, this.color);
}
