package baseclass;

import baseclass.tools.GetFieldsName;
import baseclass.tools.GetP2Type;
import baseclass.tools.P2Math;
import p2.p2server.P2Server;
import p2.pao.*;
import p2.security.ConnectionKey;
import p2.security.UserInfo;
import p2.util.P2AppException;
import p2.util.P2Exception;
import p2.webclient.system.controller.SessionContext;
import p2.application.tmaxbillnum.tmaxbillnum;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;

public class PaoCust extends Pao implements PaoRemote {

    /**
     * 构造函数
     *
     * @param arg0
     */
    public PaoCust(PaoSet arg0) {
        super(arg0);
    }

    @Override
    public void canDelete() throws P2Exception {
        super.canDelete();
    }

    public void fieldAction(Object paoField, String fieldname)
            throws P2Exception {
    }

    /**
     * 数据更新日志
     *
     * @throws P2Exception
     */
    private void byCreatelog() throws P2Exception {
        try {
            String ftablename = getThisPaoSet().getName();

            PaoSetRemote TOPERATIONLOGAPPSET = getPaoSet(
                    "$TOPERATIONLOGAPPSET", "TOPERATIONLOGAPPSET",
                    "FISUSED=1 and FTABLENAME='" + ftablename + "'");
            if (TOPERATIONLOGAPPSET.count() == 1) {
                String FIELDNAMES = TOPERATIONLOGAPPSET.getPao(0).getString(
                        "FIELDNAMES");
                String[] fieldnames = FIELDNAMES.split(";");

                PaoSetRemote TOPERATIONLOGDETAIL = getPaoSet(
                        "TOPERATIONLOGDETAIL", "TOPERATIONLOGDETAIL");

                for (String fieldname : fieldnames) {
                    if (toBeDeleted() || toBeAdded() || isModified(fieldname)) {
                        PaoRemote pao = TOPERATIONLOGDETAIL.addAtEnd();
                        pao.setValue("FTABLENAME", ftablename);
                        pao.setValue("UNIQUEIDVALUE", getUniqueIDValue());
                        pao.setValue("FIELDNAME", fieldname);
                        pao.setValue("FIELDVALUE", getString(fieldname));
                        pao.setValue("FIELDOLDVALUE", getPaoField(fieldname)
                                .getPreviousValue().asString());
                        pao.setValue("fstatus", toBeDeleted() ? "删除"
                                : toBeAdded() ? "新增" : "修改");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getHrQywechat(String hrid) throws P2Exception {
        PaoSetRemote pp_hr = getPaoSet("$pp_hr", "pp_hr", "hrid='" + hrid + "'");
        if (!pp_hr.isEmpty()) {
            return pp_hr.getPao(0).getString("fqywechat");
        } else {
            return "";
        }
    }

    public String getAgentQywechat(String fagentnum) throws P2Exception {
        StringBuilder Qywechat = new StringBuilder();
        PaoSetRemote tagents_users = getPaoSet("$tagents_users", "tagents_users", "fagentnum='" + fagentnum + "'");
        int i = 0;
        while (tagents_users.getPao(i) != null) {
            if (!tagents_users.getPao(0).getPaoSet("pp_hr").isEmpty()) {
                String fQywechat = tagents_users.getPao(i).getPaoSet("pp_hr").getPao(0).getString("fqywechat");
                if (!fQywechat.equals("")) {
                    if (Qywechat.toString().equals("")) {
                        Qywechat = new StringBuilder(fQywechat);
                    } else {
                        Qywechat.append(";").append(fQywechat);
                    }
                }
            }
            i++;
        }
        return Qywechat.toString();
    }


    public void fieldValidate(Object paoField, String fieldname)
            throws P2Exception {
    }

    public void fieldInitValue(Object paoField, String fieldname)
            throws P2Exception {
    }

    /*
     * public void fieldAction(PaoFieldObjectBindCust paoField,String fieldname)
     * throws P2Exception { } public void fieldValidate(PaoFieldObjectBindCust
     * paoField,String fieldname) throws P2Exception { }
     */

    public PaoSetRemote fieldGetlist(Object paoField, PaoSetRemote list,
                                     String fieldname) throws P2Exception {
        return list;
    }

    @Override
    public void init() throws P2Exception {
        super.init();
    }

    @Override
    public void add() throws P2Exception {
        super.add();
        String[] fieldsname = new GetFieldsName(getName()).getFields();
        if (Arrays.asList(fieldsname).contains("FPARENTID")
                && getOwner() != null) {
            setValue("FPARENTID", getOwner().getUniqueIDValue());
        }
    }

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

    /**
     * 删除行时，行号更新，用于表体删除时，行号的更新，可在delete中调用。
     *
     * @param rowfieldname 行号的栏位名称
     * @throws P2Exception
     */
    public void byUpdateRowNum(String rowfieldname) throws P2Exception {
        int rows = getThisPaoSet().count();
        int k = 1;
        for (int i = 0; i < rows; i++) {
            if (!getThisPaoSet().getPao(i).isSelected()) {
                getThisPaoSet().getPao(i).setValue(rowfieldname, k, 11L);
                k = k + 1;
            }
        }
    }

    /**
     * 批量添加数据，用于对话框选择带入表体或、、字段必须一一对应、
     *
     * @param remote   数据源表
     * @param arg      数据源表字段
     * @param remote2  目标表
     * @param arg2     目标表字段
     * @param isselect 是否过滤选中项
     */
    public void BatchAdd(PaoSetRemote remote, String[] arg,
                         PaoSetRemote remote2, String[] arg2, boolean isselect)
            throws P2Exception {
        if (arg.length != arg2.length) {
            throw new P2AppException("", "原表数组和目标表数组长度匹配。");
        }
        if (!isselect) {
            remote.selectAll();
        }
        Vector<PaoRemote> vector = remote.getSelection();
        // 数据表名称
        String objectname = remote.getName();
        for (PaoRemote pao : vector) {
            PaoRemote newpao = remote2.addAtEnd();
            for (int n = 0; n < arg.length; n++) {
                if (arg[n].startsWith("$")) {
                    String value = arg[n].substring(1);
                    newpao.setValue(arg2[n], value, 2L);
                } else if (arg[n].startsWith("-")) {
                    GetP2Type getP2Type = new GetP2Type(objectname);
                    String value = arg[n].substring(1);
                    String p2type = getP2Type.getP2Type(value);
                    if ("DECIMAL".equals(p2type) || "FLOAT".equals(p2type)) {
                        newpao.setValue(arg2[n], -pao.getDouble(value), 2L);
                    } else if ("INTEGER".equals(p2type)
                            || "SMALLINT".equals(p2type)) {
                        newpao.setValue(arg2[n], -pao.getInt(value), 2L);
                    }
                } else {
                    GetP2Type getP2Type = new GetP2Type(objectname);
                    String p2type = getP2Type.getP2Type(arg[n]);
                    if ("DECIMAL".equals(p2type) || "FLOAT".equals(p2type)) {
                        newpao.setValue(arg2[n], pao.getDouble(arg[n]), 2L);
                    } else if ("INTEGER".equals(p2type)
                            || "SMALLINT".equals(p2type)) {
                        newpao.setValue(arg2[n], pao.getInt(arg[n]), 2L);
                    } else if ("BOOLEAN".equals(p2type)) {
                        newpao.setValue(arg2[n], pao.getBoolean(arg[n]), 2L);
                    } else if ("DATE".equals(p2type)
                            || "DATETIME".equals(p2type)) {
                        newpao.setValue(arg2[n], pao.getDate(arg[n]), 2L);
                    }  else {
                        newpao.setValue(arg2[n], pao.getString(arg[n]), 2L);
                    }
                }
            }
        }
    }

    /**
     * 创建任务箱提醒
     *
     * @param users       需提醒的用户账号
     * @param tablename   表名
     * @param id          数据ID
     * @param appname     应用名
     * @param title       任务箱标题
     * @param description 任务箱描述
     * @throws P2Exception
     */
    public void byCreateAssignment(String[] users, String tablename, long id,
                                   String appname, String title, String description)
            throws P2Exception {
        PaoSetRemote pw_assignments = getPaoSet("$pw_assignment",
                "pw_assignment");
        for (String username : users) {
            double assignid = pw_assignments.max("ASSIGNID");
            Date date = Calendar.getInstance().getTime();
            PaoRemote pw_assignment = pw_assignments.addAtEnd();
            pw_assignment.setValue("ASSIGNID", P2Math.add(assignid, 1), 11L);
            pw_assignment.setValue("Assigncode", username, 11L);// 帐号编码
            pw_assignment.setValue("app", appname, 11L);// 要启动的应用程序的名称
            pw_assignment.setValue("Startdate", date, 11L);// 开始时间
            pw_assignment.setValue("Duedate", date, 11L);// 到期时间
            pw_assignment.setValue("Orighr", getUserName(), 11L);
            pw_assignment.setValue("Ownertable", tablename, 11L);
            pw_assignment.setValue("Ownerid", id, 11L);
            pw_assignment.setValue("Pwdescription", title, 11L);// 任务箱标题
            pw_assignment.setValue("ownerdescription", description, 11L);// 任务箱描述
            pw_assignment.setValue("Assignstatus", "active", 11L);// 任务分配状态
            pw_assignment.setValue("Wfid", 0, 11L);// 工作流标识
            pw_assignment.setValue("Nodeid", 1, 11L);
            pw_assignment.setValue("Processrev", 1, 11L);// 流程修订本
            pw_assignment.setValue("PROCESSNAME", "1", 11L);// 流程
            pw_assignment.setValue("Emailnotification", false, 11L);// 是否发送电子邮件
            pw_assignment.setValue("Langcode", "ZH", 11L);
            pw_assignment.setValue("ROLEID", 0, 11L);// 人力资源小组
        }
    }

    /**
     * 删除任务箱数据
     *
     * @param users     提醒的用户账号
     * @param tablename 表名
     * @param id        数据id
     * @throws P2Exception
     */
    @SuppressWarnings("unlikely-arg-type")
    public void byDeleteAssignment(String[] users, String tablename, long id)
            throws P2Exception {
        PaoSetRemote pw_assignments = getPaoSet("$pw_assignment",
                "pw_assignment");
        int i = 0;
        while (pw_assignments.getPao(i) != null) {
            for (String user : users) {
                String Assigncode = pw_assignments.getPao(i).getString(
                        "Assigncode");
                String Ownertable = pw_assignments.getPao(i).getString(
                        "Ownertable");
                String Ownerid = pw_assignments.getPao(i).getString("Ownerid");
                if (Assigncode.equals(user) && Ownertable.equals(tablename)
                        && Ownerid.equals(String.valueOf(id))) {
                    pw_assignments.getPao(i).delete();
                }
            }
            i++;
        }
    }

    /**
     * 获取paoset中field栏位的值，将其存入数组并返回
     *
     * @param paoset
     * @param fieldname
     * @return
     * @throws P2Exception
     */
    public String[] getStrings(PaoSetRemote paoset, String fieldname)
            throws P2Exception {
        String[] values = new String[paoset.count()];
        int i = 0;
        while (paoset.getPao(i) != null) {
            values[i] = paoset.getPao(i).getString(fieldname);
            i++;
        }
        return values;
    }

    /**
     * 获取paoset中field栏位的唯一值，将其存入数组并返回
     *
     * @param paoset
     * @param fieldname
     * @return
     * @throws P2Exception
     */
    public String[] getDistinctString(PaoSetRemote paoset, String fieldname,
                                      boolean isselect) throws P2Exception {
        ArrayList<String> list = new ArrayList<String>();
        if (isselect) {
            for (PaoRemote paoRemote : (Iterable<PaoRemote>) paoset.getSelection()) {
                String date = paoRemote.getString(fieldname);
                if (!list.contains(date)) {
                    list.add(date);
                }
            }
        } else {
            int i = 0;
            while (paoset.getPao(i) != null) {
                String date = paoset.getPao(i).getString(fieldname);
                if (!list.contains(date)) {
                    list.add(date);
                }
                i++;
            }
        }
        /*
         * int i = 0; while (paoset.getPao(i) != null) { if (isselect) { if
         * (paoset.getPao(i).isSelected()) { String date =
         * paoset.getPao(i).getString(fieldname); if (!list.contains(date)) {
         * list.add(date); } } } else { String date =
         * paoset.getPao(i).getString(fieldname); if (!list.contains(date)) {
         * list.add(date); } } i++; }
         */
        /*
         * String[] date = new String[list.size()]; int n = 0; for (String d :
         * list) { date[n] = d; n++; } return date;
         */
        int size = list.size();
        return  list.toArray(new String[size]);
    }

    public String[] getDistinctArray(String[] arrays) {
        ArrayList<String> a = new ArrayList<String>();
        for (String array : arrays) {
            if (!a.contains(array)) {
                a.add(array);
            }
        }
        int size = a.size();
        return a.toArray(new String[size]);
    }

    /**
     * 计算选中的行的栏位和
     *
     * @param paoset
     * @param fieldname
     * @return
     * @throws P2Exception
     */
    public double getSelectSum(PaoSetRemote paoset, String fieldname)
            throws P2Exception {
        double a = 0;
        int i = 0;
        while (paoset.getPao(i) != null) {
            if (paoset.getPao(i).isSelected()) {
                a = P2Math.add(a, paoset.getPao(i).getDouble(fieldname));
            }
            i++;
        }
        return a;
    }

    public Date getSelectEarliestDate(PaoSetRemote paoset, String fieldname)
            throws P2Exception {
        Date date = null;
        int i = 0;
        while (paoset.getPao(i) != null) {
            if (paoset.getPao(i).isSelected()) {
                Date newdate = paoset.getPao(i).getDate(fieldname);
                if (newdate == null || "".equals(paoset.getPao(i).getString(fieldname))) {
                    i++;
                    continue;
                } else {
                    if (date == null) {
                        date = newdate;
                    } else {
                        if (date.after(newdate)) {
                            date = newdate;
                        }
                    }
                }
            }
            i++;
        }
        if (date == null || "".equals(paoset.getPao(i).getString(fieldname))) {
            throw new P2AppException("", "无日期数据");
        }
        return date;
    }

    public String getBillNum(String appname) throws P2Exception {
        PaoSetRemote maxbill = P2Server.getP2Server().getPaoSet("tmaxbillnum",
                getUserInfo());
        maxbill.setWhere("app='" + appname + "' and siteid='" + getString("siteid") + "'");
        maxbill.reset();
        PaoRemote pao = null;
        if (maxbill.isEmpty()) {
            pao = maxbill.addAtEnd();
            pao.setValue("FSERIALNUM", 1);
            pao.setValue("APP", appname);
            pao.setValue("FLENGTH", 10);
        } else {
            pao = maxbill.getPao(0);
        }
        String billnum = ((tmaxbillnum) pao).getBillNum(true);
        maxbill.save();
        return billnum;
    }

    public String getAgentOrderBillNum(long tagentsid) throws P2Exception {
        PaoSetRemote maxbill = P2Server.getP2Server().getPaoSet("tmaxbillnum",
                getUserInfo());
        maxbill.setWhere("app='AGENTORDER' and siteid='" + getString("siteid") + "' and tagentsid='" + tagentsid + "'");
        maxbill.reset();
        PaoRemote pao = null;
        if (maxbill.isEmpty()) {
            pao = maxbill.addAtEnd();
            pao.setValue("SITEID",  getString("siteid") );
            pao.setValue("FSERIALNUM", 1);
            pao.setValue("APP", "AGENTORDER");
            pao.setValue("FLENGTH", 11);
            pao.setValue("TAGENTSID", tagentsid);
            pao.setValue("FADDTIME", true);
            pao.setValue("FTIMETYPE", "yyyyMMdd");
        } else {
            pao = maxbill.getPao(0);
        }
        String billnum = ((tmaxbillnum) pao).getBillNum(false);
        maxbill.save();
        return billnum;
    }

    /**
     * 设置总数，主要用来添加行时计算表头总金额、数量等。
     *
     * @param childPaoSet 需计算的表名
     * @param fild        需计算的栏位名称
     * @throws P2Exception
     */
    public double bySetTotalValue(PaoSetRemote childPaoSet, String fild)
            throws P2Exception {
        return childPaoSet.sum(fild);
    }

    /**
     * 获取系统参数
     *
     * @return
     * @throws P2Exception
     */
    public PaoRemote getSysVarsByUser() throws P2Exception {
        PaoSetRemote paoset = getPaoSet("$SYSVARS", "SYSVARS", "siteid='" + getUserInfo().getInsertSite() + "'");
        if (paoset.count() == 1) {
            return paoset.getPao(0);
        } else {
            throw new P2AppException("", "无系统参数");
        }
    }

    /**
     * 获取系统参数
     *
     * @return
     * @throws P2Exception
     */
    public PaoRemote getSysVars() throws P2Exception {
        PaoSetRemote paoset = getPaoSet("$SYSVARS", "SYSVARS", "siteid='" + getSite() + "'");
        if (paoset.count() == 1) {
            return paoset.getPao(0);
        } else {
            throw new P2AppException("", "无系统参数");
        }
    }

    /*
     * if (icpaoset.count() == 0) { icpao = icpaoset.addAtEnd();
     * icpao.setValue("fstockno", fstockno); icpao.setValue("fitemno", fitemno);
     * icpao.setValue("fdscpno", fdscpno); icpao.setValue("fbatchno",fbatchno);
     * }else
     */

    public Date getDateTime() {
        return Calendar.getInstance().getTime();
    }

    public Date getDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取当前系统时间，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public String getDateTime_Str() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(calendar.getTime());
    }

    /**
     * 获取当前系统时间，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public String getDate_Str() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(calendar.getTime());
    }

    /**
     * 获取当前系统时间，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public String getDateTime_Str(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(calendar.getTime());
    }

    /**
     * 获取当前系统时间，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public String getDate_Str(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(calendar.getTime());
    }

    public String getAgentnumByHrid(String hrid) throws P2Exception {
        PaoSetRemote tagents = P2Server.getP2Server().getPaoSet(
                "tagents_users", P2Server.getP2Server().getSystemUserInfo());
        tagents.setWhere("hrid='" + hrid + "'");
        tagents.reset();
        if (tagents.count() == 1) {
            String fagentnum = tagents.getPao(0).getString("fagentnum");
            tagents.close();
            return fagentnum;
        } else {
            tagents.close();
            return null;
        }
    }

    public ArrayList<HashMap<String, Object>> runQuerySQL(String sqlFormat)
            throws P2Exception {
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        Connection conn = null;
        Statement state = null;
        ResultSet rs = null;
        ConnectionKey connectionKey = P2Server.getP2Server().getSystemUserInfo().getConnectionKey();
        conn = P2Server.getP2Server().getDBConnProvider().getConnection(connectionKey);
        try {
            state = conn.createStatement();
            rs = state.executeQuery(sqlFormat);
            // 栏位名称
            ResultSetMetaData metaData = rs.getMetaData();
            // 栏位数
            int count = metaData.getColumnCount();
            String[] fieldnames = new String[count];
            for (int i = 1; i <= count; i++) {
                fieldnames[i - 1] = metaData.getColumnLabel(i);
            }
            while (rs.next()) {
                HashMap<String, Object> map = new HashMap<String, Object>(16);
                for (String fieldname : fieldnames) {
                    map.put(fieldname, rs.getObject(fieldname));
                }
                list.add(map);
            }
            rs.close();
            rs = null;
            state.close();
            state = null;
            P2Server.getP2Server().getDBConnProvider().freeConnection(connectionKey);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public void runUpdateSQL(String sqlFormat) throws P2Exception {
        Connection conn = null;
        Statement state = null;
        ConnectionKey connectionKey = P2Server.getP2Server().getSystemUserInfo().getConnectionKey();
        conn = P2Server.getP2Server().getDBConnProvider().getConnection(connectionKey);
        try {
            state = conn.createStatement();
            state.execute(sqlFormat);
            state.close();
            state = null;
            P2Server.getP2Server().getDBConnProvider().freeConnection(connectionKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 启用、停用验证
     *
     * @param isused
     * @throws P2Exception
     */
    public void usedvalidate(boolean isused) throws P2Exception {
    }

    /**
     * 启用、停用
     *
     * @param isused
     * @throws P2Exception
     */
    public void used(boolean isused) throws P2Exception {
    }

    /**
     * 红冲验证
     *
     * @throws P2Exception
     */
    public void hongvalidate() throws P2Exception {
        if (!"蓝".equals(getString("frb"))) {
            throw new P2AppException("", "红字单据不可红冲");
        }
    }

    /**
     * 红冲
     *
     * @return
     * @throws P2Exception
     */
    public PaoRemote hong() throws P2Exception {
        PaoRemote newpao = duplicate();
        newpao.setValue("frb", "红", 11L);
        return newpao;
    }

    /**
     * 审核、反审核验证
     *
     * @param ischeck
     * @throws P2Exception
     */
    public void checkvalidate(boolean ischeck) throws P2Exception {
    }

    /**
     * 审核、反审核
     *
     * @param ischeck
     * @throws P2Exception
     */
    public void check(boolean ischeck) throws P2Exception {
    }

    /**
     * 复核、反复核验证
     *
     * @param isrecheck
     * @throws P2Exception
     */
    public void recheckvalidate(boolean isrecheck) throws P2Exception {
    }

    /**
     * 复核、反复核
     *
     * @param isrecheck
     * @throws P2Exception
     */
    public void recheck(boolean isrecheck) throws P2Exception {
    }

    /**
     * 提交、反提交验证
     *
     * @param issubmit
     * @throws P2Exception
     */
    public void submitvalidate(boolean issubmit) throws P2Exception {
    }

    /**
     * 提交、反提交
     *
     * @param issubmit
     * @throws P2Exception
     */
    public void submit(boolean issubmit) throws P2Exception {
    }

    /**
     * 确认、反确认验证
     *
     * @param isconfirm
     * @throws P2Exception
     */
    public void confirmvalidate(boolean isconfirm) throws P2Exception {
    }

    /**
     * 确认、反确认
     *
     * @param isconfirm
     * @throws P2Exception
     */
    public void confirm(boolean isconfirm) throws P2Exception {
    }

    /**
     * 关闭、反关闭验证
     *
     * @return
     * @throws P2Exception
     */
    public int closevalidate(boolean isclose) throws P2Exception {
        return 1;
    }

    /**
     * 关闭、反关闭
     *
     * @return
     * @throws P2Exception
     */
    public int close(boolean isclose) throws P2Exception {
        return 1;
    }

    public void copyFieldValue(PaoRemote frompao, String[] fromfields,
                               PaoRemote topao, String[] tofields2) throws P2Exception {
        for (int i = 0; i < fromfields.length; i++) {
            topao.setValue(tofields2[i], frompao.getString(fromfields[i]));
        }
    }

    /**
     * 唯一值验证
     *
     * @param fieldname
     * @return
     * @throws P2Exception
     */
    public void distinctfieldcheck(String fieldname) throws P2Exception {
        PaoSetRemote paoset = P2Server.getP2Server().getPaoSet(getName(),
                getUserInfo());
        paoset.setWhere(fieldname + "='" + getString(fieldname)
                + "' and siteid='" + getString("siteid") + "'");
        paoset.reset();
        if (!paoset.isEmpty()) {
            paoset.close();
            throw new P2AppException("", "该"
                    + getPaoField(fieldname).getColumnTitle() + "已存在");
        }
        paoset.close();
    }

    /**
     * 唯一值验证
     *
     * @param fieldnames
     * @return
     * @throws P2Exception
     */
    public void distinctfieldcheck(String[] fieldnames) throws P2Exception {
        StringBuilder where = new StringBuilder(" siteid='" + getString("siteid") + "' ");
        StringBuilder msg = new StringBuilder();
        for (String fieldname : fieldnames) {
            where.append(" and ").append(fieldname).append("='").append(getString(fieldname)).append("'");
            msg.append(getPaoField(fieldname).getColumnTitle()).append(";");
        }
        PaoSetRemote paoset = P2Server.getP2Server().getPaoSet(getName(),
                getUserInfo());
        paoset.setWhere(where.toString());
        paoset.reset();
        if (!paoset.isEmpty()) {
            paoset.close();
            throw new P2AppException("", "该" + msg + "已存在");
        }
        paoset.close();
    }

    /**
     * 根据起订量及增量重计算数量
     *
     * @param fqty
     * @param FMINQTY
     * @param FADDQTY
     * @return
     * @throws P2Exception
     */
    public double caculateQty(double fqty, double FMINQTY, double FADDQTY)
            throws P2Exception {
        if (fqty < FMINQTY) {
            return FMINQTY;
        } else {
            if (FADDQTY != 0) {
                double a = ((P2Math.sub(fqty, FMINQTY) * 1000000) % (FADDQTY * 1000000)) / 1000000;
                fqty = a == 0 ? fqty : P2Math.add(P2Math.sub(fqty, a), FADDQTY);
            }
            return fqty;
        }
    }

    public PaoSetRemote getAppShortCut(SessionContext sessionContext)
            throws P2Exception {
        UserInfo userInfo = sessionContext.getUserInfo();
        PaoSetRemote APPSHORTCUT_VIEW = P2Server.getP2Server().getPaoSet(
                "APPSHORTCUT_VIEW", P2Server.getP2Server().getSystemUserInfo());
        APPSHORTCUT_VIEW.setWhere("hrid='" + userInfo.getUserName() + "'");
        APPSHORTCUT_VIEW.setOrderBy("SEQUENCE");
        APPSHORTCUT_VIEW.reset();
        return APPSHORTCUT_VIEW;
    }

    /**
     * 复制
     *
     * @return
     * @throws P2Exception
     */
    @Override
    public PaoRemote duplicate() throws P2Exception {
        String appname = getThisPaoSet().getApp();
        PaoRemote copyPao = null;
        if (null != appname && !"".equals(appname)) {
            PaoSetRemote tdatacopyset = getPaoSet("$tdatacopyset", "tdatacopyset", "appname='" + appname + "'");
            if (!tdatacopyset.isEmpty()) {
                copyPao = copy();
                PaoSetRemote tdatacopysetfor = tdatacopyset.getPao(0).getPaoSet("tdatacopysetfor");
                tdatacopysetfor.setWhere("fismainobject=0");
                tdatacopysetfor.reset();

                int i = 0;
                while (tdatacopysetfor.getPao(i) != null) {
                    String foreignlinkname = tdatacopysetfor.getPao(i).getString("foreignlink");
                    PaoSetRemote foreignlink = getPaoSet(foreignlinkname);
                    if (!foreignlink.isEmpty()) {
                        foreignlink.copy(copyPao.getPaoSet(foreignlinkname));
                    }
                    i++;
                }
            }
        }
        return copyPao;
    }

    /**
     * 复制时跳过的字段
     */
    @Override
    protected boolean skipCopyField(PaoFieldInfo arg0) throws P2Exception {
        String appname = getThisPaoSet().getApp();
        boolean ismainobject = true;
        if (null == appname || "".equals(appname)) {
            ismainobject = false;
            appname = getOwner().getThisPaoSet().getApp();
        }
        if ("".equals(appname)) {
            return false;
        }
        PaoSetRemote tdatacopyset = getPaoSet("$tdatacopyset", "tdatacopyset", "appname='" + appname + "'");
        if (!tdatacopyset.isEmpty()) {
            PaoSetRemote tdatacopysetfor = tdatacopyset.getPao(0).getPaoSet("tdatacopysetfor");
            if (ismainobject) {
                tdatacopysetfor.setWhere("fismainobject=1");
            } else {
                tdatacopysetfor.setWhere("fismainobject=0 and foreignlink='" + getThisPaoSet().getRelationName() + "'");
            }
            tdatacopysetfor.reset();

            if (!tdatacopysetfor.isEmpty()) {
                PaoSetRemote tdatacopysetskipcopyfield = tdatacopysetfor.getPao(0).getPaoSet("tdatacopysetskipcopyfield");
                String[] fields = getStrings(tdatacopysetskipcopyfield, "fieldname");
                return Arrays.asList(fields).contains(arg0.getName());
            }
        }
        return false;
    }
}
