import 'package:flutter/material.dart';
import 'package:get/route_manager.dart';
import 'package:special_equipment_flutter/common/color_const.dart';
import 'package:special_equipment_flutter/common/route_string.dart';
import 'package:special_equipment_flutter/dio/api.dart';
import 'package:special_equipment_flutter/dio/http_utils.dart';
import 'package:special_equipment_flutter/model/login_bo.dart';
import 'package:special_equipment_flutter/model/unit_rigister_bo.dart';
import 'package:special_equipment_flutter/utils/storage_util.dart';
import 'package:special_equipment_flutter/utils/string_utils.dart';
import 'package:special_equipment_flutter/utils/toast_utils.dart';
import 'package:special_equipment_flutter/widgets/custom_button.dart';
import 'package:special_equipment_flutter/widgets/custom_textfield.dart';
import 'package:special_equipment_flutter/widgets/divider_custom.dart';

///公司账号注册
class RegisterPage2 extends StatefulWidget {
  ///获取单位信息 对象
  var bundle = Get.arguments;

  RegisterPage2({super.key});

  @override
  State<RegisterPage2> createState() => _RegisterPage2State();
}

class _RegisterPage2State extends State<RegisterPage2> {
  TextEditingController? loginNameText = TextEditingController();
  TextEditingController? passwordText = TextEditingController();
  TextEditingController? okPasswordText = TextEditingController();
  TextEditingController? nameText = TextEditingController();
  TextEditingController? moblieText = TextEditingController();

  FocusNode? loginNameFocusNode = FocusNode();
  FocusNode? passwordFocusNode = FocusNode();
  FocusNode? okPasswordFocusNode = FocusNode();
  FocusNode? nameFocusNode = FocusNode();
  FocusNode? moblieFocusNode = FocusNode();
  UnitRigisterBo? user = UnitRigisterBo();

