package nckd.base.helper;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.ConfirmTypes;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.control.Button;
import kd.bos.form.control.Control;
import kd.bos.form.control.events.BeforeClickEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.EventObject;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 基础服务云->基础资料->盐业通用数据
 * 页面编码: nckd_changeuserpwd , 修改登录pwd
 * 动态表单
 * author：chengchaohua
 * date: 2025-02-07
 */
public class ChangeUserLoginPwd extends AbstractFormPlugin implements Plugin {

    private static final Log LOGGER = LogFactory.getLog(ChangeUserLoginPwd.class);


    @Override
    public void registerListener(EventObject e) {
        // 按钮点击监听
        Button button = this.getView().getControl("nckd_updatepwd");
        button.addClickListener(this);
        super.registerListener(e);
    }

    @Override
    public void beforeClick(BeforeClickEvent evt) {
        super.beforeClick(evt);
        String key = ((Control) evt.getSource()).getKey();
        if ("nckd_updatepwd".equals(key)) {
            DynamicObject userObj = (DynamicObject) this.getModel().getValue("nckd_user");
            if (userObj == null) {
                this.getView().showTipNotification("人员必选");
                evt.setCancel(true);
                return;
            }

            String pwd = (String) this.getModel().getValue("nckd_newpwd");
            if (pwd == null || pwd.length() <= 6) {
                this.getView().showTipNotification("密码不能少于7位");
                evt.setCancel(true);
                return;
            } else {
                if (!checkPwd(pwd)){
                    this.getView().showTipNotification("密码只能包含数字，大小写字母和@，并至少包含一个字母");
                    evt.setCancel(true);
                    return;
                }
            }
        }
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        String key = ((Control) evt.getSource()).getKey();
        if ("nckd_updatepwd".equals(key)) {
            ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener("updatepwd", this);
            String confirmTip = "是否确认继续?";
            this.getView().showConfirm(confirmTip, MessageBoxOptions.YesNo, ConfirmTypes.Default, confirmCallBacks);
        }
    }

    /**
     * 用户确认了交互信息后，触发此事件
     */
    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);
        IDataModel model = this.getModel();
        if (StringUtils.equals("updatepwd", messageBoxClosedEvent.getCallBackId())) {
            // 1.产品交互信息
            if (messageBoxClosedEvent.getResult() == MessageBoxResult.Yes) {
                // 确认执行
                String pwd = (String) model.getValue("nckd_newpwd");
                DynamicObject userObj = (DynamicObject) model.getValue("nckd_user");

                Map<String, Object> map = UserServiceHelper.changePsw((Long) (userObj.getPkValue()), null, pwd);
                Boolean result = (Boolean) map.get("success");
                if (result) {
                    this.getView().showSuccessNotification(userObj.getString("name") + "：密码更新成功");
                    LOGGER.info("管理员修改：" + userObj.getString("name") + "，密码成功");
                } else {
                    this.getView().showErrorNotification("密码更新失败：" + map.get("msg"));
                }
            } else {
                // 取消或关闭弹框
                this.getView().showSuccessNotification("已取消更新");
            }
        }
    }

    // 校验密码字符
    boolean checkPwd(String pwd) {
        // 正则表达式：[a-zA-Z0-9@]+$
        //  表示字符串的开始
        // [a-zA-Z0-9@] 表示允许的字符集，包括小写字母、大写字母、数字和@
        // + 表示前面的字符集可以出现一次或多次
        // $ 表示字符串的结束
        String regex = "(?=.*[a-zA-Z])[a-zA-Z0-9@]+$";

        Pattern pattern = Pattern.compile(regex);
        // 返回true为校验符合
        return pattern.matcher(pwd).matches();
    }

}
