package nccloud.itf.sscivm.ivsale.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.sscivm.ivsale.bp.IVApplicationQueryBP;
import nc.bs.sscivm.util.IVMSagaValidationUtils;
import nc.jdbc.framework.page.LimitSQLBuilder;
import nc.jdbc.framework.page.SQLBuilderFactory;
import nc.jdbc.framework.processor.BaseProcessor;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pubitf.setting.defaultdata.OrgSettingAccessor;
import nc.ui.querytemplate.querytree.IQueryScheme;
import nc.vo.bd.material.measdoc.MeasdocVO;
import nc.vo.pf.pub.util.SQLUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDouble;
import nc.vo.sscivm.ivsale.IVApplicationAggVO;
import nc.vo.sscivm.ivsale.IVApplicationHeadVO;
import nc.vo.sscivm.ivsale.IVApplicationRelationVO;
import nc.vo.sscivm.ivsale.IVApplogVO;
import nccloud.itf.sscivm.ivsale.service.IVApplicationQueryService;

public class IVApplicationQueryServiceImpl implements IVApplicationQueryService {
    private static final String TS = "ts";
    private static final String PKS = "pks";
    private BaseDAO baseDAO = new BaseDAO();
    private static Map<String, Map<String, String>> PUBLISHAPPMAP = new HashMap();

    public IVApplicationQueryServiceImpl() {
    }

    private BaseDAO getBaseDAO() {
        return this.baseDAO;
    }

    public IVApplicationAggVO queryByPK(String pk) throws BusinessException {
        return (new IVApplicationQueryBP()).getAggIVApplicationVOByPK(pk);
    }

    public IVApplicationAggVO queryByPK(String pk, boolean checkSaga) throws BusinessException {
        if (checkSaga) {
            IVMSagaValidationUtils.checkSagaStatus(pk, IVApplicationHeadVO.getDefaultTableName(), "pk_ivapplication");
        }

        return (new IVApplicationQueryBP()).getAggIVApplicationVOByPK(pk);
    }

    public IVApplicationAggVO[] queryAggVOsByPks(String[] pks) throws BusinessException {
        return (new IVApplicationQueryBP()).queryAggIVApplicationVOByCondition(SQLUtil.buildSqlForIn("pk_ivapplication", pks));
    }

    public IVApplicationAggVO[] queryAggVOsByPks(String[] pks, boolean checkSaga) throws BusinessException {
        if (checkSaga) {
            IVMSagaValidationUtils.checkSagaStatus(pks, IVApplicationHeadVO.getDefaultTableName(), "pk_ivapplication");
        }

        return (new IVApplicationQueryBP()).queryAggIVApplicationVOByCondition(SQLUtil.buildSqlForIn("pk_ivapplication", pks));
    }

    public IVApplicationAggVO[] queryAggVOsByCondition(String condition) throws BusinessException {
        return (new IVApplicationQueryBP()).queryAggIVApplicationVOByCondition(condition);
    }

    public Map<String, List<String>> queryApplicationPksBySchema(IQueryScheme queryscheme, String appcode, Boolean sgbzflag) throws BusinessException {
        if (queryscheme == null) {
            return null;
        } else {
            String queryCondition = queryscheme.getWhereSQLOnly();
            Map<String, List<String>> pkAndTsList = null;
            if (!queryCondition.isEmpty()) {
                String tradetype = this.getTradetypeByApp(appcode);
                if ("SSCIVA-kpsq".equals(tradetype)) {
                    queryCondition = "(" + queryCondition + ")";
                } else {
                    queryCondition = "(" + queryCondition + " and transtypecode = '" + tradetype + "')";
                }

                if (sgbzflag != null) {
                    if (sgbzflag) {
                        queryCondition = queryCondition + " and sgbz ='Y' ";
                    } else {
                        queryCondition = queryCondition + " and (sgbz='N' or isnull(sgbz,'~')='~') ";
                    }
                }

                String sql = this.buildQuerySql(queryCondition);
                pkAndTsList = (Map) this.getBaseDAO().executeQuery(sql, new BaseProcessor() {
                    private static final long serialVersionUID = 1L;
                    Map<String, List<String>> result = new HashMap();
                    List<String> pkList = new ArrayList();
                    List<String> tsList = new ArrayList();

                    public Object processResultSet(ResultSet paramResultSet) throws SQLException {
                        while (paramResultSet.next()) {
                            this.pkList.add((String) paramResultSet.getObject("pk_ivapplication"));
                            this.tsList.add((String) paramResultSet.getObject("ts"));
                        }

                        this.result.put("pks", this.pkList);
                        this.result.put("ts", this.tsList);
                        return this.result;
                    }
                });
            }

            return pkAndTsList;
        }
    }

