import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:base/consts/color.dart';
import 'package:base/model/LoginResult.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:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/plan_inspection/check_point_detail.dart';
import '../../model/plan_inspection/plan_task_detail.dart';
import '../../services/no_plan_inspection.dart';
import '../../services/plan_inspection_services.dart';
import '../../view/CheckExecute/navigation_checkexec.dart';
import '../../view/plan_inspection/plan_list_content_detail.dart';
import 'qr_page_new.dart';

class PlanListContent extends StatefulWidget {
  final num planTaskId;
  final arguments;

  const PlanListContent(this.planTaskId,{this.arguments});

  @override
  State<StatefulWidget> createState() => _PlanListContent(planTaskId);
}

class _PlanListContent extends State<PlanListContent> with AutomaticKeepAliveClientMixin {
  num planTaskId;

  _PlanListContent(this.planTaskId);

  @override
  bool get wantKeepAlive => true;
  bool isAnimating = false;
  final EasyRefreshController _controllers = EasyRefreshController();
  PlanTaskDetail initData;
  String theme = '';
  LoginResult loginResult;
  bool hasOperationPermission = false;
  bool hasFixedPoint = false;
  CheckPointDetail pointDetail;

  Future<void> initPlatformState() async {
    try {
      FlutterNfcTools.ndefEventsStream.listen((m) {
        if (m['ndefMessage'] == null) {
          shortMessage('标签无内容');
          return;
        }
        List<int> payload = m['ndefMessage'][0]['payload'].sublist(3).cast<int>().toList();
        String content = FlutterNfcTools.bytesToString(payload);
        if (content.isNotEmpty) {
          if (initData.finishStatus == 1) {
            getNfcContent(content);
          }
        } else {
          shortMessage('标签内容无法识别！');
        }
      });
    } on PlatformException {
      shortMessage('内容读取失败！');
    }
  }

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

