/*
 * @Author: XianKaiQun
 * @Date: 2020-07-10 10:30:59
 * @LastEditors: wuwei oyoung3231@gmail.com
 * @LastEditTime: 2025-05-27 16:02:50
 * @Description: 
 */
part of '../index.dart';

class _PassWordComponent extends StatefulWidget {
  _PassWordComponent({Key? key}) : super(key: key);
  static show(BuildContext context) async {
    await showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) {
        return _PassWordComponent();
      },
    );
  }

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

class __PassWordComponentState extends State<_PassWordComponent> {
  final formKey = GlobalKey<FormState>();
  bool show1 = false;
  bool show2 = false;
  bool show3 = false;

  late Map params = {
    'origPsw': '',
    'newPsw': '',
    'newPswCheck': '',
  };

  changeShow1() {
    show1 = !show1;
    setState(() {});
  }

  changeShow2() {
    show2 = !show2;
    setState(() {});
  }

  changeShow3() {
    show3 = !show3;
    setState(() {});
  }

  validatorPsw(String value) {
    if (value.length < 6) {
      return '密码不能少于6位';
    }

    Pattern pattern = r'^[\d]+$|^[a-zA-Z]+$';
    RegExp regExp = new RegExp(pattern as String);
    if (regExp.hasMatch(value)) {
      return '不能使用纯数字或者纯字母';
    }
    if (value == params['origPsw']) {
      return '新旧密码不能相同';
    }
  }

  changeParams(String field, String value) {
    params[field] = value;
  }

  ///修改密码
  Future submit() async {
  
    if (params['origPsw'] == null || params['origPsw'] == '') {
      WToastUtil.show('原密码不可为空', location: WToastLoction.top);
      return;
    }

    if (params['newPswCheck'] == null || params['newPswCheck'] == '') {
      WToastUtil.show('请输入确认密码', location: WToastLoction.top);
      return;
    }

    print(params['newPswCheck']);
    print(params['origPsw']);

    if (params['newPswCheck'] != params['newPsw']) {
      WToastUtil.show('两次新密码输入不一致', location: WToastLoction.top);
      return;
    }

    if (params['newPsw'] == null || params['newPsw'].length < 6) {
      WToastUtil.show('密码不能少于6位', location: WToastLoction.top);
      return;
    }

    if (params['newPsw'] == null || params['newPsw'].length > 20) {
      WToastUtil.show('密码不能多于20位', location: WToastLoction.top);
      return;
    }

    // RegExp regExp = new RegExp(r'^[\d]+$|^[a-zA-Z]+$');
    // if (regExp.hasMatch(params['newPsw'])) {
    //   WToastUtil.show('不能使用纯数字或者纯字母', location: WToastLoction.top);
    //   return;
    // }

    final hasUppercase = RegExp(r'[A-Z]');
    if (hasUppercase.hasMatch(params['newPsw']) != true) {
      WToastUtil.show('至少包含一个大写字母', location: WToastLoction.top);
      return;
    }

    final hasLowercase = RegExp(r'[a-z]');
    if (hasLowercase.hasMatch(params['newPsw']) != true) {
      WToastUtil.show('至少包含一个小写字母', location: WToastLoction.top);
      return;
    }

    final hasNumber = RegExp(r'[0-9]');
    if (hasNumber.hasMatch(params['newPsw']) != true) {
      WToastUtil.show('至少包含一个数字', location: WToastLoction.top);
      return;
    }

    if (params['newPsw'] == params['origPsw']) {
      WToastUtil.show('新旧密码不能相同', location: WToastLoction.top);
      return;
    }

    final publicKey =
        "04e60d11e34bc2050e1ff22cfa4dbf3de25586b4a96a24a82d5cdd871086575bd0b32b569c6092aca803cb079a31a5c905095847f6dfd9d9bef0717a43c3437ce4";

    var cipherOrigin =
        SM2Crypto.encrypt(params['origPsw'], publicKey, c1c3c2Mode: true);
    var cipherNew =
        SM2Crypto.encrypt(params['newPsw'], publicKey, c1c3c2Mode: true);
    print('cipherOrigin加密: $cipherOrigin');
    print('cipherNew加密: $cipherNew');

    var res = await AuthApi.putPswMotify({
      "origPsw": cipherOrigin,
      "newPsw": cipherNew,
    });
    if (res == true) {
      Get.back();
      WModalUtil.showSync('您需要重新登录', title: '密码修改成功', canCancel: false)
          .then((value) {
        final authGlobalStore = GetIt.I.get<AuthGlobalStore>();
        authGlobalStore.logout();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    return WisForm(
      autovalidateMode: AutovalidateMode.always,
      formKey: formKey,
      child: WisDialog(
        title: WisText('修改密码', size: 16.pt),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.pt),
        ),
        contentPadding: EdgeInsets.all(15.pt),
        content: Wisdom.column(
          minHeight: 260.pt,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            TextFormField(
              onChanged: (v) => changeParams('origPsw', v),
              obscureText: !show1,
              decoration: InputDecoration(
                hintText: '请输入原始密码',
                contentPadding: EdgeInsets.all(10.pt),
                isDense: true,
                fillColor: colorScheme.background,
                filled: true,
                icon: Text('原始密码'),
                suffix: Wisdom(
                  onTap: () => changeShow1(),
                  child: Icon(
                    FaIcons.eye,
                    size: 15.pt,
                    color: show1 ? colorScheme.primary : Colors.black38,
                  ),
                ),
              ),
            ),
            SizedBox(height: 10.pt),
            TextFormField(
              onChanged: (v) => changeParams('newPsw', v),
              obscureText: !show2,
              decoration: InputDecoration(
                hintText: '请输入新密码',
                contentPadding: EdgeInsets.all(10.pt),
                isDense: true,
                fillColor: colorScheme.background,
                filled: true,
                icon: Text('新的密码'),
                suffix: Wisdom(
                  onTap: () => changeShow2(),
                  child: Icon(
                    FaIcons.eye,
                    size: 15.pt,
                    color: show2 ? colorScheme.primary : Colors.black38,
                  ),
                ),
              ),
            ),
            SizedBox(height: 10.pt),
            TextFormField(
              onChanged: (v) => changeParams('newPswCheck', v),
              // validator: (v) {
              //   return v != params['newPsw'] ? '两次密码输入不一致' : null;
              // },
              obscureText: !show3,
              decoration: InputDecoration(
                hintText: '请输入确认密码',
                contentPadding: EdgeInsets.all(10.pt),
                isDense: true,
                fillColor: colorScheme.background,
                filled: true,
                icon: Text('确认密码'),
                suffix: Wisdom(
                  onTap: () => changeShow3(),
                  child: Icon(
                    FaIcons.eye,
                    size: 15.pt,
                    color: show3 ? colorScheme.primary : Colors.black38,
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 15.pt),
              child: Text(
                '*密码不能少于6位，需包含数字、大写字母、小写字母',
                style: TextStyle(color: Colors.orange, fontSize: 12.pt),
              ),
            ),
            WLoadingButton(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.pt),
              ),
              onPressed: () => submit(),
              color: colorScheme.primary,
              height: 44.pt,
              child: Text('确认修改'),
            )
          ],
        ),
      ),
    );
  }
}
