package nckd.jimin.jyyy.hr.hom.formplugin;

import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.OrmLocaleValue;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.fi.v2.fah.utils.StringUtils;
import kd.hr.hom.common.util.PinyinUtil;
import kd.sdk.plugin.Plugin;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Module           :核心人力云-入职管理-入职人员管理-入职申请
 * Description      :入职申请/办理表单插件
 * @author Tyx
 * @date  2025/5/13
 * 标识 hom_onbrdinfo
 */
public class OnbrdInfoEditEx extends AbstractFormPlugin implements Plugin {

    private static String email_ex = "@jeyoupharma.com";    //邮箱后缀
    private static String homoPhone_entity = "nckd_homophone";
    /**
     * 值改变事件
     * @param e
     */
    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String key = e.getProperty().getName();
        IDataModel model = this.getModel();
        //姓名变化后，生成邮箱
        //2025-05-23 修改：个人性质为职能人员或学术代表 且 职级不等于O1-O4 才生成邮箱
        if(key.equals("name") || key.equals("nckd_personproperty") || key.equals("ajoblevel")) {
            Object oriName = model.getValue("name");
            Object property = model.getValue("nckd_personproperty");
            Object jobLevel = model.getValue("ajoblevel");
            if (ObjectUtils.isEmpty(oriName) || ObjectUtils.isEmpty(property) || ObjectUtils.isEmpty(jobLevel)) {
                this.getModel().setValue("nckd_companyemail", null);
                return;
            }
            OrmLocaleValue orm = (OrmLocaleValue) this.getModel().getValue("name");
            String name = orm.getLocaleValue_zh_CN().trim();
            String propertyNo = ((DynamicObject) property).getString("number");
            String jobLevelNo = ((DynamicObject) jobLevel).getString("name");
            List propertyCon = Arrays.asList(new String[]{"A1","A2"});
            List jobLevelCon = Arrays.asList(new String[]{"O1","O2","O3","O4"});
            if(!propertyCon.contains(propertyNo) || jobLevelCon.contains(jobLevelNo)) {
                this.getModel().setValue("nckd_companyemail", null);
                return;
            }
            else {
                try {
                    //转换成拼音
                    //2025-05-23 处理多音字 只处理姓氏
                    String surName = name.substring(0,1);
                    //查询多音字基础资料上是否有维护该姓氏，有的话以维护的拼音为准；
                    String py1 = getHomoPhoneChar(surName);
                    String py2 = PinyinUtil.converterToSpell(name.substring(1, name.length())).replaceAll("\\s", "");
                    String py = py1.concat(py2);
                    py = py.toLowerCase();
                    //查询是否有重复
                    String sql = " /*dialect*/ select distinct fbusemail from t_hrpi_percontact where fbusemail like '" + py + "%" + email_ex + "'";
                    DataSet dataSet = DB.queryDataSet(this.getClass().getName(), DBRoute.of("hr"), sql);
                    String email = "";
                    int maxSerial = 0;
                    while (dataSet.hasNext()) {
                        Row rowData = dataSet.next();
                        email = rowData.getString("fbusemail");
                        Pattern pat = Pattern.compile(py + "([0-9]+)" + email_ex);
                        Matcher matcher = pat.matcher(email);
                        while (matcher.find()) {
                            String serial = email.substring(matcher.start(1), matcher.end(1));
                            if (maxSerial < java.lang.Integer.valueOf(serial)) {
                                maxSerial = java.lang.Integer.valueOf(serial);
                            }
                        }
                        if (maxSerial == 0) {
                            //找到了一个同名，但是没有序号的邮箱
                            maxSerial++;
                        }
                    }
                    if (maxSerial > 0) {
                        maxSerial++;
                        py = py + maxSerial;
                    }
                    this.getModel().setValue("nckd_companyemail", py + email_ex);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }


    /**
     * 获取多音字拼音
     * @param surName
     * @return
     * @throws Exception
     */
    public String getHomoPhoneChar(String surName) throws Exception {
        QFilter filter = new QFilter("name", QCP.equals, surName);
        boolean isExists = QueryServiceHelper.exists(homoPhone_entity, new QFilter[]{filter});
        if(isExists) {
            DynamicObject dyn = QueryServiceHelper.queryOne(homoPhone_entity,"nckd_pinyin",new QFilter[]{filter});
            return dyn.getString("nckd_pinyin");
        }
        else {
            return PinyinUtil.converterToSpell(surName).replaceAll("\\s", "");
        }
    }
}