  Future<void> initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      String str = preferences.get('LoginResult');
      setState(() {
        loginResult = LoginResult(str);
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    }).then((f) {
      loadData();
    });
  }

  Future<void> loadData() async {
    setState(() {
      isAnimating = true;
    });
    //接收传递的参数
    var args = ModalRoute.of(context).settings.arguments;
    await queryPlanTaskById(planTaskId==0 ? args : planTaskId).then((data) {
      if (data.message != null && data.message.isNotEmpty) {
        MsgBox.showMessageAndExitCurrentPage(data.message, true, context);
        return;
      }
      setState(() {
        initData = data;
        isAnimating = false;
        //20190926根据毛工要求去掉判断
//        hasOperationPermission = loginResult.user.id == initData.userId;
        hasOperationPermission = true;

        if (initData.points != null && initData.points.isNotEmpty) {
          hasFixedPoint = initData.points.where((f) => f.isFixed == '1').isNotEmpty;
        }
      });
      if (hasOperationPermission && hasFixedPoint) {
        initPlatformState();
      }
    }).then((v) {
      // 进行中的任务进行提示
      if (initData.finishStatus == 1 && hasOperationPermission && hasFixedPoint) {
        longMessage('请您靠近标签或扫码！', textColor: Colors.white, backgroundColor: Colors.red);
      }
      if (initData.finishStatus == 1 && !hasOperationPermission) {
        longMessage('非本人计划不能进行巡检！', textColor: Colors.white, backgroundColor: Colors.red);
      }
    });
  }

  Future<void> getDetailData(int pointId) async {
    await queryPointPlanTaskDetail(widget.planTaskId, pointId).then((data) {
      if (data.message != null && data.message.isNotEmpty) {
        MsgBox.showMessageAndExitCurrentPage(data.message, true, context);
        return;
      }
      setState(() {
        pointDetail = data;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    if (initData == null) {
      return Scaffold(
          appBar: AppBar(
        title: const Text(''),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ));
    }
    return Scaffold(
        appBar: AppBar(
          title: Text(
            initData.taskName ?? '',
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
          actions: <Widget>[
            initData.finishStatus == 1 /*&& hasOperationPermission && hasFixedPoint*/
                ? IconButton(
                    icon: const Icon(
                      Icons.crop_free,
                    ),
                    onPressed: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return NewQrPage(planTaskId: planTaskId);
                      })).then((v) {
                        // 刷新页面
                        loadData();
                      });
                    },
                  )
                : Container(),
            IconButton(
              icon: const Icon(
                Icons.autorenew,
              ),
              onPressed: () {
                loadData();
              },
            )
          ],
        ),
        body: ModalProgressHUD(
          child: Container(
            child: Column(
              children: <Widget>[
                Expanded(
                  child: Container(
                      width: 400,
                      child: Stack(
                        children: <Widget>[
                          charts.PieChart(_createSampleData(initData),
                              animate: false,
                              defaultRenderer:
                                  charts.ArcRendererConfig(arcWidth: 20, arcRendererDecorators: [charts.ArcLabelDecorator()])),
                          Container(
                            padding: const EdgeInsets.only(top: 60),
                            child: Column(
                              children: <Widget>[
                                Text(
                                  initData.taskPlanNum.toString(),
                                  style: const TextStyle(fontSize: 18),
                                ),
                                const Text('计划巡检')
                              ],
                            ),
                            alignment: Alignment.center,
                          )
                        ],
                      )),
                  flex: 2,
                ),
                Expanded(
                    child: Container(
                        padding: const EdgeInsets.only(left: 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: const TextStyle(color: Colors.grey)),
                              ],
                            ),
                            Container(
                              child: Row(
                                children: <Widget>[
                                  Text(
                                    '时间:' + initData.beginTime + ' - ' + initData.endTime,
                                    style: const 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>[
                                            Container(
                                              width: MediaQuery.of(context).size.width - 70,
                                              child: Text(
                                                initData.points[index].name,
                                                style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                            ),
                                            const Padding(
                                              padding: EdgeInsets.only(top: 5),
                                            ),
                                            Container(
                                              width: 280,
                                              child: 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)),
                                                  )
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Icon(
                                        Icons.keyboard_arrow_right,
                                        color: Theme.of(context).primaryColor,
                                      )
                                    ],
                                  )),
                              onTap: () {
                                if (hasOperationPermission) {
                                  if (initData.points[index].isFixed == '1') {
                                    Navigator.push(context, MaterialPageRoute(builder: (context) {
                                      return PlanListContentDetail(planTaskId, initData.points[index].pointId);
                                    })).then((v) {
                                      loadData();
                                    });
                                  } else {
                                    // 直接去填写页面
                                    if (initData.points[index].status == '0') {
                                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                                        return NavigationCheckExec(initData.points[index].pointId,
                                            pointName: initData.points[index].name, planId: planTaskId);
                                      })).then((v) {
                                        loadData();
                                      });
                                    } else {
                                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                                        return PlanListContentDetail(planTaskId, initData.points[index].pointId);
                                      }));
                                    }
                                  }
                                }
                              },
                            ));
                      },
                    ),
                  ),
                  flex: 4,
                ),
              ],
            ),
          ),
          inAsyncCall: isAnimating,
          // demo of some additional parameters
          opacity: 0.7,
          progressIndicator: const CircularProgressIndicator(),
        ));
  }

  List<charts.Series<LinearSales, String>> _createSampleData(PlanTaskDetail initData) {
    List<LinearSales> data = [];
    if (initData.taskPlanNum == 0) {
      data.add(LinearSales('', -1, charts.MaterialPalette.gray.shadeDefault));
    } else {
      if (initData.unqualified > 0) {
        data.add(LinearSales('不合格', initData.unqualified, charts.MaterialPalette.red.shadeDefault));
      }
      if (initData.omission > 0) {
        data.add(LinearSales('漏检', initData.omission, charts.MaterialPalette.yellow.shadeDefault));
      }
      if (initData.finshNum > 0) {
        data.add(LinearSales('合格', initData.finshNum, charts.MaterialPalette.green.shadeDefault));
      }
      if (initData.unplan > 0) {
        data.add(LinearSales('未开始', initData.unplan, charts.MaterialPalette.gray.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,
        labelAccessorFn: (LinearSales row, _) => row.sales == -1 ? '' : '${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 if (pointStatus == '2') {
      return Colors.red;
    } else if (pointStatus == '3') {
      return Colors.yellow;
    } else {
      return Colors.white;
    }
  }

  String getPointStatus(String pointStatus) {
    if (pointStatus == '0') {
      return '未开始';
    } else if (pointStatus == '1') {
      return '合格';
    } else if (pointStatus == '2') {
      return '不合格';
    } else if (pointStatus == '3') {
      return '漏检';
    } else {
      return '';
    }
  }

  Future<void> getNfcContent(String no) async {
    // check点的合法性
    int pointNum = initData.points.where((f) => f.pointNO == no).toList().length;
    if (pointNum <= 0) {
      shortMessage('此点非巡检计划中的点，请确认后重新执行！').then((v) {
        return;
      });
      return;
    }

    await getQueryPlanTaskBySerialInfo(2, no, initData.planTaskId).then((data) {
      // 跳转页面
      if (data != null && data.success) {
        Point _execPoint;
        for (final _point in initData.points) {
          if (_point.pointId == data.id) {
            _execPoint = _point;
            break;
          }
        }

        if (null == _execPoint) {
          shortMessage('此点非巡检计划中的点，请确认后重新执行！');
          return;
        }

        // 检查点是否已经巡检过
        bool hasChecked = false;
        if (_execPoint != null && _execPoint.finish != 0) {
          hasChecked = true;
        }
        if (hasChecked) {
          shortMessage('该巡检点已经进行过巡检！');
        } else {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return NavigationCheckExec(data.id, planId: planTaskId, pointName: _execPoint.name, checkMode: 'NFC');
          })).then((v) {
            // 刷新页面
            loadData();
          });
        }
      } else {
        shortMessage(data.message);
      }
    });
  }
}

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

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