import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

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

///@Description     兼容海康手持机的新版二维码扫描页面
///@author          helinlin
///@create          2022-05-23 16:56

class NewQrPage extends StatefulWidget {
  final num planTaskId;

  const NewQrPage({Key key, this.planTaskId}) : super(key: key);

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

class _NewQrPageState extends State<NewQrPage> {
  MethodChannel methodChannel;
  List<Point> points;

  @override
  void initState() {
    super.initState();
    loadData();
    methodChannel = const MethodChannel('amosMethodChannel');
    checkPermission();
  }

  /// 检查权限
  Future<void> checkPermission() async {
    bool hasPermission = await Permission.camera.isGranted;
    if (!hasPermission) {
      bool hasPermission = await Permission.camera.request().isGranted;
      if (!hasPermission) {
        MsgBox.showMessageOnly('请授予权限后重新操作！', context);
      } else {
        scan();
      }
    } else {
      scan();
    }
  }

  ///扫码
  Future<void> scan() async {
    String result = await methodChannel.invokeMethod('scan');
    if (result != null && result.isNotEmpty) {
      if(result.contains('\r')) {
        result = result.replaceAll('\r', '');
      }
      getContent(result);
    } else {
      Navigator.pop(context);
    }
  }

  void loadData () async{
    await getOfflinePlanListOutputById(this.widget.planTaskId).then((data){
      setState(() {
        points = data.points;
      });
    });
  }

  Future<void> getContent(String no) async {
    Point chkPoint;
    for(var point in this.points){
      if(point.pointNO == no){
        chkPoint = point;
        break;
      }
    }
    if(chkPoint==null){
        shortMessage('此点非巡检计划中的点，请确认后重新执行！').then((v) {
          scan();
        });
        return;
    }

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

    print(chkPoint);

    Navigator.push( context,
        new MaterialPageRoute(builder: (context) {
          return CheckExecInspection(chkPoint,"QR");
        })).then((v) {
          Navigator.pop(context);
        });

    // 校验是否按顺序巡检
    // if(this.widget.inOrder == "1"){
    //   num lastOrder = chkPoint.orderNo - 1;
    //   if(lastOrder < 1){
    //     // 本次扫描的点就是第一个点
    //   }else{
    //     Point _lastPoint;
    //     for(var _point in this.points){
    //       if(_point.orderNo == lastOrder){
    //         _lastPoint = _point;
    //         break;
    //       }
    //     }
    //
    //     // check data
    //     if(_lastPoint.status == '1'){
    //       // 已完成 ok
    //     }else{
    //       Fluttertoast.showToast(
    //         msg: '此巡检为按序巡检,请按顺序进行巡检任务！',
    //         toastLength: Toast.LENGTH_SHORT,
    //       ).then((v){
    //         if(this._controller != null){
    //           setState(() {
    //             returnTimes = 0;
    //           });
    //           this._controller.startCamera(onScan);
    //         }
    //       });
    //       return;
    //     }
    //   }
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black54,
      appBar: AppBar(
        title: const Text(
          '二维码扫描',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
        centerTitle: true,
        elevation: 0,
        brightness: Brightness.light,
        backgroundColor: Colors.black54,
      ),
      body: Container(
        color: Colors.black54,
        width: double.infinity,
        height: double.infinity,
      ),
    );
  }
}
