package p2.application.tenterprise_users;

import baseclass.PaoCust;
import com.cnd3b.common.data.Row;
import com.cnd3b.common.data.Rows;
import com.cnd3b.common.data.db.DBConnect;
import p2.pao.PaoSet;
import p2.util.P2Exception;
import p2.application.tagents.tagents;
import p2.application.tenterprise.tenterprise;

import java.util.ArrayList;
import java.util.Random;

public class tenterprise_users extends PaoCust {
    public tenterprise_users(PaoSet arg0) {
        super(arg0);
    }

    @Override
    public void add() throws P2Exception {
        super.add();
        if (getOwner() instanceof tagents) {
            setValue("tagentsid", getOwner().getUniqueIDValue(), 11L);
            setValue("fusertype", "经销商", 11L);
        } else if (getOwner() instanceof tenterprise) {
            if ("PROMOTERS".equals(getString("siteid"))) {
                setValue("fusertype", "推广人", 11L);
            } else {
                setValue("fusertype", "企业", 11L);
            }
        }
        setValue("faccountno", createAccount());
        //setValue("fshortcode", createShortCode());//简码（邀请码）
    }

    @Override
    protected void save() throws P2Exception {
        super.save();
    }

    public static long maxAccount = 0L;
    public static ArrayList<Long> accountList = new ArrayList<>();

    private long createAccount() {
        if (maxAccount == 0) {
            DBConnect dbConnect = new DBConnect();
            Row rows = dbConnect.runSqlQuery(0,"select convert(bigint,isnull(max(faccountno),100001)) as faccountno from tenterprise_users");

            maxAccount = rows.getLong("faccountno");

            Rows rows2 = dbConnect.runSqlQuery("select faccountno from tenterprise_users");
            for (Row row : rows2) {
                accountList.add(Long.parseLong(row.getString("faccountno")));
            }
        }
        maxAccount = maxAccount + 1;
        if (accountList.contains(maxAccount)) {
            return createAccount();
        } else {
            accountList.add(maxAccount);
            return maxAccount;
        }
    }

    public static ArrayList<String> ShortCodelist = new ArrayList<>();

    private String createShortCode() {
        if (ShortCodelist.isEmpty()) {
            DBConnect dbConnect = new DBConnect();
            Rows rows = dbConnect.runSqlQuery("select fshortcode from tenterprise_users");
            ShortCodelist = rows.toArrayList("fshortcode");
        }
        String allChar = "1234567890";
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 7; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        if (ShortCodelist.contains(sb.toString())) {
            return createShortCode();
        } else {
            ShortCodelist.add(sb.toString());
            return sb.toString();
        }
    }
}