    private String buildQuerySql(String queryCondition) {
        StringBuilder sql = new StringBuilder("SELECT * ");
        sql.append("from " + IVApplicationHeadVO.getDefaultTableName() + " where ");
        String var10000 = sql.toString();
        return var10000 + queryCondition + " and dr = 0 order by preparedate desc, billno desc";
    }

    public String getDefaultOrgUnit() throws Exception {
        return OrgSettingAccessor.getDefaultOrgUnit();
    }

    public List<IVApplicationHeadVO> queryApplicationsBySchema(IQueryScheme queryscheme, String pageSize, String appcode, Boolean sgbzflag) throws BusinessException {
        if (queryscheme == null) {
            return null;
        } else {
            StringBuilder sql = new StringBuilder();
            String queryCondition = queryscheme.getWhereSQLOnly();
            String tradetype = this.getTradetypeByApp(appcode);
            if ("SSCIVA-kpsq".equals(tradetype)) {
                queryCondition = "(" + queryCondition + ")";
            } else {
                queryCondition = "(" + queryCondition + " and transtypecode = '" + tradetype + "')";
            }

            if (sgbzflag != null) {
                if (sgbzflag) {
                    queryCondition = queryCondition + " and sgbz ='Y'  ";
                } else {
                    queryCondition = queryCondition + " and (sgbz='N' or isnull(sgbz,'~')='~')  ";
                }
            }

            List<IVApplicationHeadVO> applicationHeadVOList = null;
            if (null != queryCondition && !queryCondition.isEmpty()) {
                LimitSQLBuilder limitSQLBuilder = SQLBuilderFactory.getInstance().createLimitSQLBuilder(this.getBaseDAO().getDBType());
                sql.append(limitSQLBuilder.build(this.buildQuerySql(queryCondition), 1, Integer.valueOf(pageSize)));
                applicationHeadVOList = (List) this.getBaseDAO().executeQuery(sql.toString(), new BeanListProcessor(IVApplicationHeadVO.class));
            }

            if (applicationHeadVOList != null && applicationHeadVOList.size() > Integer.parseInt(pageSize)) {
                applicationHeadVOList = applicationHeadVOList.subList(0, Integer.parseInt(pageSize));
            }

            return applicationHeadVOList;
        }
    }

