import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/internal/lift/model/lift_list_entity.dart';
import 'package:liftmanager/internal/project/model/project_list_entity.dart';
import 'package:liftmanager/internal/repair/model/repair_list_entity.dart';
import 'package:liftmanager/internal/repair/repair_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/text_field_item.dart';

class RepairCreatePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return RepairCreatePageState();
  }
}

class RepairCreatePageState extends State<RepairCreatePage> {
  RepairCreateItem item = RepairCreateItem();
  TextEditingController _controller = TextEditingController();
  TextEditingController _controller1 = TextEditingController();
  TextEditingController _controller2 = TextEditingController();

  /// 选择时间
  Future<void> _selectTime() async {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
      item.callerDate = "${date.toString().split(".")[0]}";
      setState(() {});
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  _showBottomSheet(list, Function callback) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: 360.0,
          child: ListView.builder(
            itemExtent: 48.0,
            itemBuilder: (_, index) {
              return InkWell(
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  alignment: Alignment.centerLeft,
                  child: Text(list[index]),
                ),
                onTap: () {
                  setState(() {
                    callback(index);
                  });
                  NavigatorUtils.goBack(context);
                },
              );
            },
            itemCount: list.length,
          ),
        );
      },
    );
  }

  _saveAction() {
    if (item.projectId.length == 0) {
      toasts("请选择项目");
      return;
    }
    if (item.liftId.length == 0) {
      toasts("请选择电梯");
      return;
    }
    if (item.callerDate.length == 0) {
      toasts("请选择报修时间");
      return;
    }
    if (item.callerName.length == 0) {
      toasts("请填写报修人姓名");
      return;
    }
    if (item.callerTel.length == 0) {
      toasts("请填写报修人电话");
      return;
    }

    if (_controller.text.toString().length == 0) {
      toasts("请填写故障描述");
      return;
    }
    showLoading(context, "正在提交...");
    ApiService(context: context).repairAdd(
        item.projectId,
        item.liftId,
        item.isTrapped,
        item.isCritical,
        item.repairReason,
        _controller.text.toString(),
        item.callerName,
        item.callerTel,
        item.callerDate, onSuccess: (res) {
      dismissLoading(context);
      showAlert(context, "提示", "保存成功", "确定", () {
        NavigatorUtils.goBack(context);
        NavigatorUtils.goBack(context);
      });
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "发起急修",
        actions: <Widget>[
          FlatButton(
              onPressed: () {
                _saveAction();
              },
              child: Text(
                "确定",
                style: TextStyle(color: Colours.blue_app_main),
              ),
              textColor: Colours.text,
              highlightColor: Colors.transparent)
        ],
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: defaultTargetPlatform == TargetPlatform.iOS
                  ? FormKeyboardActions(child: _buildBody())
                  : SingleChildScrollView(child: _buildBody()),
            )
          ],
        ),
      ),
    );
  }

  _buildBody() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        ClickItem(
          title: "项目名称",
          content: "${item.projectName.length == 0 ? '请选择' : item.projectName}",
          onTap: () {
            NavigatorUtils.pushResult(
                context, RepairRouter.repairSelectProjectPage, (result) {
              setState(() {
                List values = result;
                ProjectListItem model = values[0];
                item.projectName = model.projectName;
                item.projectId = model.projectId;

                LiftListItem liftmodel = values[1];
                item.registrationCode = liftmodel.registrationCode;
                item.liftId = liftmodel.id;
                // item.registrationCode = "";
                // item.liftId = "";
                setState(() {});
              });
            });
          },
        ),
        Offstage(
          offstage: item.projectId.length == 0,
          child: ClickItem(
            title: "电梯",
            content:
                "${item.registrationCode.length == 0 ? '请选择' : item.registrationCode}",
            onTap: () {
              NavigatorUtils.pushResult(context,
                  "${RepairRouter.repairSelectLiftPage}?id=${item.projectId}",
                  (result) {
                setState(() {
                  LiftListItem model = result;
                  item.registrationCode = model.registrationCode;
                  item.liftId = model.id;
                  setState(() {});
                });
              });
            },
          ),
        ),
        ClickItem(
          title: "故障原因",
          content:
              "${item.repairReason == 0 ? '其他' : item.repairReason == 1 ? '停电' : '故障'}",
          onTap: () {
            _showBottomSheet(["其他", "停电", "故障"], (index) {
              item.repairReason = index;
              setState(() {});
            });
          },
        ),
        ClickItem(
          title: "是否关人",
          content: "${item.isTrapped == 0 ? '否' : '是'}",
          onTap: () {
            _showBottomSheet(["否", "是"], (index) {
              item.isTrapped = index;
              setState(() {});
            });
          },
        ),
        ClickItem(
          title: "是否紧急",
          content: "${item.isCritical == 0 ? '否' : '是'}",
          onTap: () {
            _showBottomSheet(["否", "是"], (index) {
              item.isCritical = index;
              setState(() {});
            });
          },
        ),
        ClickItem(
            title: "报修时间",
            content: "${item.callerDate}",
            onTap: () {
              _selectTime();
            }),
        TextFieldItem(
          title: "报修人",
          content: "${item.callerName}",
          controller: TextEditingController(),
          hintText: "请填写",
          focusNode: FocusNode(),
          onChanged: (res) {
            print(res);
            item.callerName = res;
          },
        ),
        TextFieldItem(
          title: "报修人电话",
          content: "${item.callerTel}",
          controller: TextEditingController(),
          hintText: "请填写",
          focusNode: FocusNode(),
          onChanged: (res) {
            print(res);
            item.callerTel = res;
          },
        ),
        Container(
          color: ThemeUtils.getTabsBg(context),
          child: Padding(
            padding: const EdgeInsets.only(
                top: 5, left: 15.0, right: 15.0, bottom: 8.0),
            child: TextField(
                maxLength: 30,
                maxLines: 3,
                controller: _controller,
                decoration: InputDecoration(
                    hintText: "故障描述",
                    border: InputBorder.none,
                    hintStyle: TextStyles.textGray14)),
          ),
        ),
      ],
    );
  }
}
