package com.steering.pss.sale.base;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import net.sf.json.JSONObject;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;

/**
 * 客户信息重生版
 *
 * @author WenHB
 * @date 2015-11-09
 */
public class CoreCustomerReborn extends DBCommon {

    /**
     * 查询基础信息
     *
     * @param name
     * @return
     */
    public CoreReturnObject queryBaseInfo(String name) {
        Object[] params = new Object[]{name};
        return this.getDataBySqlID("CoreCustomerReborn.queryBaseInfo", params);
    }

    /**
     * 获取树形结构
     *
     * @return
     */
    public CoreReturnObject queryTivCode() {
        return this.getDataBySqlID("CoreCustomerReborn.GetRegionTree");
    }

    /**
     * 查询客户基础信息
     *
     * @param custNm
     * @return
     */
    public CoreReturnObject queryCustomerInfo(String custNm, String saleOrg) {
        Object[] obj = new Object[]{custNm};
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.queryCustomerInfo");
        String str = "";
        if (saleOrg.equals("admin")) { // 管理员查看所有
            return this.getData(sql, new Object[]{custNm});
        } else if (saleOrg.equals("100102")) { // 国贸
            str = "  AND A.SALE_ORG IN ('100102')";
        } else {//销售钢贸天淮
            str = "  AND A.SALE_ORG IN ('100101', '100103', '100105')";
        }
        sql += str;
        return this.getData(sql, obj);
    }

    /**
     * 查询客户的订结信息
     *
     * @param custNo
     * @return
     */
    public CoreReturnObject queryCustomerOrderUnit(String custNo) {
        Object[] obj = new Object[]{custNo};
        return this.getDataBySqlID("CoreCustomerReborn.queryCustomerOrderUnit",
                obj);
    }

    /**
     * 查询客户收货信息
     *
     * @param custNo
     * @return
     */
    public CoreReturnObject queryCustomerReceiveUnit(String custNo) {
        Object[] obj = new Object[]{custNo};
        return this.getDataBySqlID(
                "CoreCustomerReborn.queryCustomerReceiveUnit", obj);
    }

    /**
     * 查询客户信息
     *
     * @param customerNm
     * @return
     */
    public CoreReturnObject queryCustomerList(String customerNm,
                                              String saleOrg) {
        Object[] obj = new Object[]{customerNm};
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.queryCustomerList");
        String str = "";
        if (saleOrg.equals("admin")) { // 管理员查看所有
            return this.getData(sql, new Object[]{customerNm});
        } else if (saleOrg.equals("100102")) { // 国贸
            str = "  AND D.SALE_ORG IN ('100102')";
        } else {//销售钢贸天淮
            str = "  AND D.SALE_ORG IN ('100101', '100103', '100105')";
        }
        sql += str;
        return this.getData(sql, obj);

    }

    /**
     * 获取订结信息记录
     *
     * @param custNo
     * @return
     */
    public CoreReturnObject queryCustomerOrderCount(String custNo) {
        Object[] obj = new Object[]{custNo};
        return this.getDataBySqlID("CoreCustomerReborn.queryCustomerOrderCount",
                obj);
    }

    /**
     * 获取收货信息记录
     *
     * @param custNo
     * @return
     */
    public CoreReturnObject queryCustomerReceiveCount(String custNo) {
        Object[] obj = new Object[]{custNo};
        return this.getDataBySqlID(
                "CoreCustomerReborn.queryCustomerReceiveCount", obj);
    }

    /**
     * 验证客户名称是否存在
     *
     * @param custNm
     * @return
     */
    public CoreReturnObject validateCustomerNm(String custNm) {
        Object[] obj = new Object[]{custNm};
        return this.getDataBySqlID("CoreCustomerReborn.validateCustomerNm",
                obj);
    }

    /**
     * 验证客户名称是否存在
     *
     * @param custNm
     * @return
     */
    public CoreReturnObject validateCustomerNmAndOrg(String custNm, String saleOrg) {
        Object[] obj = new Object[]{custNm, saleOrg};
        return this.getDataBySqlID("CoreCustomerReborn.validateCustomerNmAndOrg",
                obj);
    }

