/*
 * @Author       : WuWei
 * @LastEditors: wuwei
 * @Date         : 2021-08-17 15:03:40
 * @LastEditTime: 2024-01-15 10:56:51
 * @Description  : 巡逻、设备巡检、设备保养点位表单
 */

import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:task_package/src/assets.gen.dart';
import 'package:task_package/src/view_models/location_util_store.dart';
import 'package:task_package/src/view_models/point_form_store.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:task_package/src/models/task_operation_node_list.dart';

import '../../impl/qrcode_impl.dart';
import '../../models/tak_operation_instruction.dart';
import '../../models/task_operation_form.dart';
import '../../models/task_operation_instruction_list.dart';
part 'components/detail_form.dart';
part 'components/scan_qrcode.dart';
part 'components/standard_form.dart';
part 'components/info.dart';
part 'components/work_detail.dart';
part 'index.g.dart';

///路由传递的参数
class PointFormPageArguments {
  final String? id;
  final String? cid;
  final String? platformId;
  final String? relationIds;
  final String? type;
  final String? detailStatus;
  final bool? seqencing;
  final dynamic route;
  final dynamic detailData;
  final bool? isEquipment;
  final bool? isDealAbnormalSolve;
  final TaskOperationNodeListItemList? routeItem;
  final bool? isHistory;
  PointFormPageArguments({
    this.id,
    this.cid,
    this.platformId,
    this.relationIds,
    this.type,
    this.detailStatus,
    this.route,
    this.detailData,
    this.seqencing,
    this.isEquipment,
    this.isDealAbnormalSolve,
    this.routeItem,
    this.isHistory,
  });

  ///
  ///
  ///
  ///
  ///
  ///
  ///
//***以下为模板代码谨慎修改***
  factory PointFormPageArguments.fromJson(Map<String, dynamic> json) {
    return _$PointFormPageArgumentsFromJson(json);
  }
  factory PointFormPageArguments.fromRouteArguments(BuildContext context) {
    return _$PointFormPageArgumentsFromJson(
        (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>);
  }
  Map<String, dynamic> toJson() => _$PointFormPageArgumentsToJson(this);
}

///
///
///
///
///
//***以下为模板代码谨慎修改***
class PointFormPage extends StatelessWidget {
  const PointFormPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => PointFormStore(context)),
        // ChangeNotifierProvider(create: (_) => LocationUtilStore(context)),
      ],
      child: _PageView(),
    );
  }
}

class _PageView extends StatefulWidget {
  _PageView({Key? key}) : super(key: key);

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

class __PageViewState extends State<_PageView> {
  PointFormStore get store => Provider.of(context, listen: false);
  // LocationUtilStore get store2 =>
  //     Provider.of<LocationUtilStore>(context, listen: false);
  @override
  void initState() {
    super.initState();
    // store.onGetDetail();
  }

  @override
  void deactivate() {
    // store.destroy();
    super.deactivate();
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = WTheme.of(context).colorScheme;
    final store = Provider.of<PointFormStore>(context, listen: true);
    Future<bool> _onWillPop() async {
      return (await showDialog(
            context: context,
            builder: (context) => AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15.pt),
              ),
              title: WisText('确认返回吗'),
              content: WisText(
                '确认是否已提交，填写的表单会丢失',
                size: 13.pt,
              ),
              actions: <Widget>[
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: WisText(
                    '取消',
                    size: 15.pt,
                    color: colorScheme.mainTitle,
                  ),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: WisText(
                    '确认',
                    size: 15.pt,
                    color: colorScheme.mainTitle,
                  ),
                ),
              ],
            ),
          )) ??
          false;
    }

    return Observer(builder: (_) {
      return WillPopScope(
        onWillPop:
            store.detail?.status == 'finished' || (store.formList.length == 0)
                ? null
                : _onWillPop,
        child: Scaffold(
          appBar: WAppBar(
            brightness: Brightness.light,
            iconTheme: IconThemeData(
              color: colorScheme.mainTitle,
              size: 19.pt,
            ),
            backgroundColor: Colors.white,
            title: WisText(
              store.isHistory ? '操作记录' : '点位详情',
              size: 19.pt,
              weight: FontWeight.w600,
              color: colorScheme.mainTitle,
            ),
          ),
          body: WisScrollView(
            onInit: () => store.onGetDetail(),
            slivers: [
              Observer(builder: (BuildContext context) {
                return Column(children: [
                  /// 基本信息
                  _BuildInfo(),
                  SizedBox(
                    height: 10.pt,
                  ),
                  if (store.detail?.status != 'finished') ...[
                    if (store.formList.length > 0) ...[
                      /// 作业标准表单
                      _BuildStandard(),
                    ] else ...[
                      /// 扫描二维码
                      if (store.detail != null) ...[
                        _BuildScanQRCode(),
                      ] else ...[
                        Container(height: 0),
                      ]
                    ],
                  ] else ...[
                    /// 作业标准填写详情
                    _BuildDetailForm(),
                  ],
                  SizedBox(
                    height: 59.pt,
                  ),
                ]);
              }).asSliver(),
            ],
          ),

          /// 没有扫描二维码之前 底部没有这个按钮
          bottomSheet: store.isShowBottom == true ? _BuildBottom() : null,
        ),
      );
    });
  }
}