    public List<IVApplicationHeadVO> queryApplicationsBySchema(IQueryScheme queryscheme, String pageSize, String appcode, Boolean sgbzflag, Boolean pageControl) throws BusinessException {
        if (queryscheme == null) {
            return null;
        } else {
            StringBuilder sql = new StringBuilder();
            String queryCondition = queryscheme.getWhereSQLOnly();
            String tradetype = this.getTradetypeByApp(appcode);
            if ("SSCIVA-kpsq".equals(tradetype)) {
                queryCondition = "(" + queryCondition + ")";
            } else {
                queryCondition = "(" + queryCondition + " and transtypecode = '" + tradetype + "')";
            }

            if (sgbzflag != null) {
                if (sgbzflag) {
                    queryCondition = queryCondition + " and sgbz ='Y'  ";
                } else {
                    queryCondition = queryCondition + " and (sgbz='N' or isnull(sgbz,'~')='~')  ";
                }
            }

            List<IVApplicationHeadVO> applicationHeadVOList = null;
            // 如果pageControl 为false 那么不走分页的逻辑
            if (null != queryCondition && !queryCondition.isEmpty()) {
                if (pageControl) {
                    LimitSQLBuilder limitSQLBuilder = SQLBuilderFactory.getInstance().createLimitSQLBuilder(this.getBaseDAO().getDBType());
                    sql.append(limitSQLBuilder.build(this.buildQuerySql(queryCondition), 1, Integer.valueOf(pageSize)));
                }
                applicationHeadVOList = (List) this.getBaseDAO().executeQuery(this.buildQuerySql(queryCondition).toString(), new BeanListProcessor(IVApplicationHeadVO.class));
            }

            if (applicationHeadVOList != null && applicationHeadVOList.size() > Integer.parseInt(pageSize)) {
                if (!pageControl) {
                    return applicationHeadVOList;
                }
                applicationHeadVOList = applicationHeadVOList.subList(0, Integer.parseInt(pageSize));
            }

            return applicationHeadVOList;
        }
    }

    public IVApplicationHeadVO[] queryHeadVOsByFpdmFphm(String fpdm, String fphm) throws BusinessException {
        StringBuilder querySql = new StringBuilder("select DISTINCT " + IVApplicationHeadVO.getDefaultTableName() + ".*  from ");
        String var10001 = IVApplogVO.getDefaultTableName();
        querySql.append(var10001 + ", " + IVApplicationHeadVO.getDefaultTableName());
        var10001 = IVApplicationHeadVO.getDefaultTableName();
        querySql.append(" where " + var10001 + ".dr =0 and (" + IVApplicationHeadVO.getDefaultTableName() + ".pk_ivapplication=" + IVApplogVO.getDefaultTableName() + ".lyid or " + IVApplicationHeadVO.getDefaultTableName() + ".pk_ivapplication in ( select ron.pk_ivapplication from " + IVApplicationRelationVO.getDefaultTableName() + " ron  where ron.fpqqlsh = " + IVApplogVO.getDefaultTableName() + ".lyid)) and " + IVApplogVO.getDefaultTableName() + ".fphm ='" + fphm + "' and " + IVApplogVO.getDefaultTableName() + ".dr=0 ");
        if (fpdm != null) {
            var10001 = IVApplogVO.getDefaultTableName();
            querySql.append(" and " + var10001 + ".fpdm ='" + fpdm + "' ");
        }

        List<IVApplicationHeadVO> ivApplicationHeadVOList = (List) this.getBaseDAO().executeQuery(querySql.toString(), new BeanListProcessor(IVApplicationHeadVO.class));
        return ivApplicationHeadVOList != null && ivApplicationHeadVOList.size() != 0 ? (IVApplicationHeadVO[]) ivApplicationHeadVOList.toArray(new IVApplicationHeadVO[ivApplicationHeadVOList.size()]) : null;
    }

    // 根据筛选出的开票申请单的主键查询开票记录
    public List<IVApplogVO> queryByInvoiceNumberAndAggPK(String[] pks, String[] invoiceDate, String[] invoiceNums) throws BusinessException {
        StringBuilder sql = new StringBuilder("select lyid from " + IVApplogVO.getDefaultTableName() + " where 1=1");
        String invoiceDateStr, pkStr, invoiceNumStr;
        if (pks != null && pks.length > 0) {
            pkStr = SQLUtil.buildSqlForIn("lyid", pks);
            sql.append(" and ").append(pkStr);
        }
        if (invoiceDate != null && invoiceDate.length > 0) {
            invoiceDateStr = " KPRQ >= '" + invoiceDate[0] + "'" + " and KPRQ <=" + "'" + invoiceDate[1] + "'";
            sql.append(" and ").append(invoiceDateStr);
        }
        if (invoiceNums != null && invoiceNums.length > 0) {
            invoiceNumStr = SQLUtil.buildSqlForIn("FPHM", invoiceNums);
            sql.append(" and ").append(invoiceNumStr);
        }
        return (List<IVApplogVO>) this.getBaseDAO().executeQuery(sql.toString(), new BeanListProcessor(IVApplogVO.class));
    }