    /**
     * 新增客户信息
     *
     * @param parm
     * @param saleOrg
     * @return
     */
    public CoreReturnObject addCustomer(String parm, String saleOrg) {
        CoreReturnObject cro = new CoreReturnObject();
        JSONObject json = JSONObject.fromObject(parm);
        SlmBaseCustomerEntity sbc = (SlmBaseCustomerEntity) JSONObject
                .toBean(json, SlmBaseCustomerEntity.class);
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            //2021.1.16 解决客户名称重复时 不同销售组织新增
            String customerNo = isExistsCustomerNM(con, sbc.getCustomerNm());
            if (customerNo.equals("")) {
                // 生成客户代码
                customerNo = generateCustomerCode(con, sbc.getRegionNo());
                if (customerNo == null || customerNo.equals("")) {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("客户代码生成失败");
                    return cro;
                }
                sbc.setCustomerNo(customerNo);
                // 新增客户信息
                String sql = CoreXmlSqlParsersFactory
                        .getSql("CoreCustomerReborn.InsertCustomer");
                sql = EntityTool.fillSqlByEntity(sql, sbc);
                PreparedStatement ps = con.prepareStatement(sql);
                ps.executeUpdate();
                ps.close();
            }
            // 客户授权
            impowerSaleOrg(con, customerNo, saleOrg, sbc.getCreateName());
            // 插入用途表
            insertIntoCustomerUse(con, customerNo, saleOrg, sbc.getCreateName(),
                    "100204"); // 新增的客户都有“最终用户”的属性
            con.commit();
            cro.setV_errCode(0);
            cro.setResult(customerNo);
        } catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setV_errMsg(e.getMessage());
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 修改客户主记录信息
     *
     * @param parm
     * @param saleOrg
     * @return
     */
    public CoreReturnObject updateCustomer(String parm, String saleOrg) {
        CoreReturnObject cro = new CoreReturnObject();
        JSONObject json = JSONObject.fromObject(parm);
        SlmBaseCustomerEntity sbc = (SlmBaseCustomerEntity) JSONObject
                .toBean(json, SlmBaseCustomerEntity.class);
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            // 修改客户信息
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreCustomerReborn.UpdateCustomer");
            sql = EntityTool.fillSqlByEntity(sql, sbc);
            PreparedStatement ps = con.prepareStatement(sql);
            ps.executeUpdate();
            ps.close();
            // 客户授权
            impowerSaleOrg(con, sbc.getCustomerNo(), saleOrg,
                    sbc.getUpdateName());
            // 插入用途表
            insertIntoCustomerUse(con, sbc.getCustomerNo(), saleOrg,
                    sbc.getUpdateName(), "100204"); // 新增的客户都有“最终用户”的属性
            con.commit();
            cro.setV_errCode(0);
        } catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setV_errMsg(e.getMessage());
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 新增订结单位
     *
     * @param parm
     * @param saleOrg
     * @return
     */
    public CoreReturnObject addCustomerOrderUnit(String parm, String saleOrg) {
        CoreReturnObject cro = new CoreReturnObject();
        JSONObject json = JSONObject.fromObject(parm);
        SlmBaseOrderUnitEntity sbo = (SlmBaseOrderUnitEntity) JSONObject
                .toBean(json, SlmBaseOrderUnitEntity.class);
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            // 新增订结信息
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreCustomerReborn.InsertCustomerOrderUnit");
            sql = EntityTool.fillSqlByEntity(sql, sbo);
            PreparedStatement ps = con.prepareStatement(sql);
            ps.executeUpdate();
            ps.close();
            // 插入用途表
            insertIntoCustomerUse(con, sbo.getCustomerNo(), saleOrg,
                    sbo.getCreateName(), "100202"); // 对于订结单位 只给与“结算单位”属性
            // 默认订货单位和结算单位属性 同时存在
            con.commit();
            cro.setV_errCode(0);
        } catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setV_errMsg(e.getMessage());
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 修改客户订结信息
     *
     * @param parm
     * @param saleOrg
     * @return
     */
    public CoreReturnObject updateCustomerOrderUnit(String parm,
                                                    String saleOrg) {
        CoreReturnObject cro = new CoreReturnObject();
        JSONObject json = JSONObject.fromObject(parm);
        SlmBaseOrderUnitEntity sbo = (SlmBaseOrderUnitEntity) JSONObject
                .toBean(json, SlmBaseOrderUnitEntity.class);
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            // 修改客户信息
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreCustomerReborn.UpdateCustomerOrderUnit");
            sql = EntityTool.fillSqlByEntity(sql, sbo);
            PreparedStatement ps = con.prepareStatement(sql);
            ps.executeUpdate();
            ps.close();
            // 插入用途表
            insertIntoCustomerUse(con, sbo.getCustomerNo(), saleOrg,
                    sbo.getUpdateName(), "100202"); // 新增的客户都有“最终用户”的属性
            con.commit();
            cro.setV_errCode(0);
        } catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setV_errMsg(e.getMessage());
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 新增客户收货信息
     *
     * @param parm
     * @param saleOrg
     * @return
     */
    public CoreReturnObject addCustomerReceiveUnit(String parm,
                                                   String saleOrg) {
        CoreReturnObject cro = new CoreReturnObject();
        JSONObject json = JSONObject.fromObject(parm);
        SlmBaseReceivUnitEntity sbr = (SlmBaseReceivUnitEntity) JSONObject
                .toBean(json, SlmBaseReceivUnitEntity.class);
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            // 新增收货信息
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreCustomerReborn.InsertCustomerReceiveUnit");
            sql = EntityTool.fillSqlByEntity(sql, sbr);
            PreparedStatement ps = con.prepareStatement(sql);
            ps.executeUpdate();
            ps.close();
            // 插入用途表
            insertIntoCustomerUse(con, sbr.getCustomerNo(), saleOrg,
                    sbr.getCreateName(), "100203"); // “收货单位”属性
            con.commit();
            cro.setV_errCode(0);
        } catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setV_errMsg(e.getMessage());
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 修改客户的收货信息
     *
     * @param parm
     * @param saleOrg
     * @return
     */
    public CoreReturnObject updateCustomerReceiveUnit(String parm,
                                                      String saleOrg) {
        CoreReturnObject cro = new CoreReturnObject();
        JSONObject json = JSONObject.fromObject(parm);
        SlmBaseReceivUnitEntity sbr = (SlmBaseReceivUnitEntity) JSONObject
                .toBean(json, SlmBaseReceivUnitEntity.class);
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            // 修改客户信息
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreCustomerReborn.UpdateCustomerReceiveUnit");
            sql = EntityTool.fillSqlByEntity(sql, sbr);
            PreparedStatement ps = con.prepareStatement(sql);
            ps.executeUpdate();
            ps.close();
            // 插入用途表
            insertIntoCustomerUse(con, sbr.getCustomerNo(), saleOrg,
                    sbr.getUpdateName(), "100203"); // 新增的客户都有“最终用户”的属性
            con.commit();
            cro.setV_errCode(0);
        } catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setV_errMsg(e.getMessage());
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 删除客户信息
     *
     * @param custNo
     * @param name
     * @return
     */
    public CoreReturnObject deleteCustomerBaseInfo(String custNo, String name) {

        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.deleteCustomerBaseInfo"));
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.deleteCustomerOrderUnit"));
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.deleteCustomerReceiveUnit"));
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.deleteCustomerUseAll"));

        parmlist.add(new Object[]{name, custNo});
        parmlist.add(new Object[]{custNo});
        parmlist.add(new Object[]{custNo});
        parmlist.add(new Object[]{name});

        return this.getDao(CoreConstantData.sysbeanstr)
                .ExcuteTransction(sqllist, parmlist);
    }