  @override
  void initState() {
    super.initState();
    user = widget.bundle;
    // loginNameText!.text = 'laoliu';
    // passwordText!.text = 'Aa123456.';
    // okPasswordText!.text = 'Aa123456.';
    // nameText!.text = '老刘';
    // moblieText!.text = '15201506338';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      body: Stack(
        children: [
          Image.asset('assets/home/rigister_bg.png'),
          Container(
            margin:
                const EdgeInsets.only(left: 15, top: 130, right: 15, bottom: 0),
            decoration: const BoxDecoration(
              color: ColorConst.whiteColor,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: CustomScrollView(
              primary: false,
              shrinkWrap: true,
              slivers: <Widget>[
                SliverToBoxAdapter(
                  child: Column(
                    children: [
                      buildUnitAccount(),
                      buildSubmit(),
                      const SizedBox(height: 30)
                    ],
                  ),
                ),
              ],
            ),
          ),
          buildTopTitle(context)
        ],
      ),
    );
  }

  ///单位用户
  Container buildUnitAccount() {
    return Container(
      margin: const EdgeInsets.only(left: 10, top: 20, right: 10, bottom: 30),
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              buildSchedule(),

              ///分割线
              DividerCustom(Colors.grey[300], 15, 15, 0, 0),
              Container(
                  margin: const EdgeInsets.only(left: 5, right: 5),
                  child: const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('登录名'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ])),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: false,
                  hintText: '请填写登录名',
                  controller: loginNameText,
                  focusNode: loginNameFocusNode,
                  isNoChinese: true,
                  onChanged: (text) {
                    if (text.length >= 6) {}
                  }),
              Container(
                width: 1080,
                margin: const EdgeInsets.only(left: 5, right: 5, top: 5),
                padding:
                    const EdgeInsets.only(left: 5, right: 5, top: 3, bottom: 3),
                decoration: BoxDecoration(
                  color: Colors.orange[50],
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(5),
                      topRight: Radius.circular(5),
                      bottomLeft: Radius.circular(5),
                      bottomRight: Radius.circular(5)),
                ),
                child: const Text(
                  softWrap: true,
                  '登录名仅支持字母+数字组合、纯字母、6-20位',
                  style: TextStyle(color: Colors.orange, fontSize: 12),
                ),
              ),

              const SizedBox(height: 8),
              Container(
                  margin: const EdgeInsets.only(left: 5, right: 5),
                  child: const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('密码'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ])),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: false,
                  obscureText: true,
                  hintText: '请填写密码',
                  controller: passwordText,
                  focusNode: passwordFocusNode,
                  isNoChinese: true),
              Container(
                margin: const EdgeInsets.only(left: 5, right: 5, top: 5),
                padding:
                    const EdgeInsets.only(left: 5, right: 5, top: 3, bottom: 3),
                decoration: BoxDecoration(
                  color: Colors.orange[50],
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(5),
                      topRight: Radius.circular(5),
                      bottomLeft: Radius.circular(5),
                      bottomRight: Radius.circular(5)),
                ),
                child: const Text(
                  softWrap: true,
                  '密码至少包含以下 3 种类别：大写字母、小写字母、数字、特殊符号、8-20位',
                  style: TextStyle(color: Colors.orange, fontSize: 12),
                ),
              ),
              const SizedBox(height: 8),
              Container(
                  margin: const EdgeInsets.only(left: 5, right: 5),
                  child: const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('确认密码'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ])),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: false,
                  obscureText: true,
                  hintText: '请填写确认密码',
                  controller: okPasswordText,
                  focusNode: okPasswordFocusNode,
                  isNoChinese: true),
              const SizedBox(height: 8),
              Container(
                  margin: const EdgeInsets.only(left: 5, right: 5),
                  child: const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('联系人'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ])),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: false,
                  hintText: '请填写联系人',
                  controller: nameText,
                  focusNode: nameFocusNode),
              const SizedBox(height: 8),
              Container(
                  margin: const EdgeInsets.only(left: 5, right: 5),
                  child: const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('联系电话'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ])),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: false,
                  textInputType: TextInputType.phone,
                  maxLength: 11,
                  hintText: '请填写联系电话',
                  controller: moblieText,
                  focusNode: moblieFocusNode),
            ],
          )
        ],
      ),
    );
  }

  Column buildSchedule() {
    return Column(
      children: [
        const SizedBox(height: 5),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 18,
              height: 18,
              decoration: const BoxDecoration(
                  shape: BoxShape.circle, color: ColorConst.blue4Color),
              child: const Center(
                child: Text(
                  '1',
                  style: TextStyle(color: Colors.white, fontSize: 12),
                ),
              ),
            ),
            Container(
                width: 50,
                height: 1,
                margin: const EdgeInsets.only(left: 10, right: 10),
                color: ColorConst.greyE2Color),
            Container(
              width: 18,
              height: 18,
              decoration: const BoxDecoration(
                  shape: BoxShape.circle, color: ColorConst.blue4Color),
              child: const Center(
                child: Text(
                  '2',
                  style: TextStyle(color: Colors.white, fontSize: 12),
                ),
              ),
            ),
            Container(
                width: 50,
                height: 1,
                margin: const EdgeInsets.only(left: 10, right: 10),
                color: ColorConst.greyE2Color),
            const Text(
              '. . .',
              style: TextStyle(color: Colors.grey, fontSize: 16),
            ),
          ],
        ),
        const SizedBox(
          height: 5,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '单位信息',
              style: TextStyle(color: ColorConst.blue4Color, fontSize: 13),
            ),
            Container(
                width: 20,
                height: 0,
                margin: const EdgeInsets.only(left: 10, right: 10),
                color: ColorConst.greyE2Color),
            const Text('单位用户',
                style: TextStyle(color: ColorConst.blue4Color, fontSize: 13)),
            Container(
                width: 20,
                height: 0,
                margin: const EdgeInsets.only(left: 10, right: 10),
                color: ColorConst.greyE2Color),
            const Text('完成注册',
                style: TextStyle(color: Colors.grey, fontSize: 13)),
          ],
        )
      ],
    );
  }

  ///标题
  Stack buildTitle(text, image, isVis) {
    return Stack(
      alignment: Alignment.bottomLeft,
      children: [
        Container(
          color: ColorConst.blue3Color,
          width: 90,
          height: 10,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(
              image,
              size: 18,
              color: ColorConst.blueColor,
            ),
            Container(
              margin: const EdgeInsets.only(left: 5),
              child: Text.rich(
                  softWrap: true,
                  TextSpan(children: [
                    if (isVis) ...[
                      const TextSpan(
                          text: '*',
                          style: TextStyle(
                              fontSize: 14, color: ColorConst.red1BgColor)),
                    ],
                    TextSpan(
                      text: text,
                      style: const TextStyle(fontSize: 16, color: Colors.black),
                    ),
                  ])),
            )
          ],
        )
      ],
    );
  }

  Container buildTopTitle(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 50),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          IconButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            iconSize: 30,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                  margin: const EdgeInsets.only(top: 5),
                  child: const Text(
                    '注册单位用户',
                    style: TextStyle(
                        fontSize: 23,
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                  )),
              Container(
                  height: 3,
                  width: 50,
                  alignment: Alignment.topLeft,
                  margin: const EdgeInsets.only(top: 3, bottom: 3),
                  decoration: const BoxDecoration(
                    color: Colors.white54,
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  )),
              const Text(
                '请填写真实信息完成单位用户注册',
                style: TextStyle(fontSize: 12, color: Colors.white),
              ),
            ],
          ),
        ],
      ),
    );
  }

  ///注册按钮
  Row buildSubmit() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
            margin: const EdgeInsets.only(top: 10, bottom: 10),
            child: GradientButton(
                tapCallback: () {
                  Get.back();
                },
                height: 35,
                width: 100,
                borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(10),
                    topRight: Radius.circular(20),
                    bottomLeft: Radius.circular(20),
                    bottomRight: Radius.circular(10)),
                disable: false,
                colors: const [ColorConst.blueColor, ColorConst.blue1Color],
                child: const Text(
                  "上一步",
                  style: TextStyle(fontSize: 14, color: ColorConst.whiteColor),
                ))),
        const SizedBox(width: 30),
        Container(
            margin: const EdgeInsets.only(top: 10, bottom: 10),
            child: GradientButton(
                tapCallback: () {
                  _registerClick();
                },
                height: 35,
                width: 150,
                borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(10),
                    topRight: Radius.circular(20),
                    bottomLeft: Radius.circular(20),
                    bottomRight: Radius.circular(10)),
                disable: false,
                colors: const [ColorConst.blueColor, ColorConst.blue1Color],
                child: const Text(
                  "立即注册",
                  style: TextStyle(fontSize: 14, color: ColorConst.whiteColor),
                ))),
      ],
    );
  }

  void _registerClick() {
    if (loginNameText!.text.isEmpty) {
      loginNameFocusNode!.requestFocus();
      ToastUtils.showCenter('请填写登录名');
      return;
    }
    if (!StringUtils.isValidName(loginNameText!.text)) {
      loginNameFocusNode!.requestFocus();
      ToastUtils.showCenter('登录名仅支持字母+数字组合、纯字母、大于等于 6 位');
      return;
    }

    if (passwordText!.text.isEmpty) {
      passwordFocusNode!.requestFocus();
      ToastUtils.showCenter('请填写密码');
      return;
    }

    if (!StringUtils.isValidPassword(passwordText!.text)) {
      passwordFocusNode!.requestFocus();
      ToastUtils.showCenter('密码至少包含以下 3 种类别：大写字母、小写字母、数字、特殊符号、8-20位');
      return;
    }

    if (okPasswordText!.text.isEmpty) {
      okPasswordFocusNode!.requestFocus();
      ToastUtils.showCenter('请填写确认密码');
      return;
    }
    if (passwordText!.text != okPasswordText!.text) {
      ToastUtils.showCenter('两次密码不一致，请重新输入');
      return;
    }
    if (nameText!.text.isEmpty) {
      nameFocusNode!.requestFocus();
      ToastUtils.showCenter('请填写联系人');
      return;
    }
    if (moblieText!.text.isEmpty) {
      moblieFocusNode!.requestFocus();
      ToastUtils.showCenter('请填写联系电话');
      return;
    }
    //登录名
    user!.loginName = loginNameText!.text;
    //密码、确认密码
    user!.newPassword = okPasswordText!.text;
    //联系人
    user!.name = nameText!.text;
    //联系电话
    user!.mobile = moblieText!.text;

    HttpUtils.getUnitRigister(context, user).then((value) {
      if (value == null) {
        return;
      }
      if (mounted) {
        setState(() {
          ToastUtils.showCenter('注册成功');

          ///注册成功直接登录
          HttpUtils.doLogin(context, loginNameText!.text, okPasswordText!.text)
              .then((value) {
            if (value != null) {
              LoginBo loginBo = value;
              StorageUtil.getInstance().set(SpKeys.USER_NAME, loginBo.username);
              StorageUtil.getInstance().set(SpKeys.NAME, loginBo.name);
              StorageUtil.getInstance()
                  .set(SpKeys.JSESSION_ID, loginBo.jsessionid);
              StorageUtil.getInstance().set(SpKeys.USER_ID, loginBo.userId);
              StorageUtil.getInstance()
                  .set(SpKeys.OFFICE_ID, loginBo.user!.office!.id);
              StorageUtil.getInstance()
                  .set(SpKeys.OFFICE_TYPE, loginBo.user!.office!.type);
              StorageUtil.getInstance()
                  .set(SpKeys.OFFICE_NAME, loginBo.user!.office!.name);
              StorageUtil.getInstance()
                  .set(SpKeys.ROLE_NAMES, loginBo.user!.roleNames);
              Get.offAllNamed(RouteString.HOME);
            }
          });
        });
      }
    });
  }
}
