/*
 * @Author: WuWei
 * @Date: 2020-07-03 17:08:39
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-01-11 17:02:02
 * @Description:
 */
//自定义组件，放置文本输入框

import 'package:flutter/material.dart';
import 'package:task_package/src/impl/task_service_impl.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

// ignore: must_be_immutable
class InputDialog extends StatefulWidget {
  InputDialog({
    Key? key,
    required this.id,
    this.child,
  }) : super(key: key);
  final String? id;
  final Widget? child;

  static Future<bool?> show(context, {required String? id}) async {
    return await WBottomModalUtil.show<bool>(
      context,
      bodyConstraints: BoxConstraints(),
      title: Text('请填写任务用时'),
      body: InputDialog(id: id),
    );
  }

  _InputDialogState createState() => _InputDialogState();
}

class _InputDialogState extends State<InputDialog> {
  FocusNode? myFocusNode;
  final modalformKey = GlobalKey<FormState>();

  double? time = 0;

  @override
  void initState() {
    super.initState();
    getUseTime();
    myFocusNode = FocusNode();
  }

  @override
  void dispose() {
    myFocusNode!.dispose();
    super.dispose();
  }

  String? alltime;
  alltimeChange(String v) {
    alltime = v;
  }

  getUseTime() async {
    time = await TaskServiceImpl.instance!.getUseTime({'id': widget.id});
    setState(() {});
  }

  /// 任务确认完成 返回一个true   通知刷新
  Future onModelFinish() async {
    if (!modalformKey.currentState!.validate()) {
      return;
    }
    var res = await TaskServiceImpl.instance!.putFinished(
      {
        'id': widget.id,
        'content': alltime,
      },
    );
    if (res.data == 1) {
      WToastUtil.show('任务完成成功！');
      Navigator.pop(context, true);
    }
  }

  validator(value) {
    if (value == null || value == '') {
      return '任务用时不能为空';
    }
    var parse = double.tryParse(value) ?? 0;

    if (parse <= 0) {
      return '只支持大于0的数字';
    }
    if (parse > 99999.9) {
      return '超过最大输入限制99999.9';
    }
    Pattern pattern =
        r'^([1-9][0-9]*)+([.][0-9]{1}){0,1}$|^[0]+([.][1-9]{1}){0,1}$';
    RegExp time = new RegExp(pattern as String);

    if (!time.hasMatch(value)) {
      return '只支持一位小数的数字';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    return Padding(
      padding: EdgeInsets.only(
        bottom: MediaQuery.of(context).viewInsets.bottom,
      ),
      child: SingleChildScrollView(
        child: WisForm(
          formKey: modalformKey,
          child: Wisdom.column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            padding: EdgeInsets.all(15.pt),
            children: <Widget>[
              Wisdom.row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text('任务持续时长：'),
                  Text('$time小时'),
                ],
              ),
              Divider(height: 40.pt),
              TextFormField(
                autofocus: true,
                focusNode: myFocusNode,
                textAlign: TextAlign.right,
                onChanged: (v) => alltimeChange(v),
                validator: (v) => validator(v),
                style: TextStyle(fontWeight: FontWeight.normal),
                decoration: InputDecoration(
                  icon: Text('任务用时'),
                  suffixIcon: Text('小时'),
                  suffixIconConstraints: BoxConstraints(
                    maxHeight: 20.pt,
                  ),
                  hintText: '请输入本次任务用时',
                  suffixStyle: TextStyle(color: Colors.black),
                  fillColor: Colors.white,
                  contentPadding: EdgeInsets.zero,
                ),
                keyboardType: TextInputType.numberWithOptions(
                  decimal: true,
                ),
              ),
              Divider(height: 20.pt),
              WisText('说明', size: 15.pt, bold: true, height: 2.5),
              WisText(
                '1. 任务用时输入支持一位小数。\n2. 任务持续时长为派单至当前时长。\n3. 确认完成后，任务内容不可修改\n',
                size: 12.pt,
              ),
              WLoadingButton(
                height: 44.pt,
                onPressed: () => onModelFinish(),
                color: colorScheme.primary,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.pt),
                ),
                child: WisText('确定'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