    /**
     * 删除客户订结信息
     *
     * @param custNo
     * @param name
     * @return
     */
    public CoreReturnObject deleteCustomerOrderUnit(String custNo) {
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.deleteCustomerOrderUnit"));
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.deleteCustomerUse"));
        parmlist.add(new Object[]{custNo});
        parmlist.add(new Object[]{custNo, "100202"});

        return this.getDao(CoreConstantData.sysbeanstr)
                .ExcuteTransction(sqllist, parmlist);
    }

    /**
     * 删除客户的收货信息
     *
     * @param custNo
     * @param name
     * @return
     */
    public CoreReturnObject deleteCustomerReveciveUnit(String custNo) {
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.deleteCustomerReceiveUnit"));
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.deleteCustomerUse"));
        parmlist.add(new Object[]{custNo});
        parmlist.add(new Object[]{custNo, "100203"});

        return this.getDao(CoreConstantData.sysbeanstr)
                .ExcuteTransction(sqllist, parmlist);
    }

    /**
     * 生成客户代码
     *
     * @param con
     * @param regionNo
     * @return
     * @throws SQLException
     */
    public String generateCustomerCode(Connection con, String regionNo)
            throws SQLException {

        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.generateCustomerCode");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, regionNo);
        ps.setObject(2, regionNo);
        ps.setObject(3, regionNo);
        ps.setObject(4, regionNo);
        ps.setObject(5, regionNo);
        ResultSet rs = ps.executeQuery();
        String code = "";
        if (rs.next()) {
            code = rs.getString(1);
        }
        rs.close();
        ps.close();
        return code;
    }