class _BuildBottom extends StatelessWidget {
  const _BuildBottom({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final colorScheme = WTheme.of(context).colorScheme;
    final store = Provider.of<PointFormStore>(context, listen: false);

    void _onShowAbnormalList() {
      showModalBottomSheet(
        isScrollControlled: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.pt),
            topRight: Radius.circular(10.pt),
          ),
        ),
        context: context,
        builder: (BuildContext context) {
          return new SingleChildScrollView(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom),
            child: SafeArea(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Wisdom(
                        width: 100,
                        alignment: Alignment.centerLeft,
                      ),
                      Text(
                        '异常处理',
                        textAlign: TextAlign.center,
                        maxLines: 1,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ).asExpanded(),
                      Wisdom(
                        width: 100,
                        alignment: Alignment.centerRight,
                        child: CloseButton(
                          onPressed: () => Navigator.pop(context),
                        ),
                      ),
                    ],
                  ),
                  Divider(height: 1),
                  ConstrainedBox(
                    constraints: BoxConstraints(minHeight: 250, maxHeight: 600),
                    child: Stack(
                      children: [
                        SingleChildScrollView(
                          child: Wisdom.column(
                            padding: EdgeInsets.symmetric(
                                horizontal: 15.pt, vertical: 10.pt),
                            mainAxisAlignment: MainAxisAlignment.center,
                            margin: EdgeInsets.only(bottom: 60.pt),
                            children: [
                              for (int i = 0;
                                  i < store.abnormalItemList.length;
                                  i++)
                                Wisdom.row(
                                  onTap: () => store.toCreateTaskByAbnormal(
                                      store.abnormalItemList[i]),
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 5.pt, vertical: 10.pt),
                                  margin: EdgeInsets.symmetric(vertical: 5.pt),
                                  borderRadius: BorderRadius.circular(8.pt),
                                  color: Colors.grey[100],
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    WisText(
                                      '${store.abnormalItemList[i].title ?? '--'}',
                                      size: 16.pt,
                                      weight: FontWeight.bold,
                                      height: 1.8,
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ).asExpanded(),
                                    Wisdom(
                                      margin: EdgeInsets.only(left: 5.pt),
                                      child: Icon(
                                        Icons.arrow_forward_ios,
                                        size: 14.pt,
                                        color: colorScheme.grey,
                                      ),
                                    )
                                  ],
                                )
                            ],
                          ),
                        ),
                        new Positioned(
                          bottom: 15,
                          left: 0.0,
                          right: 0.0,
                          child: new Wisdom(
                            borderRadius: BorderRadius.circular(25.pt),
                            color: colorScheme.primary,
                            margin: EdgeInsets.symmetric(horizontal: 15.pt),
                            child: new TextButton(
                              child: new Text(
                                '取消',
                                textAlign: TextAlign.center,
                                style: new TextStyle(
                                    color: Colors.white, fontSize: 15.0),
                              ),
                              onPressed: () => Navigator.pop(context),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      );
    }

    Widget _buildInstruction() {
      return Observer(builder: (_) {
        return Row(
          children: [
            if (store.isHistory) ...[
              Container(),
            ] else ...[
              Wisdom(
                borderRadius: BorderRadius.circular(100.pt),
                padding:
                    EdgeInsets.symmetric(horizontal: 15.pt, vertical: 5.pt),
                margin: EdgeInsets.only(right: 9.pt),
                border: Border.all(
                  color: colorScheme.primary,
                  width: 1.pt,
                ),
                onTap: () => {
                  if (store.instructionList.length == 0)
                    {
                      WToastUtil.show('暂无作业指导~'),
                    }
                  else if (store.instructionList.length > 1)
                    {
                      store.toWorkInstructionsList(),
                    }
                  else
                    {
                      store.toWorkInstructionsDetail(),
                    }
                },
                child: Center(
                  child: WisText(
                    '作业指导',
                    size: 16.pt,
                    color: colorScheme.primary,
                  ),
                ),
              ),
            ]
          ],
        );
      });
    }

    Widget _buildErrbtn() {
      return Wisdom(
        onTap: () => _onShowAbnormalList(),
        borderRadius: BorderRadius.circular(100.pt),
        padding: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 5.pt),
        margin: EdgeInsets.symmetric(horizontal: 9.pt),
        border: Border.all(
          color: colorScheme.primary,
          width: 1.pt,
        ),
        color: colorScheme.primary,
        child: Center(
          child: WisText(
            ' 异常处理',
            size: 16.pt,
            color: Colors.white,
          ),
        ),
      );
    }

    Widget _buidBottomRow(List<Widget>? child) {
      return Wisdom.row(
        height: 70.pt,
        color: Colors.white,
        padding: EdgeInsets.only(
            left: 15.pt, right: 15.pt, bottom: 18.pt, top: 10.pt),
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: child ?? [],
      );
    }

    Widget _buildRepair() {
      return Wisdom(
        onTap: () => store.toRepair(),
        height: 44.pt,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 5.pt),
        borderRadius: BorderRadius.circular(100.pt),
        color: colorScheme.primary,
        child: Wisdom.column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              WisText(
                '报修',
                color: Colors.white,
                size: 16.pt,
              ),
            ]),
      );
    }

    return Observer(
      builder: (_) {
        if (store.detail?.status == 'unFinished') {
          if (store.formList.length > 0) {
            return _buidBottomRow([
              /// 作业指导
              _buildInstruction(),
              Wisdom.row(
                height: 44.pt,
                color: colorScheme.primary,
                padding:
                    EdgeInsets.symmetric(horizontal: 15.pt, vertical: 5.pt),
                mainAxisAlignment: MainAxisAlignment.center,
                borderRadius: BorderRadius.circular(100.pt),
                onTap: () => {store.onHandleSubmit()},
                children: [
                  WisText(
                    '提交',
                    color: Colors.white,
                    size: 16.pt,
                    weight: FontWeight.w300,
                  ),
                ],
              ).asFlexible(flex: 1)
            ]);
          } else {
            return _buidBottomRow([
              /// 作业指导
              _buildInstruction(),
            ]);
          }
        } else {
          // 类型是设备巡检（451357265520177152）或设备保养（451357265520177153）或 2023.12.22 设备维修（451357265520177154）
          if (store.detail?.type == '451357265520177152' ||
              store.detail?.type == '451357265520177153' ||
              store.detail?.type == '451357265520177154') {
            return _buidBottomRow([
              /// 作业指导
              _buildInstruction(),
              // 2024.01.05 去除下一个操作
              if (store.isDealAbnormalSolve == true &&
                  store.abnormalItemList.length > 0) ...[
                /// 报修
                _buildRepair(),

                /// 异常处理
                _buildErrbtn().asExpanded(),
              ] else ...[
                /// 报修
                _buildRepair().asFlexible(flex: 2),
              ],
            ]);
          } else {
            return Observer(builder: (_) {
              return _buidBottomRow([
                /// 作业指导
                _buildInstruction(),
                if (store.isDealAbnormalSolve == true &&
                    store.abnormalItemList.length > 0) ...[
                  /// 异常处理
                  _buildErrbtn().asExpanded(),
                ],
              ]);
            });
          }
        }
      },
    );
  }
}
