import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_i18n/modules/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/device.dart';
import 'package:flyinsono/managers/interfaces/entities/device_entities.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

class FQRLoginViewState extends FState<FQRScanView> {
  String? _qrCode;
  bool? _addUserDeviceResult;
  String _errorMessage = '';
  bool isCanLogin = false;
  ScanType scanType = ScanType.QRLogin;
  @override
  FWidget build(BuildContext context) {
    FWidget? body;
    if (scanType == ScanType.QRLogin) {
      if (isCanLogin) {
        body = _buildConfirmLogin();
      } else if (_errorMessage.isEmpty) {
        body = _buildLoginTips();
      }
    }
    if (body == null) {
      body = _buildAddDeviceResultView();
    }
    return FScaffold(
      appBar: FAppBar(
        backgroundColor: FTheme.ins.colorScheme.primary,
        title: FText(scanType == ScanType.QRLogin
            ? i18nBook.common.confirmScanQRLogin.t
            : i18nBook.user.addDevice.t),
        centerTitle: true,
      ),
      body: FCenter(
        child: body,
      ),
    );
  }

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

  Future<void> _addUserDevice() async {
    try {
      var deviceManager = Get.find<IDeviceManager>();
      var deviceInfos = await deviceManager.getUserDevicePagedList(1, 1,
          keyword: _qrCode ?? '');
      //已存在则直接路由至设备列表中
      if (deviceInfos != null &&
          deviceInfos.pageData != null &&
          deviceInfos.pageData!.length > 0) {
        router.replace(
          RouteNames.User.Device,
        );
        Future.delayed(Duration(milliseconds: 1000), () {
          PromptBox.toast(i18nBook.user.deviceAdded.t);
        });
        return;
      }
      if (Store.user.isPrincipal) {
        var deviceInfo =
            await deviceManager.getDeviceByShortCode(_qrCode ?? '');
        if (deviceInfo != null &&
            deviceInfo.organizationCode.isNotNullOrEmpty &&
            deviceInfo.organizationCode != VINNO_DEVICE_CODE) {
          setState(() {
            _errorMessage = i18nBook.user.deviceUsed.t;
          });
          return;
        } else if (deviceInfo == null) {
          setState(() {
            _errorMessage = i18nBook.errorCodes.errorCode2000.t;
          });
          return;
        }
        Future.delayed(Duration(milliseconds: 500), () {
          router.replace(
            RouteNames.Org.AddDevice,
            parameters: {'scanData': _qrCode ?? ''},
          );
        });
      } else {
        var addResult =
            await rpc.device.scanBindDeviceAsync(ScanBindDeviceRequest(
          shortCode: _qrCode,
          token: Store.user.token,
        ));
        if (addResult) {
          PromptBox.toast(i18nBook.remedical.addSuccess.t);
          router.replace(
            RouteNames.User.Device,
          );
        } else {
          router.back();
        }
      }
    } on JsonRpcException catch (ex) {
      setState(() {
        _errorMessage = i18nBook
                .getTrItem(ErrorCodesModule.ModuleName, 'errorCode${ex.code}')
                ?.t ??
            '';
      });
    } catch (e) {
      logger.e('FQRScanView _addUserDevice ex:', e);
    }
  }

  FWidget _buildAddDeviceResultView() {
    return FColumn(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (_addUserDeviceResult != null) ...[
          FText(
            _addUserDeviceResult!
                ? i18nBook.remedical.addSuccess.t
                : i18nBook.remedical.addFailed.t,
            style: TextStyle(color: Colors.black54, fontSize: FFontSizes.H4),
          ),
        ],
        if (_errorMessage.isNotEmpty) ...[
          FText(_errorMessage),
        ],
      ],
    );
  }

  FWidget _buildCancelButton() {
    return FContainer(
      margin: EdgeInsets.symmetric(
          vertical: FSpacings.XL, horizontal: FSpacings.MINI_BUTTON),
      child: FOutlinedButton(
        businessParent: widget,
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(
            Colors.transparent,
          ),
        ),
        name: 'cancel qr login',
        child: FContainer(
          alignment: Alignment.center,
          margin: EdgeInsets.symmetric(
              vertical: FSpacings.XL, horizontal: FSpacings.MINI_BUTTON),
          width: double.infinity,
          child: FText(i18nBook.common.cancel.t),
        ),
        onPressed: () {
          router.back();
        },
      ),
    );
  }

  FWidget _buildConfirmLogin() {
    return FColumn(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        FIcon(
          Icons.personal_video_rounded,
          size: 230.0,
          color: FTheme.ins.colorScheme.secondary,
        ),
        FText(
          i18nBook.common.flyinsonoLoginConfirm.t,
          style: TextStyle(color: Colors.black54),
        ),
        const FSizedBox(height: 40),
        FContainer(
          margin: EdgeInsets.symmetric(
              vertical: FSpacings.XL, horizontal: FSpacings.MINI_BUTTON),
          child: FElevatedButton(
            businessParent: widget,
            name: 'qr login',
            style: ElevatedButton.styleFrom(
              minimumSize: Size(double.infinity, 50),
            ),
            child: FText(i18nBook.common.confirmLogin.t),
            onPressed: () async {
              var loginResult = await _onLoginPressed();
              if (loginResult) {
                router.back();
              }
            },
          ),
        ),
        FSizedBox(height: FSpacings.M),
        _buildCancelButton(),
      ],
    );
  }

  FWidget _buildLoginTips() {
    return FColumn(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const FExpanded(child: FSizedBox()),
        FText(
          i18nBook.common.inconsistentServer.t,
          style: TextStyle(fontSize: 20),
        ),
        const FSizedBox(height: FSpacings.L),
        FText(
          i18nBook.common.ensureConsistentServerSelection.t,
          style: TextStyle(
            fontSize: 18,
            color: Colors.black54,
          ),
        ),
        FSizedBox(height: FSpacings.L),
        const FExpanded(child: FSizedBox()),
        _buildCancelButton(),
      ],
    );
  }

  void _initParameters() {
    var parameters = router.getParams() ?? {};
    if (parameters.isEmpty) {
      return;
    }
    var scanData = parameters['scanData'] ?? '';
    if (scanData.isEmpty) {
      return;
    }
    if ((!scanData.contains('&') && scanData.length == 6) ||
        scanData.contains('VCloudTerminal')) {
      if (scanData.contains('VCloudTerminal')) {
        _qrCode = scanData.split('://')[1];
      } else {
        _qrCode = scanData;
      }
      _addUserDevice();
      scanType = ScanType.AddDevice;
      return;
    }
    var scanDataInfos = scanData.split('&');
    if (scanDataInfos.length != 2) {
      isCanLogin = false;
      _errorMessage = i18nBook.auth.scanCorrectQRCode.t;
      return;
    } else {
      _qrCode = scanDataInfos[0];
      isCanLogin = true;
      if (mounted) {
        setState(() {});
      }
    }
  }

  Future<bool> _onLoginPressed() async {
    return await rpc.login.confirmScanAsync(ConfirmScanRequest(
      token: Store.user.token,
      scanCode: _qrCode,
    ));
  }
}

class FQRScanView extends FStatefulWidget implements FPage {
  FQRScanView();

  @override
  String get pageName => "FQRLoginView";

  @override
  FState<FStatefulWidget> createState() {
    return FQRLoginViewState();
  }
}

enum ScanType {
  QRLogin,
  AddDevice,
}