    /**
     * 新增修改用户时 授权销售组织
     *
     * @param con
     * @param customerNo
     * @param saleOrg
     * @param name
     * @throws SQLException
     */
    public void impowerSaleOrg(Connection con, String customerNo,
                               String saleOrg, String name) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.clearExistsSaleOrg");
        String sql1 = CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.impowerSaleOrg");
        PreparedStatement ps = con.prepareStatement(sql);
        if (saleOrg.equals("100101") || saleOrg.equals("100103") || saleOrg.equals("100105")) { // 销售 钢贸 天淮
            ps.setObject(1, customerNo);
            ps.setObject(2, "100101");
            ps.setObject(3, "100103");
            ps.setObject(4, "100105");
            ps.executeUpdate();
            ps.close();
            // 插入授权表
            ps = con.prepareStatement(sql1);
            ps.setObject(1, customerNo);
            ps.setObject(2, "100101");
            ps.setObject(3, name);
            ps.executeUpdate();
            ps.close();
            ps = con.prepareStatement(sql1);
            ps.setObject(1, customerNo);
            ps.setObject(2, "100103");
            ps.setObject(3, name);
            ps.executeUpdate();
            ps.close();
            ps = con.prepareStatement(sql1);
            ps.setObject(1, customerNo);
            ps.setObject(2, "100105");
            ps.setObject(3, name);
            ps.executeUpdate();
            ps.close();

        } else if (saleOrg.equals("100102")) { // 国贸
            ps.setObject(1, customerNo);
            ps.setObject(2, "100102");
            ps.setObject(3, "100102");
            ps.setObject(4, "100102");
            ps.executeUpdate();
            ps.close();
            // 插入授权表
            ps = con.prepareStatement(sql1);
            ps.setObject(1, customerNo);
            ps.setObject(2, "100102");
            ps.setObject(3, name);
            ps.executeUpdate();
            ps.close();
        }

    }

    /**
     * 插入用途表
     *
     * @param con
     * @param customerNo
     * @param saleOrg
     * @param name
     * @param use
     * @throws SQLException
     */
    public void insertIntoCustomerUse(Connection con, String customerNo,
                                      String saleOrg, String name, String use) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.insertCustomerUse");
        if (saleOrg.equals("100101") || saleOrg.equals("100103") || saleOrg.equals("100105")) {
            if (!isExistsCustomerUsr(con, customerNo, "100101", use)) {
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setObject(1, customerNo);
                ps.setObject(2, "100101");
                ps.setObject(3, use);
                ps.setObject(4, name);
                ps.executeUpdate();
                ps.close();
            }

            if (!isExistsCustomerUsr(con, customerNo, "100103", use)) {
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setObject(1, customerNo);
                ps.setObject(2, "100103");
                ps.setObject(3, use);
                ps.setObject(4, name);
                ps.executeUpdate();
                ps.close();
            }
            if (!isExistsCustomerUsr(con, customerNo, "100105", use)) {
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setObject(1, customerNo);
                ps.setObject(2, "100105");
                ps.setObject(3, use);
                ps.setObject(4, name);
                ps.executeUpdate();
                ps.close();
            }
        } else if (saleOrg.equals("100102")) {
            if (!isExistsCustomerUsr(con, customerNo, "100102", use)) {
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setObject(1, customerNo);
                ps.setObject(2, "100102");
                ps.setObject(3, use);
                ps.setObject(4, name);
                ps.executeUpdate();
                ps.close();
            }
        }

    }

    /**
     * 用途表是否存在记录
     *
     * @param con
     * @param customerNo
     * @param saleOrg
     * @param use
     * @return
     * @throws SQLException
     */
    public Boolean isExistsCustomerUsr(Connection con, String customerNo,
                                       String saleOrg, String use) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.queryCustomerUse");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, customerNo);
        ps.setObject(2, saleOrg);
        ps.setObject(3, use);
        ResultSet rs = ps.executeQuery();
        String result = "";
        if (rs.next()) {
            result = rs.getString(1);
        }
        if (result == null || result.equals("")) {
            return false;
        }
        return true;
    }

    public String isExistsCustomerNM(Connection con, String customerNM) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreCustomerReborn.validateCustomerNm");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, customerNM);
        ResultSet rs = ps.executeQuery();
        String result = "";
        if (rs.next()) {
            result = rs.getString(1);
        }
        return result;
    }

}
