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 '../../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';

///@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;
  PlanTaskDetail initData;

  @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) {
      getContent(result);
    } else {
      Navigator.pop(context);
    }
  }

  Future<void> loadData() async {
    await queryPlanTaskById(widget.planTaskId).then((data) {
      setState(() {
        initData = data;
      });
    });
  }

  Future<void> getContent(String no) async {
    if (null == initData) {
      shortMessage('计划数据不存在！').then((v) {
        scan();
      });
      return;
    }
    int pointNum = initData.points.where((f) => f.pointNO == no).toList().length;
    print(no);
    if (pointNum <= 0) {
      shortMessage('此点非巡检计划中的点，请确认后重新执行！').then((v) {
        scan();
      });
      return;
    }
    await getQueryPlanTaskBySerialInfo(1, no, widget.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('此点非巡检计划中的点，请确认后重新执行！').then((v) {
            scan();
          });
        } else {
          if (_execPoint.finish != 0) {
            shortMessage('该巡检点已执行巡检！').then((v) {
              scan();
            });
            return;
          }
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return NavigationCheckExec(data.id, planId: widget.planTaskId, pointName: _execPoint.name, checkMode: 'QR');
          })).then((v) {
            Navigator.pop(context);
          });
        }
      } else {
        shortMessage(data.message).then((v) {
          scan();
        });
      }
    });
  }

  @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,
      ),
    );
  }
}