    public List<IVApplicationHeadVO> queryHeadVOsByPks(String[] pks) throws BusinessException {
        List<IVApplicationHeadVO> applicationHeadVOList = this.queryHeadVOsByPks(pks, (Boolean) null);
        return applicationHeadVOList;
    }

    public List<IVApplicationHeadVO> queryHeadVOsByPks(String[] pks, Boolean sgbzflag) throws BusinessException {
        String sqlcondition = "";
        if (sgbzflag != null) {
            if (sgbzflag) {
                sqlcondition = " sgbz ='Y' and  ";
            } else {
                sqlcondition = " (sgbz='N' or isnull(sgbz,'~')='~') and  ";
            }
        }

        List<IVApplicationHeadVO> applicationHeadVOList = (List) this.getBaseDAO().retrieveByClause(IVApplicationHeadVO.class, "dr = 0 and " + sqlcondition + SQLUtil.buildSqlForIn("pk_ivapplication", pks), "preparedate desc, billno desc");
        return applicationHeadVOList;
    }

    public MeasdocVO[] queryMeasdocByPk(String pk) throws BusinessException {
        String condition = " ( pk_measdoc ='" + pk + "')";
        BaseDAO dao = new BaseDAO();
        Collection<MeasdocVO> coll = dao.retrieveByClause(MeasdocVO.class, condition);
        return coll == null ? null : (MeasdocVO[]) coll.toArray(new MeasdocVO[0]);
    }

    public UFDouble queryTaxRateByMaterialPK(String pk) throws BusinessException {
        StringBuilder sql = new StringBuilder();
        sql.append("select taxrate from bd_taxrate where pk_taxcode in ");
        sql.append("(");
        sql.append("select pk_taxcode from bd_taxcode where mattaxes in ");
        sql.append("(");
        sql.append("select pk_mattaxes from bd_material where pk_material = '");
        sql.append(pk);
        sql.append("'))");
        String condition = sql.toString();
        List<Object> result = (List) this.getBaseDAO().executeQuery(condition, new ColumnListProcessor());
        return result != null && result.size() > 0 ? new UFDouble(result.get(0).toString()) : null;
    }

    private String getTradetypeByApp(String appcode) throws BusinessException {
        String tradetype = null;
        String pk_group = InvocationInfoProxy.getInstance().getGroupId();
        Map<String, String> map = (Map) PUBLISHAPPMAP.get(pk_group);
        if (map != null && map.size() > 0) {
            tradetype = (String) map.get(appcode);
        }

        if (tradetype == null) {
            StringBuilder condition = new StringBuilder();
            condition.append("select pk_billtypecode from pub_publishapp where publishappid =");
            condition.append("(");
            condition.append("select pk_appregister from sm_appregister where code = '" + appcode + "'");
            condition.append(")");
            tradetype = (String) this.getBaseDAO().executeQuery(condition.toString(), new ColumnProcessor());
        }

        if (tradetype == null && appcode != null && appcode.length() > 3) {
            appcode = appcode.substring(0, appcode.length() - 3);
            tradetype = this.getTradetypeByApp(appcode);
        }

        if (map == null) {
            map = new HashMap();
        }

        if (tradetype == null || tradetype.length() == 0) {
            tradetype = "SSCIVA-kpsq";
        }

        map.put(appcode, tradetype);
        PUBLISHAPPMAP.put(pk_group, map);
        return tradetype;
    }
}
