com.belle.yitiansystem.merchant.service.impl.MerchantsService.java Source code

Java tutorial

Introduction

Here is the source code for com.belle.yitiansystem.merchant.service.impl.MerchantsService.java

Source

package com.belle.yitiansystem.merchant.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Order;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.type.Type;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import com.belle.finance.costsettlement.costsetofbooks.model.vo.CostSetofBooks;
import com.belle.infrastructure.constant.Constant;
import com.belle.infrastructure.orm.basedao.CritMap;
import com.belle.infrastructure.orm.basedao.PageFinder;
import com.belle.infrastructure.orm.basedao.Query;
import com.belle.infrastructure.util.GetSessionUtil;
import com.belle.infrastructure.util.JDBCUtils;
import com.belle.infrastructure.util.Md5Encrypt;
import com.belle.infrastructure.util.UUIDGenerator;
import com.belle.infrastructure.util.UUIDUtil;
import com.belle.infrastructure.util.XmlTool;
import com.belle.other.dao.impl.SupplierContactDaoImpl;
import com.belle.other.dao.impl.SupplierContractDaoImpl;
import com.belle.other.model.pojo.SupplierContactSp;
import com.belle.other.model.pojo.SupplierContract;
import com.belle.other.model.pojo.SupplierSp;
import com.belle.other.service.ISqlService;
import com.belle.other.util.CodeGenerate;
import com.belle.yitiansystem.merchant.dao.impl.MerchantConsumableDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.MerchantExpressTemplateDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.MerchantGrantConsumableDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.MerchantRejectedAddressDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.MerchantUserDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.MerchantsAuthorityDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.MerchantsRoleDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.RoleAuthorityDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.SpLimitBrandDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.SpLimitCatDaoImpl;
import com.belle.yitiansystem.merchant.dao.impl.UserAuthorityDaoImpl;
import com.belle.yitiansystem.merchant.model.pojo.MerchantExpressTemplate;
import com.belle.yitiansystem.merchant.model.pojo.MerchantOperationLog;
import com.belle.yitiansystem.merchant.model.pojo.MerchantOperationLog.OperationType;
import com.belle.yitiansystem.merchant.model.pojo.MerchantRejectedAddress;
import com.belle.yitiansystem.merchant.model.pojo.MerchantUser;
import com.belle.yitiansystem.merchant.model.pojo.MerchantsAuthority;
import com.belle.yitiansystem.merchant.model.pojo.MerchantsRole;
import com.belle.yitiansystem.merchant.model.pojo.RoleAuthority;
import com.belle.yitiansystem.merchant.model.pojo.SpLimitBrand;
import com.belle.yitiansystem.merchant.model.pojo.SpLimitCat;
import com.belle.yitiansystem.merchant.model.pojo.UserRole;
import com.belle.yitiansystem.merchant.model.vo.MerchantsVo;
import com.belle.yitiansystem.merchant.service.IMerchantOperationLogService;
import com.belle.yitiansystem.merchant.service.IMerchantsService;
import com.belle.yitiansystem.merchant.service.ISupplierYgContactService;
import com.belle.yitiansystem.systemmgmt.dao.ISystemmgtUserDao;
import com.belle.yitiansystem.systemmgmt.model.pojo.SystemmgtUser;
import com.yougou.component.area.api.IAreaApi;
import com.yougou.component.area.model.Area;
import com.yougou.kaidian.common.commodity.pojo.Cat;
import com.yougou.kaidian.common.constant.CacheConstant;
import com.yougou.kaidian.common.vo.AuthorityComparator;
import com.yougou.kaidian.common.vo.MerchantsAuthorityVo;
import com.yougou.merchant.api.supplier.service.ISupplierService;
import com.yougou.merchant.api.supplier.vo.SupplierVo;
import com.yougou.pc.api.ICommodityBaseApiService;
import com.yougou.pc.model.brand.Brand;
import com.yougou.pc.model.category.Category;
import com.yougou.purchase.api.IPurchaseApiService;
import com.yougou.purchase.model.SupplierContact;

/**
 * 
 * -?service
 * 
 * @author wang.m
 * @date 2012-03-05
 * 
 */
@Service
public class MerchantsService implements IMerchantsService {
    @Resource
    private ISqlService sqlService;
    @Resource
    private SupplierContactDaoImpl SupplierContactDaoImpl;
    @Resource
    private ISystemmgtUserDao userDao;
    /*@Resource
    private SupplierDaoImpl supplierDaoImpl;*/
    // ??
    @Resource
    private SupplierContractDaoImpl supplierContractDaoImpl;
    @Resource
    private MerchantUserDaoImpl merchantUserDaoImpl;
    @Resource
    private SpLimitCatDaoImpl spLimitCatDaoImpl;
    @Resource
    private SpLimitBrandDaoImpl spLimitBrandDaoImpl;

    // ???
    @Resource
    private MerchantsAuthorityDaoImpl merchantsAuthorityDaoImpl;
    // 
    @Resource
    private MerchantsRoleDaoImpl merchantsRoleDaoImpl;
    @Resource
    private RoleAuthorityDaoImpl roleAuthorityDaoImpl;
    /*@Resource
    private ICostSetOfBooksDao costSetOfBooksDao;*/
    @Resource
    private MerchantConsumableDaoImpl merchantConsumableDaoImpl;
    @Resource
    private MerchantGrantConsumableDaoImpl merchantGrantConsumableDaoImpl;
    @Resource
    private MerchantExpressTemplateDaoImpl merchantExpressTemplateDaoImpl;
    @Resource
    private MerchantRejectedAddressDaoImpl merchantRejectedAddressDaoImpl;

    @Resource
    private IMerchantOperationLogService merchantOperationLogService;

    @Resource
    private ICommodityBaseApiService commodityBaseApiService;
    @Resource
    private ISupplierService supplierService;
    @Resource
    private UserAuthorityDaoImpl userAuthorityDao;
    @Resource
    private ISupplierYgContactService supplierYgContactService;

    private Logger logger = Logger.getLogger(MerchantsService.class);

    @Resource
    private IAreaApi areaApi;
    @Resource
    private IPurchaseApiService purchaseApiService;
    @Resource
    private com.belle.yitiansystem.merchant.dao.mapper.MerchantBrandMapper merchantBrandMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * ?????
     * 
     * @author wang.m
     * @Date 2012-03-05
     */
    @Deprecated
    public PageFinder<Map<String, Object>> queryMerchantsList(Query query, MerchantsVo merchantsVo) {
        String sql = "SELECT DISTINCT t1.id,t1.supplier,t1.supplier_code,t1.coupons_allocation_proportion,"
                + "t1.is_valid,t1.update_date,t1.update_user,t1.inventory_code,is_input_yougou_warehouse"
                + " FROM tbl_sp_supplier t1 LEFT JOIN tbl_sp_limit_brand t2 ON t1.id = t2.supply_id"
                + " LEFT JOIN tbl_commodity_brand t3 ON t2.brand_no = t3.brand_no"
                + " WHERE supplier_type='' AND t1.delete_flag=1 ";

        // ?
        if (merchantsVo != null) {
            if (StringUtils.isNotBlank(merchantsVo.getSupplier())) {// ??
                sql += " AND t1.supplier LIKE '%" + merchantsVo.getSupplier().trim() + "%'";
            }
            if (StringUtils.isNotBlank(merchantsVo.getBrandName())) {
                sql += " AND t3.brand_name LIKE '%" + merchantsVo.getBrandName().trim() + "%'";
            }
            if (StringUtils.isNotBlank(merchantsVo.getSupplierCode())) {// ?
                sql += " AND t1.supplier_code LIKE '" + merchantsVo.getSupplierCode().trim() + "%'";
            }
            if (null != merchantsVo.getIsValid() && merchantsVo.getIsValid() != 0) {// ?
                sql += " AND t1.is_valid= " + merchantsVo.getIsValid();
            }
            if (null != merchantsVo.getIsInputYougouWarehouse()) {// 
                sql += " AND t1.is_input_yougou_warehouse= " + merchantsVo.getIsInputYougouWarehouse();
            }
        }
        sql += " ORDER BY t1.update_date DESC";
        PageFinder<Map<String, Object>> pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);
        return pageFinder;
    }

    /**
     * ?ID??
     * @param merchantId
     * @return
     */
    /*public List<Brand> getMerchantBrandListByMerchantId(String merchantId){
       final String sql = "SELECT t2.brand_no,t2.brand_name FROM tbl_sp_limit_brand t1 INNER JOIN tbl_commodity_brand t2 ON t1.brand_no = t2.brand_no WHERE t1.supply_id = '"+merchantId+"'";
       List<Map<String, Object>> lstBrand = sqlService.getDatasBySql(sql);
       List<Brand> lstBrandResult = new ArrayList<Brand>(0);
       for(Map<String, Object> mapBrand : lstBrand) {
     Brand brand = new Brand();
     brand.setBrandNo(mapBrand.get("brand_no")!=null?mapBrand.get("brand_no").toString():"");
     brand.setBrandName(mapBrand.get("brand_name")!=null?mapBrand.get("brand_name").toString():"");
     lstBrandResult.add(brand);
     brand = null;
       }
       return lstBrandResult;
    }*/

    /**
     * ?ID?
     * 
     * @author wang.m
     * @Date 2012-03-05
     */
    @Deprecated
    public PageFinder<Map<String, Object>> querySupplierContactSpList(Query query, MerchantsVo merchantsVo,
            String supplierId) {
        String sql = "SELECT t2.id,t1.supplier,t1.supplier_code,t2.contact,t2.type,t2.tele_phone,t2.mobile_phone,"
                + " t2.fax,t2.email,t2.address FROM tbl_sp_supplier t1 "
                + " INNER JOIN tbl_sp_supplier_contact t2 WHERE t1.id=t2.supply_id and t1.delete_flag=1 ";
        // ?
        if (StringUtils.isNotBlank(supplierId)) {
            // ID
            sql += " and t1.id='" + supplierId.trim() + "'";
        }
        // ?
        if (merchantsVo != null) {
            // ??
            if (StringUtils.isNotBlank(merchantsVo.getSupplier())) {
                sql += " and t1.supplier like '" + merchantsVo.getSupplier().trim() + "%'";
            }
            // ?
            if (StringUtils.isNotBlank(merchantsVo.getSupplierCode())) {
                sql += " and t1.supplier_code like '" + merchantsVo.getSupplierCode().trim() + "%'";
            }
            // ??
            if (StringUtils.isNotBlank(merchantsVo.getContact())) {
                sql += " and t2.contact like '" + merchantsVo.getContact().trim() + "%'";
            }
            // ??
            if (StringUtils.isNotBlank(merchantsVo.getMobilePhone())) {
                sql += " and t2.mobile_phone like '" + merchantsVo.getMobilePhone().trim() + "%'";
            }
            // ?
            if (StringUtils.isNotBlank(merchantsVo.getEmail())) {
                sql += " and t2.email like '" + merchantsVo.getEmail().trim() + "%'";
            }
        }
        sql += " ORDER BY t1.update_date DESC";
        PageFinder<Map<String, Object>> pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);
        return pageFinder;
    }

    /**
     * ?ID??
     * 
     * @author wang.m
     * @Date 2012-03-05
     */
    @Deprecated
    public PageFinder<Map<String, Object>> querysupplierContractList(Query query, MerchantsVo merchantsVo,
            String supplierId) {
        String sql = "SELECT t2.id,t2.contract_no,t1.is_valid,t1.supplier,t1.supplier_code,t2.clearing_form,t2.effective_date,"
                + " t2.failure_date,t2.update_time,t2.update_user,t2.attachment FROM tbl_sp_supplier t1 "
                + " INNER JOIN tbl_sp_supplier_contract t2 WHERE t1.id=t2.supplier_id and t1.delete_flag=1 ";
        // ?
        if (StringUtils.isNotBlank(supplierId)) {
            // ID
            sql += " and t1.id='" + supplierId.trim() + "'";

        }
        // ?
        if (merchantsVo != null) {
            // ??
            if (StringUtils.isNotBlank(merchantsVo.getSupplier())) {
                sql += " and t1.supplier like '" + merchantsVo.getSupplier().trim() + "%'";
            }
            // ?
            if (StringUtils.isNotBlank(merchantsVo.getSupplierCode())) {
                sql += " and t1.supplier_code like '" + merchantsVo.getSupplierCode().trim() + "%'";
            }
            // ???
            if (StringUtils.isNotBlank(merchantsVo.getContractNo())) {
                sql += " and t2.contract_no like '" + merchantsVo.getContractNo().trim() + "%'";
            }
            // ?
            if (null != merchantsVo.getIsValid() && merchantsVo.getIsValid() != 0) {
                sql += " and t1.is_valid=" + merchantsVo.getIsValid();
            }
            // 
            if (StringUtils.isNotBlank(merchantsVo.getEffectiveDate())) {
                sql += " and t2.effective_date >'" + merchantsVo.getEffectiveDate().trim() + "'";
            }
            // 
            if (StringUtils.isNotBlank(merchantsVo.getFailureDate())) {
                sql += " and t2.failure_date <'" + merchantsVo.getFailureDate().trim() + "'";
            }
        }
        sql += " ORDER BY t2.update_time DESC";
        PageFinder<Map<String, Object>> pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);
        return pageFinder;
    }

    /**
     * 
     * ????
     * 
     * @param telePhone
     *            ?
     * @Date 2012-03-06
     * @author wang.m
     */
    @Override
    public boolean existsTelePhone(String telePhone) {
        if (StringUtils.isNotBlank(telePhone)) {
            String sql = "select count(t.id) from tbl_sp_supplier_contact t where t.tele_phone = '"
                    + telePhone.trim() + "'";
            Long count = sqlService.getCountBySql(sql, null, null);
            return count > 0;
        }
        return false;
    }

    /**
     * 
     * ???
     * 
     * @param email
     *            ?
     * @Date 2012-03-06
     * @author wang.m
     */
    public boolean existsEmail(String email) {
        if (StringUtils.isNotBlank(email)) {
            String sql = "select count(t.id) from tbl_sp_supplier_contact t where t.email = '" + email.trim() + "'";
            Long count = sqlService.getCountBySql(sql, null, null);
            return count > 0;
        }
        return false;
    }

    /**
     * 
     * ??
     * 
     * @Date 2012-03-06
     * @author wang.m
     * @throws Exception
     */
    @Transactional
    public boolean add_linkmanList(SupplierContactSp supplierContactSp, String suplierName, String operator)
            throws Exception {
        boolean bool = false;
        try {
            SupplierContactSp supplierSp = new SupplierContactSp();
            if (supplierContactSp != null) {
                SupplierSp SupplierSp = new SupplierSp();
                SupplierVo vo = supplierService.getSupplierByName(suplierName);
                BeanUtils.copyProperties(SupplierSp, vo);

                supplierSp.setSupplier(SupplierSp);
                supplierSp.setContact(supplierContactSp.getContact());// ??
                supplierSp.setTelePhone(supplierContactSp.getTelePhone());// ??
                supplierSp.setType(supplierContactSp.getType());// 
                supplierSp.setAddress(supplierContactSp.getAddress());
                supplierSp.setEmail(supplierContactSp.getEmail());
                supplierSp.setFax(supplierContactSp.getFax());
                supplierSp.setMobilePhone(supplierContactSp.getMobilePhone());
                SupplierContactDaoImpl.save(supplierSp);

                SupplierContact supplierContact = new SupplierContact();
                this.purchaseApiService.insertSupplierContact(supplierContact);

                /** ? Modifier by yang.mq **/
                MerchantOperationLog operationLog = new MerchantOperationLog();
                operationLog.setMerchantCode(SupplierSp.getSupplierCode());
                operationLog.setOperator(operator);
                operationLog.setOperated(new Date());
                operationLog.setOperationType(OperationType.CONTACT);
                operationLog.setOperationNotes(
                        merchantOperationLogService.buildMerchantContactOperationNotes(null, supplierSp));
                merchantOperationLogService.saveMerchantOperationLog(operationLog);

                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("??!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * 
     * ??
     * 
     * @Date 2012-03-06
     * @author wang.m
     * @throws Exception
     */
    @Transactional
    public boolean update_linkmanList(Query query, ModelMap modelMap, SupplierContactSp supplierContactSp,
            String suplierName, SystemmgtUser systemmgtUser) throws Exception {
        boolean bool = false;
        try {
            SupplierContactSp supplierSp = new SupplierContactSp();
            if (supplierContactSp != null) {
                // 
                //SupplierSp SupplierSp = supplierDaoImpl.findSupplierByName(suplierName);// ????
                SupplierSp SupplierSp = new SupplierSp();
                SupplierVo vo = supplierService.getSupplierByName(suplierName);
                BeanUtils.copyProperties(SupplierSp, vo);

                supplierSp.setSupplier(SupplierSp);
                supplierSp.setContact(supplierContactSp.getContact());// ??
                supplierSp.setTelePhone(supplierContactSp.getTelePhone());// ??
                supplierSp.setType(supplierContactSp.getType());// 
                supplierSp.setAddress(supplierContactSp.getAddress());
                supplierSp.setEmail(supplierContactSp.getEmail());
                supplierSp.setFax(supplierContactSp.getFax());
                supplierSp.setMobilePhone(supplierContactSp.getMobilePhone());
                supplierSp.setId(supplierContactSp.getId());

                SupplierContactSp supplierSpInfo = SupplierContactDaoImpl.getById(supplierContactSp.getId());
                String operationNotes = merchantOperationLogService
                        .buildMerchantContactOperationNotes(supplierSpInfo, supplierSp);

                SupplierContactDaoImpl.merge(supplierSp);

                if (StringUtils.isNotBlank(operationNotes)) {
                    /** ? Modifier by yang.mq **/
                    MerchantOperationLog operationLog = new MerchantOperationLog();
                    operationLog.setMerchantCode(SupplierSp.getSupplierCode());
                    operationLog.setOperator(systemmgtUser.getUsername());
                    operationLog.setOperated(new Date());
                    operationLog.setOperationType(OperationType.CONTACT);
                    operationLog.setOperationNotes(operationNotes);
                    merchantOperationLogService.saveMerchantOperationLog(operationLog);
                }

                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("??!", e);
            bool = false;
        }
        return bool;

    }

    /**
     * 
     * ???
     * 
     * @Date 2012-03-06
     * @author wang.m
     * @throws Exception
     */
    @Deprecated
    @Transactional
    public boolean add_supplierContract(Query query, ModelMap modelMap, String effective, String failure,
            SupplierContract supplierContract, String suplierName, HttpServletRequest req) throws Exception {
        boolean bool = false;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            SupplierContract contract = new SupplierContract();
            if (supplierContract != null) {
                // 
                //SupplierSp SupplierSp = this.findSupplierByName(suplierName);// ????
                SupplierSp SupplierSp = new SupplierSp();
                SupplierVo vo = supplierService.getSupplierByName(suplierName);
                BeanUtils.copyProperties(SupplierSp, vo);

                contract.setSupplier(SupplierSp);
                contract.setContractNo(supplierContract.getContractNo());// ???
                contract.setEffectiveDate(format.parse(effective));// 
                contract.setFailureDate(format.parse(failure));// ?
                contract.setClearingForm(supplierContract.getClearingForm());
                contract.setUpdateTime(formDate());// ?
                contract.setAttachment(supplierContract.getAttachment());// ??
                SystemmgtUser user = GetSessionUtil.getSystemUser(req);
                String loginUser = "";
                if (user != null) {
                    loginUser = user.getUsername();
                }
                contract.setUpdateUser(loginUser);// ?
                supplierContractDaoImpl.save(contract);

                /** ? Modifier by yang.mq **/
                MerchantOperationLog operationLog = new MerchantOperationLog();
                operationLog.setMerchantCode(SupplierSp.getSupplierCode());
                operationLog.setOperator(loginUser);
                operationLog.setOperated(new Date());
                operationLog.setOperationType(OperationType.CONTRACT);
                operationLog.setOperationNotes(
                        merchantOperationLogService.buildMerchantContractOperationNotes(null, contract));
                merchantOperationLogService.saveMerchantOperationLog(operationLog);

                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("???!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * 
     * ???
     * 
     * @Date 2012-03-06
     * @author wang.m
     * @throws Exception
     */
    @Deprecated
    @Transactional
    public boolean update_supplierContract(Query query, ModelMap modelMap, String effective, String failure,
            SupplierContract supplierContract, String suplierName, HttpServletRequest req) throws Exception {
        boolean bool = false;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            SupplierContract contract = new SupplierContract();
            if (supplierContract != null) {
                // 
                //SupplierSp SupplierSp = supplierDaoImpl.findSupplierByName(suplierName);// ????
                SupplierVo supplierInfo = supplierService.getSupplierByName(suplierName);
                SupplierSp SupplierSp = new SupplierSp();
                BeanUtils.copyProperties(SupplierSp, supplierInfo);

                contract.setSupplier(SupplierSp);
                contract.setContractNo(supplierContract.getContractNo());// ???
                contract.setEffectiveDate(format.parse(effective));// 
                contract.setFailureDate(format.parse(failure));// ?
                contract.setClearingForm(supplierContract.getClearingForm());
                contract.setUpdateTime(formDate());// ?
                contract.setAttachment(supplierContract.getAttachment());// ??
                SystemmgtUser user = GetSessionUtil.getSystemUser(req);
                String loginUser = "";
                if (user != null) {
                    loginUser = user.getUsername();
                }
                contract.setUpdateUser(loginUser);// ?
                if (StringUtils.isNotBlank(supplierContract.getId())) {
                    contract.setId(supplierContract.getId());
                }

                SupplierContract contractInfo = supplierContractDaoImpl.getById(supplierContract.getId());
                String operationNotes = merchantOperationLogService
                        .buildMerchantContractOperationNotes(contractInfo, contract);

                supplierContractDaoImpl.merge(contract);

                if (StringUtils.isNotBlank(operationNotes)) {
                    /** ? Modifier by yang.mq **/
                    MerchantOperationLog operationLog = new MerchantOperationLog();
                    operationLog.setMerchantCode(SupplierSp.getSupplierCode());
                    operationLog.setOperator(loginUser);
                    operationLog.setOperated(new Date());
                    operationLog.setOperationType(OperationType.CONTRACT);
                    operationLog.setOperationNotes(operationNotes);
                    merchantOperationLogService.saveMerchantOperationLog(operationLog);
                }

                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("???!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ?
     * 
     * @return List<SupplierSp>
     */
    public List<SupplierSp> getSupplies(String supplierspName) {
        List<SupplierSp> result = new ArrayList<SupplierSp>();
        /*CritMap critMap = new CritMap();
        critMap.addDesc("updateTimestamp");
        critMap.addEqual("supplierType", "");
        critMap.addEqual("deleteFlag", 1);//  1
        if (StringUtils.isNotBlank(supplierspName)) {
           critMap.addLike("supplierCode", supplierspName);
        }
        result = supplierDaoImpl.findByCritMap(critMap);
        */
        SupplierVo _vo = new SupplierVo();
        _vo.setSupplierType("");
        _vo.setSupplierCode(supplierspName);
        try {
            List<SupplierVo> list = supplierService.querySupplierByVo(_vo);

            if (CollectionUtils.isNotEmpty(list)) {
                SupplierSp supplier = null;
                for (SupplierVo supplierVo : list) {
                    supplier = new SupplierSp();
                    BeanUtils.copyProperties(supplier, supplierVo);
                    result.add(supplier);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 
     * ??ID??
     * 
     * @Date 2012-03-06
     * @author wang.m
     * @throws Exception
     */
    public SupplierContactSp initial_linkmanList(Query query, ModelMap modelMap, String id) {
        List<SupplierContactSp> result = new ArrayList<SupplierContactSp>();
        CritMap critMap = new CritMap();
        critMap.addEqual("id", id);
        critMap.addFech("supplier");
        result = SupplierContactDaoImpl.findByCritMap(critMap);
        SupplierContactSp supplierContactSp = null;
        if (result != null && result.size() > 0) {
            supplierContactSp = result.get(0);
        }
        return supplierContactSp;
    }

    /**
     * 
     * ???ID??
     * 
     * @Date 2012-03-06
     * @author wang.m
     * @throws Exception
     */
    public SupplierContract initial_supplierContract(Query query, ModelMap modelMap, String id) {
        List<SupplierContract> result = new ArrayList<SupplierContract>();
        CritMap critMap = new CritMap();
        critMap.addEqual("id", id);
        critMap.addFech("supplier");
        SupplierContract supplierContract = null;
        result = supplierContractDaoImpl.findByCritMap(critMap);
        if (result != null && result.size() > 0) {
            supplierContract = result.get(0);
        }
        return supplierContract;
    }

    /**
     * 
     * ????
     * 
     * @Date 2012-03-07
     * @author wang.m
     */
    public boolean exitsLoginAccount(String loginAccount) {
        // ?
        if (StringUtils.isNotBlank(loginAccount)) {
            CritMap critMap = new CritMap();
            critMap.addEqual("loginName", loginAccount.trim());
            critMap.addEqual("deleteFlag", 1);//  1
            List<MerchantUser> merchantUser = merchantUserDaoImpl.findByCritMap(critMap);
            if (merchantUser != null && merchantUser.size() > 0) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 
     * ?
     * 
     * @Date 2012-03-07
     * @author wang.m
     * @throws Exception
     */
    @Transactional
    @Deprecated
    public Integer addSupplier(HttpServletRequest req, SupplierSp supplierSp) {
        Integer count = 0;
        try {
            SupplierSp supplier = new SupplierSp();
            supplier.setUpdateTimestamp(System.currentTimeMillis());// 
            supplier.setSupplier(supplierSp.getSupplier());// ??
            supplier.setSimpleName(supplierSp.getSimpleName());// 
            supplier.setAddress(supplierSp.getAddress());// ?
            supplier.setTaxRate(supplierSp.getTaxRate());// 
            supplier.setRemark(supplierSp.getRemark());// 
            if (null != supplierSp && supplierSp.getSupplierType() != null
                    && "".equals(supplierSp.getSupplierType())) {
                if (supplierSp.getCouponsAllocationProportion() == null) {
                    supplier.setCouponsAllocationProportion(supplierSp.getCouponsAllocationProportion());// 
                } else {
                    supplier.setCouponsAllocationProportion(0.00);// 
                }
            } else {
                supplier.setCouponsAllocationProportion(0.00);// 
            }
            supplier.setSupplierType(supplierSp.getSupplierType());// 
            supplier.setIsInputYougouWarehouse(supplierSp.getIsInputYougouWarehouse());// ?
            supplier.setSetOfBooksCode(supplierSp.getSetOfBooksCode());// ???
            supplier.setSetOfBooksName(supplierSp.getSetOfBooksName());// ????
            supplier.setBalanceTraderCode(supplierSp.getBalanceTraderCode());// ?
            supplier.setBalanceTraderName(supplierSp.getBalanceTraderName());// ??
            supplier.setPosSourceNo(supplierSp.getPosSourceNo());// pos?
            supplier.setIsUseYougouWms(supplierSp.getIsUseYougouWms());//?WMS
            supplier.setDeleteFlag(1);// 
            supplier.setShipmentType(supplierSp.getShipmentType());// ?
            SystemmgtUser user = GetSessionUtil.getSystemUser(req);
            String loginUser = "";
            if (user != null) {
                loginUser = user.getUsername();
            }
            supplier.setCreator(loginUser);// 
            supplier.setUpdateUser(loginUser);// 
            supplier.setUpdateDate(new Date());//  
            // 
            if (StringUtils.isNotBlank(supplierSp.getId())) {
                // ?
                SupplierSp supplierInfo = getSupplierSpById(supplierSp.getId());
                // ?
                if (supplierInfo != null) {
                    supplier.setBank(supplierInfo.getBank());
                    supplier.setSubBank(supplierInfo.getSubBank());
                    supplier.setDutyCode(supplierInfo.getDutyCode());
                    supplier.setContact(supplierInfo.getContact());
                    supplier.setPayType(supplierInfo.getPayType());
                    supplier.setAccount(supplierInfo.getAccount());
                    supplier.setConTime(supplierInfo.getConTime());
                }
                if (supplierInfo != null) {
                    // ??()
                    if (null != supplierSp && supplierSp.getSupplierType() != null
                            && "".equals(supplierSp.getSupplierType())) {
                        // 
                        Double proportion = supplierInfo.getCouponsAllocationProportion() == null ? 0.0
                                : supplierInfo.getCouponsAllocationProportion();
                        if (supplierSp.getCouponsAllocationProportion() != null
                                && !proportion.equals(supplierSp.getCouponsAllocationProportion())) {
                            count = addMerhcantlog(supplierSp.getId(), "?",
                                    "", proportion.toString(),
                                    supplierSp.getCouponsAllocationProportion().toString(), loginUser);
                        }
                    }
                    // ????
                    String setOfBooksName = supplierInfo.getSetOfBooksName() == null ? ""
                            : supplierInfo.getSetOfBooksName();
                    if (!setOfBooksName.equals(supplierSp.getSetOfBooksName())) {
                        count = addMerhcantlog(supplierSp.getId(), "?",
                                "????", setOfBooksName, supplierSp.getSetOfBooksName(), loginUser);
                    }
                    // 
                    Double taxRate = supplierInfo.getTaxRate() == null ? 0.0 : supplierInfo.getTaxRate();
                    if (!taxRate.equals(supplierSp.getTaxRate())) {
                        count = addMerhcantlog(supplierSp.getId(), "?", "",
                                taxRate.toString(), supplierSp.getTaxRate().toString(), loginUser);
                    }
                    // ?
                    Integer warehouse = supplierInfo.getIsInputYougouWarehouse() == null ? 1
                            : supplierInfo.getIsInputYougouWarehouse();
                    if (warehouse != supplierSp.getIsInputYougouWarehouse()) {
                        String wareStr = "";
                        String wareStr1 = "";
                        if (warehouse == 1) {
                            wareStr = "";
                            wareStr1 = "?";
                        } else {
                            wareStr = "?";
                            wareStr1 = "";
                        }
                        count = addMerhcantlog(supplierSp.getId(), "?", "",
                                wareStr, wareStr1, loginUser);
                    }
                }
                supplier.setId(supplierSp.getId());
                supplier.setSupplierCode(supplierSp.getSupplierCode());// ?
                supplier.setIsValid(supplierSp.getIsValid());// ?
                //supplierDaoImpl.merge(supplier);
                //TODO
            } else {
                String supplierCode = new CodeGenerate().getSupplierCode();
                supplier.setSupplierCode(supplierCode);// ?
                supplier.setIsValid(2);// ? 
                //supplierDaoImpl.save(supplier);
                //TODO
            }

            count = 1;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("?!", e);
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 
     * ?
     * 
     * @Date 2012-03-07
     * @author wang.m
     * @throws Exception
     */
    @Transactional
    @Deprecated
    public Integer addMerchant(HttpServletRequest req, SupplierSp supplierSp, String bankNoHidden,
            String catNameHidden) {
        Integer count = 0;
        String supplierCode = "";
        String loginUser = "";
        try {
            SupplierSp supplier = new SupplierSp();
            if (supplierSp != null) {
                try {
                    SystemmgtUser user = GetSessionUtil.getSystemUser(req);
                    supplier.setUpdateTimestamp(System.currentTimeMillis());// 
                    supplier.setSupplier(supplierSp.getSupplier());
                    supplierCode = new CodeGenerate().getSupplierCode();
                    supplier.setSupplierCode(supplierCode);// ?
                    supplier.setContact(supplierSp.getContact());// ??
                    supplier.setAccount(supplierSp.getAccount());// ?
                    supplier.setSubBank(supplierSp.getSubBank());// ?
                    supplier.setBankLocal(supplierSp.getBankLocal());// 
                    supplier.setBusinessLicense(supplierSp.getBusinessLicense());// ??
                    supplier.setBusinessLocal(supplierSp.getBusinessLocal());// ?
                    supplier.setBusinessValidity(supplierSp.getBusinessValidity());// ?
                    supplier.setTaxpayer(supplierSp.getTaxpayer());// ?
                    supplier.setInstitutional(supplierSp.getInstitutional());// ?
                    supplier.setTallageNo(supplierSp.getTallageNo());// ??
                    supplier.setTaxRate(supplierSp.getTaxRate());// 
                    supplier.setCouponsAllocationProportion(supplierSp.getCouponsAllocationProportion());// 
                    supplier.setIsValid(2);// ?
                    supplier.setSupplierType(supplierSp.getSupplierType());// 
                    supplier.setIsInputYougouWarehouse(supplierSp.getIsInputYougouWarehouse());// ?
                    supplier.setIsUseYougouWms(supplierSp.getIsUseYougouWms());// ?WMS
                    supplier.setSetOfBooksCode(supplierSp.getSetOfBooksCode());// ???
                    supplier.setSetOfBooksName(supplierSp.getSetOfBooksName());// ????
                    if (user != null) {
                        loginUser = user.getUsername();
                    }
                    supplier.setCreator(loginUser);// 
                    supplier.setUpdateUser(loginUser);// 
                    supplier.setUpdateDate(new Date());//  
                    supplier.setDeleteFlag(1);// 
                    supplier.setShipmentType(supplierSp.getShipmentType());// ?
                    supplier.setTradeCurrency(supplierSp.getTradeCurrency());
                    //supplierDaoImpl.save(supplier);
                    //TODO

                    /**  Modifier by yang.mq **/
                    MerchantOperationLog operationLog = new MerchantOperationLog();
                    operationLog.setMerchantCode(supplier.getSupplierCode());
                    operationLog.setOperator(supplier.getCreator());
                    operationLog.setOperated(new Date());
                    operationLog.setOperationType(OperationType.BASIC_DATA);
                    operationLog.setOperationNotes(
                            merchantOperationLogService.buildMerchantBasicDataOperationNotes(null, supplier));
                    merchantOperationLogService.saveMerchantOperationLog(operationLog);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    logger.error("?!", e);
                    count = 0;
                }

                try {
                    // ?
                    MerchantUser merchantUser = new MerchantUser();
                    merchantUser.setLoginName(supplierSp.getLoginAccount());// ??
                    // ?MD5
                    String password = Md5Encrypt.md5(supplierSp.getLoginPassword());
                    merchantUser.setPassword(password);// ?
                    merchantUser.setMerchantCode(supplierCode);// ?
                    merchantUser.setUserName("");// ?
                    merchantUser.setCreateTime(formDate());
                    merchantUser.setStatus(1);// ? 1?
                    merchantUser.setIsAdministrator(1); // 1?
                    merchantUser.setDeleteFlag(1);// 
                    merchantUser.setIsYougouAdmin(0);
                    merchantUserDaoImpl.save(merchantUser);

                    /** ? Modifier by yang.mq **/
                    MerchantOperationLog operationLog = new MerchantOperationLog();
                    operationLog.setMerchantCode(supplier.getSupplierCode());
                    operationLog.setOperator(supplier.getCreator());
                    operationLog.setOperated(new Date());
                    operationLog.setOperationType(OperationType.ACCOUNT);
                    operationLog.setOperationNotes(
                            merchantOperationLogService.buildMerchantAccountOperationNotes(null, merchantUser));
                    merchantOperationLogService.saveMerchantOperationLog(operationLog);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    logger.error("???!", e);
                    count = 0;
                }
            }
            // ???
            addMerchantBankAndCat(supplier, req, bankNoHidden, catNameHidden, null, null, "1");
            count = 2;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("?!", e);
            count = 0;
        }
        return count;
    }

    /**
     * 
     * ?
     * 
     * @Date 2012-03-07
     * @author wang.m
     * @throws Exception
     */
    @Transactional
    public Integer updateMerchant(HttpServletRequest req, SupplierSp supplierSp, String bankNameHidden,
            String catNameHidden, String brandList, String catList) throws Exception {
        // ?
        SupplierSp supplierInfo = getSupplierSpById(supplierSp.getId());

        //TODO
        // ????
        String[] brandInfos = getSpLimitBrandBysupplierId(supplierSp.getId());
        // ???
        String[] catInfos = getSpLimitCatBysupplierId(supplierSp.getId());

        SystemmgtUser user = GetSessionUtil.getSystemUser(req);
        String loginUser = "";
        if (user != null) {
            loginUser = user.getUsername();
        }
        SupplierSp supplier = new SupplierSp();
        supplier.setId(supplierSp.getId()); // Id
        supplier.setUpdateTimestamp(System.currentTimeMillis());// 
        supplier.setSupplier(supplierSp.getSupplier());// ??
        supplier.setSupplierCode(supplierSp.getSupplierCode());// ?
        supplier.setContact(supplierSp.getContact());// ??
        supplier.setAccount(supplierSp.getAccount());// ?
        supplier.setSubBank(supplierSp.getSubBank());// ?
        supplier.setBankLocal(supplierSp.getBankLocal());// 
        supplier.setBusinessLicense(supplierSp.getBusinessLicense());// ??
        supplier.setBusinessLocal(supplierSp.getBusinessLocal());// ?
        supplier.setBusinessValidity(supplierSp.getBusinessValidity());// ?
        supplier.setTaxpayer(supplierSp.getTaxpayer());// ?
        supplier.setInstitutional(supplierSp.getInstitutional());// ?
        supplier.setTallageNo(supplierSp.getTallageNo());// ??
        supplier.setTaxRate(supplierSp.getTaxRate());// 
        supplier.setCouponsAllocationProportion(supplierSp.getCouponsAllocationProportion());// 
        supplier.setIsValid(supplierSp.getIsValid());// ?
        supplier.setSupplierType(supplierSp.getSupplierType());// 
        supplier.setIsInputYougouWarehouse(supplierSp.getIsInputYougouWarehouse());// ?
        supplier.setSetOfBooksCode(supplierSp.getSetOfBooksCode());// ???
        supplier.setSetOfBooksName(supplierSp.getSetOfBooksName());// ????
        supplier.setCreator(loginUser);// 
        supplier.setUpdateUser(loginUser);// 
        supplier.setUpdateDate(new Date());//  
        supplier.setDeleteFlag(1);// 
        supplier.setShipmentType(supplierSp.getShipmentType());// ?
        supplier.setInventoryCode(supplierSp.getInventoryCode());//?
        if (supplierSp.getTradeCurrency() != null) {
            supplier.setTradeCurrency(supplierSp.getTradeCurrency());
        }
        supplier.setIsUseYougouWms(supplierSp.getIsUseYougouWms());//?WMS

        String operationNotes = merchantOperationLogService.buildMerchantBasicDataOperationNotes(supplierInfo,
                supplier);

        //supplierDaoImpl.merge(supplier);
        //TODO

        // ?Id???
        deleteMerchantBankAndCat(supplierSp.getId());
        // ???
        addMerchantBankAndCat(supplierSp, req, bankNameHidden, catNameHidden, brandList, catList, "2");

        if (ArrayUtils.isNotEmpty(brandInfos)) {
            if (!StringUtils.equals(brandInfos[0], brandList)) {
                operationNotes += MessageFormat.format("????{0}?{1}",
                        brandInfos[0], brandList);
            }
        }
        if (ArrayUtils.isNotEmpty(catInfos)) {
            if (!StringUtils.equals(catInfos[0], catList)) {
                operationNotes += MessageFormat.format("???{0}?{1}",
                        catInfos[0], catList);
            }
        }
        if (StringUtils.isNotBlank(operationNotes)) {
            /**  Modifier by yang.mq **/
            MerchantOperationLog operationLog = new MerchantOperationLog();
            operationLog.setMerchantCode(supplier.getSupplierCode());
            operationLog.setOperator(supplier.getCreator());
            operationLog.setOperated(new Date());
            operationLog.setOperationType(OperationType.BASIC_DATA);
            operationLog.setOperationNotes(operationNotes);
            merchantOperationLogService.saveMerchantOperationLog(operationLog);
        }

        return 2;
    }

    /**
     * 
     * ?
     * 
     * @Date 2012-03-07
     * @author wang.m
     * @throws Exception
     */
    @Transactional
    public boolean update_merchants(ModelMap modelMap, Query query, SupplierSp supplierSp, HttpServletRequest req,
            String bankName, String catName) {
        boolean bool = false;
        try {
            SupplierSp supplier = new SupplierSp();
            if (supplierSp != null) {
                try {
                    supplier.setId(supplierSp.getId()); // Id
                    supplier.setUpdateTimestamp(System.currentTimeMillis());// 
                    supplier.setSupplier(supplierSp.getSupplier());// ??
                    supplier.setSupplierCode(supplierSp.getSupplierCode());// ?
                    supplier.setContact(supplierSp.getContact());// ??
                    supplier.setAccount(supplierSp.getAccount());// ?
                    supplier.setSubBank(supplierSp.getSubBank());// ?
                    supplier.setBankLocal(supplierSp.getBankLocal());// 
                    supplier.setBusinessLicense(supplierSp.getBusinessLicense());// ??
                    supplier.setBusinessLocal(supplierSp.getBusinessLocal());// ?
                    supplier.setBusinessValidity(supplierSp.getBusinessValidity());// ?
                    supplier.setTaxpayer(supplierSp.getTaxpayer());// ?
                    supplier.setInstitutional(supplierSp.getInstitutional());// ?
                    supplier.setTallageNo(supplierSp.getTallageNo());// ??
                    supplier.setTaxRate(supplierSp.getTaxRate());// 
                    supplier.setCouponsAllocationProportion(supplierSp.getCouponsAllocationProportion());// 
                    supplier.setIsValid(2);// ? 2
                    supplier.setSupplierType("");
                    supplier.setIsInputYougouWarehouse(supplierSp.getIsInputYougouWarehouse());// ?
                    supplier.setSetOfBooksCode(supplierSp.getSetOfBooksCode());// ???
                    supplier.setSetOfBooksName(supplierSp.getSetOfBooksName());// ????
                    supplier.setBalanceTraderCode(supplierSp.getBalanceTraderCode());// ?
                    supplier.setBalanceTraderName(supplierSp.getBalanceTraderName());// ??

                    SystemmgtUser user = GetSessionUtil.getSystemUser(req);
                    String loginUser = "";
                    if (user != null) {
                        loginUser = user.getUsername();
                    }
                    supplier.setCreator(loginUser);// 
                    supplier.setUpdateUser(loginUser);// 
                    supplier.setUpdateDate(new Date());//  
                    supplier.setDeleteFlag(1);// 
                    //supplierDaoImpl.merge(supplier);
                    //TODO

                    // ?Id???
                    deleteMerchantBankAndCat(supplierSp.getId());

                    // ???
                    addMerchantBankAndCat(supplierSp, req, "", "", bankName, catName, "2");
                    bool = true;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    logger.error("?!", e);
                    bool = false;
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("?!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ?ID???
     */
    private List<SpLimitBrand> getBrankSupplier(String id) {
        CritMap critMap = new CritMap();
        critMap.addEqual("supplyId", id);
        List<SpLimitBrand> list = spLimitBrandDaoImpl.findByCritMap(critMap);
        return list;
    }

    /**
     * ?ID???
     */
    private List<SpLimitCat> getCatSupplier(String id) {
        CritMap critMap = new CritMap();
        critMap.addEqual("supplyId", id);
        List<SpLimitCat> list = spLimitCatDaoImpl.findByCritMap(critMap);
        return list;
    }

    /**
     * ?ID?
     * 
     * @author wang.m
     * @Date 2012-03-07
     */
    public SupplierSp getSupplierSpById(String id) {
        SupplierSp supplierSp = new SupplierSp();

        SupplierVo _vo = new SupplierVo();
        SupplierVo supplier = null;
        _vo.setId(id);
        _vo.setIsValid(null);
        List<SupplierVo> vos = null;
        try {
            vos = supplierService.querySupplierByVo(_vo);

            supplier = CollectionUtils.isNotEmpty(vos) ? vos.get(0) : null;
            BeanUtils.copyProperties(supplierSp, supplier);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return supplierSp;
    }

    private SupplierVo getSupplierVoById(String id) {
        SupplierVo _vo = new SupplierVo();
        SupplierVo supplier = null;
        _vo.setId(id);
        List<SupplierVo> vos = null;
        try {
            vos = supplierService.querySupplierByVo(_vo);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return CollectionUtils.isNotEmpty(vos) ? vos.get(0) : null;
    }

    /**
     * ?ID???
     * 
     * @author wang.m
     * @throws SQLException
     * @Date 2012-03-08
     */
    @Deprecated
    public String[] getSpLimitCatBysupplierId(String id) throws SQLException {
        String str[] = new String[2];
        String catStr = "";
        String catHide = "";
        if (StringUtils.isNotBlank(id)) {
            /*
            CritMap critMap = new CritMap();
            critMap.addEqual("supplyId", id);
            List<SpLimitCat> spLimitCat = spLimitCatDaoImpl.findByCritMap(critMap);
            if (null != spLimitCat && spLimitCat.size() > 0) {
               for (SpLimitCat spLimitCat2 : spLimitCat) {
                  // ??3??
                  String threeCatName = this.getCatName(spLimitCat2.getCatNo());
                  // ?3??2??
                  String twoCatName = this.getTowCatName(threeCatName, spLimitCat2.getStructName());
                  // ?3??1??
                  String structName = spLimitCat2.getStructName().substring(0, 5);
                  String OneCatName = this.getOneCatName(twoCatName, structName);
                  catStr += OneCatName + "-" + twoCatName + "-" + threeCatName + ";";
                  catHide += spLimitCat2.getStructName() + ";" + spLimitCat2.getId() + "_";
               }
               catStr = catStr.substring(0, catStr.length() - 1);
               catHide = catHide.substring(0, catHide.length() - 1);
            }
            */
            List<Map<String, Object>> spLimitBrandMaps = sqlService.getDatasBySql(
                    "select id, cat_no, struct_name from tbl_sp_limit_cat where supply_id = '" + id + "'");
            if (null != spLimitBrandMaps && spLimitBrandMaps.size() > 0) {
                for (Map<String, Object> spLimitBrandMap : spLimitBrandMaps) {
                    String cat_no = MapUtils.getString(spLimitBrandMap, "cat_no");
                    String struct_name = MapUtils.getString(spLimitBrandMap, "struct_name");
                    // ??3??
                    String threeCatName = this.getCatName(cat_no);
                    // ?3??2??
                    String twoCatName = this.getTowCatName(threeCatName, struct_name);
                    // ?3??1??
                    String structName = struct_name.substring(0, 5);
                    String OneCatName = this.getOneCatName(twoCatName, structName);
                    catStr += OneCatName + "-" + twoCatName + "-" + threeCatName + ";";
                    catHide += struct_name + ";" + spLimitBrandMap.get("id") + "_";
                }
                catStr = catStr.substring(0, catStr.length() - 1);
                catHide = catHide.substring(0, catHide.length() - 1);
            }
        }
        str[0] = catStr;
        str[1] = catHide;
        return str;
    }

    /**
     * ?ID??--??
     * @param id
     * @return
     * @throws SQLException
     */
    @Deprecated
    public String[] getSpLimitBrandCatBysupplierId(String id) throws SQLException {
        String str[] = new String[2];
        String catStr = "";
        String catHide = "";
        if (StringUtils.isNotBlank(id)) {
            List<Map<String, Object>> spLimitBrandMaps = sqlService.getDatasBySql(
                    "SELECT bc.id, c.cat_no, c.struct_name, b.brand_no FROM tbl_sp_limit_cat c LEFT JOIN tbl_sp_limit_brand_cat bc ON c.id = bc.cat_id LEFT JOIN tbl_sp_limit_brand b ON bc.brand_id = b.id WHERE c.supply_id = '"
                            + id + "'");
            if (CollectionUtils.isNotEmpty(spLimitBrandMaps)) {
                for (Map<String, Object> spLimitBrandMap : spLimitBrandMaps) {
                    String struct_name = MapUtils.getString(spLimitBrandMap, "struct_name");
                    String brand_no = MapUtils.getString(spLimitBrandMap, "brand_no");
                    if (StringUtils.isBlank(struct_name))
                        continue;

                    Category cat = commodityBaseApiService.getCategoryByStructName(struct_name);
                    com.yougou.pc.model.brand.Brand brand = null;
                    if (StringUtils.isNotBlank(brand_no)) {
                        brand = commodityBaseApiService.getBrandByNo(brand_no);
                    }
                    catStr += (brand == null ? "" : brand.getBrandName()) + "|" + cat.getStructCatName() + ";";
                    catHide += brand_no + ";" + struct_name + ";" + cat.getId() + "_";
                }
                catStr = catStr.substring(0, catStr.length() - 1);
                catHide = catHide.substring(0, catHide.length() - 1);
            }
        }
        str[0] = catStr;
        str[1] = catHide;
        return str;
    }

    /**
     * ID???-??
     */
    public List<String> queryAuthorizationBrandCatBysupplierId(String id) throws SQLException {
        if (StringUtils.isBlank(id)) {
            return null;
        }

        List<String> brandStructs = new ArrayList<String>();
        List<Map<String, Object>> spLimitBrandMaps = sqlService.getDatasBySql(
                "SELECT bc.id, c.cat_no, c.struct_name, b.brand_no FROM tbl_sp_limit_cat c LEFT JOIN tbl_sp_limit_brand_cat bc ON c.id = bc.cat_id LEFT JOIN tbl_sp_limit_brand b ON bc.brand_id = b.id WHERE c.supply_id = '"
                        + id + "'");
        if (CollectionUtils.isNotEmpty(spLimitBrandMaps)) {
            for (Map<String, Object> map : spLimitBrandMaps) {
                String struct_name = MapUtils.getString(map, "struct_name");
                String brand_no = MapUtils.getString(map, "brand_no");
                if (StringUtils.isBlank(struct_name) || StringUtils.isBlank(brand_no))
                    continue;

                brandStructs.add(brand_no + ";" + struct_name);
            }
        }
        return brandStructs;
    }

    /**
     * ?ID????
     * 
     * @author wang.m
     * @throws SQLException
     * @Date 2012-03-08
     */
    @Deprecated
    public String[] getSpLimitBrandBysupplierId(String id) throws SQLException {
        String str[] = new String[2];
        String brandStr = "";
        String brandHide = "";
        if (StringUtils.isNotBlank(id)) {
            List<Map<String, Object>> spLimitBrandMaps = sqlService
                    .getDatasBySql("select id, brand_no from tbl_sp_limit_brand where supply_id = '" + id + "'");
            if (null != spLimitBrandMaps && spLimitBrandMaps.size() > 0) {
                for (Map<String, Object> spLimitBrandMap : spLimitBrandMaps) {
                    String brand_no = MapUtils.getString(spLimitBrandMap, "brand_no");
                    // ?????
                    Brand brand = commodityBaseApiService.getBrandByNo(brand_no);
                    String brandName = (brand != null) ? brand.getBrandName() : "";
                    brandStr += brandName + ";";
                    brandHide += spLimitBrandMap.get("id") + "_" + brand_no + "_" + brandName + ";";
                }
                brandStr = brandStr.substring(0, brandStr.length() - 1);
                brandHide = brandHide.substring(0, brandHide.length() - 1);
            }
        }
        str[0] = brandStr;
        str[1] = brandHide;
        return str;
    }

    /**
     * ID??
     */
    public List<String> getAuthorizationBrandNos(String id) throws SQLException {
        if (StringUtils.isBlank(id)) {
            return null;
        }

        List<String> brandNos = new ArrayList<String>();
        List<Map<String, Object>> spLimitBrandMaps = sqlService
                .getDatasBySql("select id, brand_no from tbl_sp_limit_brand where supply_id = '" + id + "'");
        if (CollectionUtils.isNotEmpty(spLimitBrandMaps)) {
            for (Map<String, Object> spLimitBrandMap : spLimitBrandMaps) {
                String brand_no = MapUtils.getString(spLimitBrandMap, "brand_no");
                if (StringUtils.isBlank(brand_no))
                    continue;

                brandNos.add(brand_no);
            }
        }
        return brandNos;
    }

    /*
     * ID??
     * (non-Javadoc)
     * @see com.belle.yitiansystem.merchant.service.IMerchantsService#queryAuthorizationBrandBysupplierId(java.lang.String)
     */
    public String queryAuthorizationBrandBysupplierId(String id) throws SQLException {
        List<String> brandNos = this.getAuthorizationBrandNos(id);
        StringBuffer sb = new StringBuffer("");

        if (CollectionUtils.isEmpty(brandNos))
            return sb.toString();

        for (String brandNo : brandNos) {
            com.yougou.pc.model.brand.Brand brand = commodityBaseApiService.getBrandByNo(brandNo);
            if (brand == null)
                continue;

            String brandName = brand.getBrandName();
            if (sb.length() == 0)
                sb.append(brandNo).append(";").append(brandName);
            else
                sb.append("_").append(brandNo).append(";").append(brandName);
        }
        return sb.toString();
    }

    /**
     * ???
     * 
     * @author wang.m
     * @Date 2012-03-08
     */
    public SystemmgtUser getSystemmgtUserByUserName(String loginUserName) {
        SystemmgtUser systemmgtUser = null;
        if (StringUtils.isNotBlank(loginUserName)) {
            CritMap critMap = new CritMap();
            critMap.addEqual("loginName", loginUserName);
            List<SystemmgtUser> systemmgtUserList = userDao.findByCritMap(critMap);
            if (systemmgtUserList != null && systemmgtUserList.size() > 0) {
                systemmgtUser = systemmgtUserList.get(0);
            }
        }
        return systemmgtUser;
    }

    /**
     * ?3??2??
     * 
     * @author wang.m
     * @Date 2012-03-20
     * 
     */
    public String getTowCatName(String brandNo, String structName) throws SQLException {
        List<Object> obj = null;
        StringBuffer buffer = new StringBuffer(1024);
        buffer.append(
                "SELECT cat_name FROM tbl_commodity_catb2c WHERE struct_name=(SELECT SUBSTRING(struct_name,1,5) FROM tbl_commodity_catb2c WHERE cat_name=? and struct_name=?) ");
        if (StringUtils.isNotBlank(brandNo)) {
            obj = new ArrayList<Object>();
            obj.add(brandNo);
            obj.add(structName);
        }
        String cat = getResouseBySql(buffer.toString(), obj);
        return cat;
    }

    /**
     * ?2??1??
     * 
     * @author wang.m
     * @Date 2012-03-20
     * 
     */
    public String getOneCatName(String brandNo, String structName) throws SQLException {
        List<Object> obj = null;
        StringBuffer buffer = new StringBuffer(1024);
        buffer.append(
                "SELECT cat_name FROM tbl_commodity_catb2c WHERE struct_name=(SELECT SUBSTRING(struct_name,1,2) FROM tbl_commodity_catb2c WHERE cat_name=? and struct_name=?)");
        if (StringUtils.isNotBlank(brandNo) && StringUtils.isNotBlank(structName)) {
            obj = new ArrayList<Object>();
            obj.add(brandNo);
            obj.add(structName);
        }
        String cat = getResouseBySql(buffer.toString(), obj);
        return cat;
    }

    /**
     * wms? ?
     * 
     * @param merchantsCode
     *            ?
     * @param warehouseName
     *            ?
     * @throws Exception
     */
    public boolean update_merchant_virtualWarehouseCode(String merchantsCode, String warehouseCode,
            HttpServletRequest req) {
        boolean bool = false;
        if (StringUtils.isNotBlank(merchantsCode) && StringUtils.isNotBlank(warehouseCode)) {
            try {
                String sql = "select 1 from tbl_wms_warehouse where warehouse_code = ? and isoutwarehouse = ?";
                Object[] obj = new Object[2];
                obj[0] = warehouseCode;
                obj[1] = NumberUtils.INTEGER_ONE;

                /**  **/
                if (JDBCUtils.getInstance().count(sql, obj) != 1) {
                    //return bool;
                }

                SystemmgtUser user = GetSessionUtil.getSystemUser(req);
                String updateUser = "";
                if (user != null) {
                    updateUser = user.getUsername();
                }

                /**  **/
                sql = "update tbl_sp_supplier set inventory_code = null, update_user = ?, update_date = ? where inventory_code = ?";
                obj = new Object[3];
                obj[0] = updateUser;// 
                obj[1] = new Date(); // ??
                obj[2] = warehouseCode;
                sqlService.updateObject(sql, obj);

                /**  **/
                sql = "update tbl_sp_supplier set inventory_code = ?, update_user = ?, update_date = ? where supplier_code = ?";
                obj = new Object[4];
                obj[0] = warehouseCode;
                obj[1] = updateUser;// 
                obj[2] = new Date(); // ??
                obj[3] = merchantsCode;
                bool = sqlService.updateObject(sql, obj);
            } catch (Exception e) {
                logger.error("wms? ?!", e);
                throw new RuntimeException(e);
            }
        }
        return bool;
    }

    /**
     * ???
     * 
     * @throws Exception
     * @throws Exception
     * 
     */
    private void update_SpLimitBrand(String id) throws Exception {
        String sql = "delete from tbl_sp_limit_brand where id=?";
        Object[] obj = new Object[1];
        obj[0] = id;
        sqlService.updateObject(sql, obj);
    }

    /**
     * ??
     * 
     * @throws Exception
     * 
     */
    private void update_SpLimitCat(String id) throws Exception {
        String sql = "delete from tbl_sp_limit_cat where id=?";
        Object[] obj = new Object[1];
        obj[0] = id;
        sqlService.updateObject(sql, obj);
    }

    /**
     * ?--
     * 
     * @throws Exception
     * 
     */
    private void update_SpLimitBrand_Cat(String id) throws Exception {
        String sql = "delete from tbl_sp_limit_brand_cat where id=?";
        Object[] obj = new Object[1];
        obj[0] = id;
        sqlService.updateObject(sql, obj);
    }

    /**
     * ???3?
     * 
     * @throws SQLException
     * 
     */
    private List<Map<String, Object>> getCommodityCatb2cByStructName(String structName) throws SQLException {
        List<Map<String, Object>> maps = null;
        String sql = "select struct_name,id,no,cat_name from tbl_commodity_catb2c WHERE level = 3 and delete_flag=1 ";
        if (StringUtils.isNotBlank(structName)) {
            // struct_name LIKE ? AND
            sql += " and struct_name like '" + structName + "%'";
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            try {
                conn = getConnection();
                pstmt = conn.prepareStatement(sql);
                rs = pstmt.executeQuery();
                Map<String, Object> map = null;
                maps = new ArrayList<Map<String, Object>>();
                while (rs.next()) {
                    map = new HashMap<String, Object>();
                    ResultSetMetaData rsmd = rs.getMetaData();
                    for (int i = 0; i < rsmd.getColumnCount();) {
                        ++i;
                        String key = rsmd.getColumnLabel(i).toLowerCase();
                        if (map.containsKey(key)) {
                            throw new IllegalArgumentException("?key  " + key);
                        }
                        map.put(key, rs.getObject(i));
                    }
                    maps.add(map);
                }
            } catch (Exception e) {
                // TODO: handle exception
                logger.error("???3?!", e);
            } finally {
                close(conn, pstmt, rs);
            }
        }
        return maps;

    }

    /**
     * ??3??
     * 
     * @author wang.m param catNo
     * @throws SQLException
     */
    private String getCatName(String catNo) throws SQLException {
        StringBuffer buffer = new StringBuffer(1024);
        buffer.append("SELECT cat_name FROM tbl_commodity_catb2c WHERE 1=1");
        if (StringUtils.isNotBlank(catNo)) {
            buffer.append(" and NO ='" + catNo + "'");
        }
        String cat = getResouseBySql(buffer.toString(), null);
        return cat;
    }

    /**
     * ?????
     * 
     * @author wang.m param brandNo
     * @throws SQLException
     */
    /*private String getBrandName(String brandNo) throws SQLException {
       StringBuffer buffer = new StringBuffer(1024);
       buffer.append("SELECT brand_name FROM tbl_commodity_brand  WHERE 1=1");
       if (StringUtils.isNotBlank(brandNo)) {
     buffer.append("  and brand_no='" + brandNo + "'");
       }
       String cat = getResouseBySql(buffer.toString(), null);
       return cat;
    }*/

    /**
     * ?sql?
     * 
     * @throws SQLException
     * 
     **/
    private String getResouseBySql(String sql, List<Object> params) throws SQLException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String str = "";
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            if (params != null && params.size() > 0) {
                for (int j = 0; j < params.size(); j++) {
                    pstmt.setObject(j + 1, params.get(j));
                }
            }
            rs = pstmt.executeQuery();
            while (rs.next()) {
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 0; i < rsmd.getColumnCount();) {
                    ++i;
                    str = (String) rs.getObject(i);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            logger.error("sql?!" + sql, e);
        } finally {
            close(conn, pstmt, rs);
        }
        return str;
    }

    /**
     * ?
     * 
     * @param conn
     * @param pstmt
     * @param rs
     */
    private void close(Connection conn, Statement pstmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }

            if (pstmt != null) {
                pstmt.close();
                pstmt = null;
            }
            if (conn != null) {
                if (!conn.isClosed()) {
                    conn.close();
                }
                conn = null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            logger.error("?!", e);
        }
    }

    private Connection getConnection() {
        return userDao.getHibernateSession().connection();
    }

    /**
     * ?
     * 
     * @author wang.m
     * @Date 2012-03-26
     * 
     */
    public List<MerchantsRole> getMerchantsRoleList() {
        CritMap critMap = new CritMap();
        critMap.addAsc("createTime");
        List<MerchantsRole> merchantsAuthorityList = merchantsRoleDaoImpl.findByCritMap(critMap);
        return merchantsAuthorityList;
    }

    /**
     * ??
     * 
     * @author wang.m
     * @Date 2012-03-26
     * 
     */
    public List<MerchantsAuthority> getMerchantsAuthorityList(String uid) {
        List<MerchantsAuthority> list = new ArrayList<MerchantsAuthority>();
        try {

            CritMap critMap = new CritMap();
            critMap.addAsc("authrityModule");
            critMap.addNotEqual("parentId", "0");
            List<MerchantsAuthority> merchantsAuthorityList = merchantsAuthorityDaoImpl.findByCritMap(critMap);
            for (MerchantsAuthority merchantsAuthority : merchantsAuthorityList) {
                String sql = "SELECT t1.authority_id FROM tbl_merchant_user_authority t1 WHERE t1.authority_id=? and t1.user_id=?";
                List<Object> params = new ArrayList<Object>();
                params.add(merchantsAuthority.getId());
                params.add(uid);
                String aid = getResouseBySql(sql, params);
                if (StringUtils.isNotBlank(aid)) {
                    if (aid.equals(merchantsAuthority.getId())) {
                    } else {
                        list.add(merchantsAuthority);
                    }
                } else {
                    list.add(merchantsAuthority);
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("??!", e);
        }
        return list;
    }

    /**
     * Id
     * 
     * @author wang.m
     * @throws SQLException
     * @Date 2012-03-26
     * 
     */
    public List<Map<String, Object>> getMerchantsRoleDaoImplById(String id) throws SQLException {
        String sql = "SELECT t1.id,t1.role_name FROM tbl_merchant_role t1 INNER JOIN tbl_merchant_user_role t2 ON t1.id=t2.role_id WHERE 1=1 AND t2.user_id='"
                + id + "'";
        List<Map<String, Object>> maps = getMapBysql(sql, null);
        return maps;
    }

    /**
     * ?
     * 
     * @author wang.M
     * 
     */
    public boolean delete_merchants(String id, String supplierCode) throws Exception {
        boolean isDeleteSuccess = false;
        try {
            if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(supplierCode)) {
                // ? 0
                /**
                String sql = "UPDATE tbl_sp_supplier SET delete_flag=0 WHERE is_valid=2 and id=?";
                Object[] obj = new Object[1];
                obj[0] = id;
                sqlService.updateObject(sql, obj);
                */
                // ???
                String sql2 = "UPDATE tbl_merchant_user SET delete_flag=0,create_time=? WHERE merchant_code=? ";
                Object[] obj2 = new Object[2];
                obj2[0] = formDate();
                obj2[1] = supplierCode;
                sqlService.updateObject(sql2, obj2);

                // ??
                /**
                String sql3 = "DELETE FROM tbl_sp_supplier_contact WHERE supply_id = ?";
                Object[] obj3 = new Object[1];
                obj3[0] = id;
                sqlService.updateObject(sql3, obj3);
                */
                this.purchaseApiService.deleteSupplierContact(id);

                // ???
                String sql4 = "DELETE FROM tbl_sp_supplier_contract WHERE supplier_id = ?";
                Object[] obj4 = new Object[1];
                obj4[0] = id;
                sqlService.updateObject(sql4, obj4);

                // ??
                String sql5 = "DELETE FROM tbl_merchant_operation_log WHERE merchant_code = ?";
                Object[] obj5 = new Object[1];
                obj5[0] = supplierCode;
                sqlService.updateObject(sql5, obj5);

                isDeleteSuccess = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("?!", ex);
            isDeleteSuccess = false;
        }
        return isDeleteSuccess;
    }

    /**
     * ??
     * 
     * @author wang.m
     * @Date 2012-03-26
     */
    public boolean saveUserAuthority(String uid, String authority) throws Exception {
        boolean bool = false;
        try {
            if (StringUtils.isNotBlank(uid) && StringUtils.isNotBlank(authority)) {
                // 
                deleteMerchantsAuthorityByPramas(uid);
                // 
                String sql = "insert into tbl_merchant_user_role(id,user_id,role_id,create_date,remark) values (?,?,?,?,?)";
                String[] strAdd = authority.split(";");
                if (strAdd.length > 0) {
                    for (String string : strAdd) {
                        Object[] obj = new Object[5];
                        // ?uuid
                        String uuid = UUIDGenerator.getUUID();
                        obj[0] = uuid;
                        obj[1] = uid;
                        obj[2] = string;
                        obj[3] = formDate();
                        obj[4] = "";
                        sqlService.updateObject(sql, obj);
                        bool = true;
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("??!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ??
     * 
     * @author wang.m
     * @Date 2012-03-26
     */
    public PageFinder<Map<String, Object>> queryMerchantsAuthorityList(Query query,
            MerchantsAuthority merchantsAuthority) {
        String sql = "SELECT t1.id,t1.parent_id,t2.authrity_name as parent_name,t1.authrity_name,t1.authrity_url,t1.authrity_module,t1.sort_no,t1.create_time,t1.remark from tbl_merchant_authority t1 LEFT JOIN tbl_merchant_authority t2 on t1.parent_id=t2.id where 1=1 ";

        // ?
        if (merchantsAuthority != null) {
            if (StringUtils.isNotBlank(merchantsAuthority.getAuthrityName())) {// ??
                sql += " and t1.authrity_name like '" + merchantsAuthority.getAuthrityName().trim() + "%' ";
            }
        }
        sql += " ORDER BY t1.sort_no asc,t1.create_time desc";
        PageFinder<Map<String, Object>> pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);
        return pageFinder;
    }

    /**
     * ??
     * 
     * @author wang.m
     * @Date 2012-03-26
     */
    public List<Map<String, Object>> queryAllMerchantsAuthorityList() {
        String sql = "SELECT t1.id,t1.parent_id,t1.authrity_name,t1.authrity_url,t1.authrity_module,t1.sort_no,t1.create_time,t1.remark from tbl_merchant_authority t1 where 1=1 ";

        sql += " ORDER BY t1.sort_no asc";
        List<Map<String, Object>> authorityList = sqlService.getDatasBySql(sql);
        return authorityList;
    }

    /**
     * 
     * ?Id??
     */
    public MerchantsAuthority getMerchantsAuthorityByid(String id) {
        List<MerchantsAuthority> result = new ArrayList<MerchantsAuthority>();
        MerchantsAuthority merchantsAuthority = null;
        CritMap critMap = new CritMap();
        if (StringUtils.isNotBlank(id)) {
            critMap.addEqual("id", id);
        }
        result = merchantsAuthorityDaoImpl.findByCritMap(critMap);
        if (result != null && result.size() > 0) {
            merchantsAuthority = result.get(0);
        }
        return merchantsAuthority;
    }

    /**
     * 
     * ?Id??
     */
    public List<MerchantsAuthority> getMerchantsAuthorityByPid(String pid) {
        CritMap critMap = new CritMap();
        critMap.addEqual("parentId", pid);
        return merchantsAuthorityDaoImpl.findByCritMap(critMap);
    }

    /**
     * 
     * ?
     */
    @Transactional
    public boolean updateMerchantsAuthority(MerchantsAuthority merchantsAuthority) {
        boolean bool = false;
        try {
            merchantsAuthorityDaoImpl.merge(merchantsAuthority);
            bool = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("?!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * 
     * ?
     */
    @Transactional
    public boolean addMerchantsAuthority(MerchantsAuthority merchantsAuthority) {
        boolean bool = false;
        try {
            merchantsAuthority.setId(null);
            merchantsAuthority.setCreateTime(formDate());
            merchantsAuthorityDaoImpl.save(merchantsAuthority);
            bool = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("?!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ?Id ??
     * 
     * @author wang.m
     * @Date 2012-03-27
     */
    private void deleteMerchantsAuthorityByPramas(String userId) {
        try {
            String sql = "delete from tbl_merchant_user_role where user_id=? ";
            Object[] obj = new Object[1];
            obj[0] = userId;
            sqlService.updateObject(sql, obj);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("?Id ??!", e);
            e.printStackTrace();
        }
    }

    /**
     * ??
     */
    public PageFinder<Map<String, Object>> queryMerchantsUser(Query query, MerchantUser merchantUser) {
        String sql = "SELECT t1.id,t1.merchant_code,t2.supplier AS merchant_name,t1.user_name,t1.login_name,"
                + "t1.mobile_code,t1.creater,t1.create_time,t1.status,t1.remark,t1.is_yougou_admin"
                + " FROM tbl_merchant_user t1 LEFT JOIN tbl_sp_supplier t2 ON t1.merchant_code = t2.supplier_code"
                + " WHERE t1.delete_flag=1 ";

        // ?
        if (merchantUser != null) {
            if (StringUtils.isNotBlank(merchantUser.getUserName())) {
                sql += " AND t1.user_name LIKE '" + merchantUser.getUserName().trim() + "%'";
            }
            if (StringUtils.isNotBlank(merchantUser.getLoginName())) {// ??
                sql += " AND t1.login_name LIKE '" + merchantUser.getLoginName().trim() + "%'";
            }
            if (StringUtils.isNotBlank(merchantUser.getMerchantCode())) {// ?
                sql += " AND t1.merchant_code LIKE '" + merchantUser.getMerchantCode().trim() + "%'";
            }
            if (NumberUtils.INTEGER_ONE.equals(merchantUser.getIsYougouAdmin())) {
                sql += " AND t1.is_yougou_admin = " + merchantUser.getIsYougouAdmin();
            } else {
                sql += " AND (t1.is_yougou_admin = 0 OR t1.is_yougou_admin is null)";
            }
        }
        sql += " ORDER BY t1.create_time DESC";
        PageFinder<Map<String, Object>> pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);
        return pageFinder;
    }

    /**
     * 
     * 
     * @author wang.m
     */
    public PageFinder<Map<String, Object>> queryMerchantsRole(Query query, MerchantsRole merchantsRole,
            String authorityName) {
        String sql = "SELECT t1.id,t1.role_name,t1.create_time,t1.remark,t1.operator,t1.status FROM tbl_merchant_role t1 where 1=1 ";

        // ?
        if (merchantsRole != null) {
            if (StringUtils.isNotBlank(merchantsRole.getRoleName())) {// ??
                sql += " and t1.role_name like '" + merchantsRole.getRoleName().trim() + "%' ";
            }
        }

        if (authorityName != null && !"".equals(authorityName.trim())) {
            sql += " and t1.id in (select ra.role_id from tbl_merchant_role_authority ra left join tbl_merchant_authority a on ra.authority_id=a.id where a.authrity_name like '%"
                    + authorityName + "%')";
        }
        sql += " ORDER BY t1.create_time desc";
        PageFinder<Map<String, Object>> pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);
        return pageFinder;
    }

    /**
     * 
     * 
     * @author wang.m
     */
    public List<MerchantsRole> queryAllMerchantsRole() {
        return merchantsRoleDaoImpl.findBy("status", "1", false);
    }

    /**
     * 
     * 
     * @author wang.m
     */
    public List<UserRole> queryUserRole(String user_id) {
        return userAuthorityDao.findBy("userId", user_id, false);
    }

    /**
     * 
     * 
     * @author wang.m
     */
    public List<UserRole> queryUserRoleByRole(String id) {
        return userAuthorityDao.findBy("roleId", id, false);
    }

    @Transactional
    public void saveUserRole(String userId, String[] role, String merchantCode, String opertor) throws Exception {
        List<UserRole> userRoles = userAuthorityDao.findBy("userId", userId, false);
        //
        for (UserRole userRole : userRoles) {
            boolean exist = false;
            if (role != null) {
                for (String r : role) {
                    if (userRole.getRoleId().equals(r)) {
                        exist = true;
                        break;
                    }
                }
            }
            if (!exist) {
                userAuthorityDao.removeById(userRole.getId());
            }
        }
        //
        CritMap critMap = null;
        UserRole userRole = null;
        MerchantsRole merchantsRole = null;
        String roleName = "";
        if (role != null) {
            for (String r : role) {
                critMap = new CritMap();
                critMap.addEqual("userId", userId);
                critMap.addEqual("roleId", r);
                List<UserRole> userRole2 = userAuthorityDao.findByCritMap(critMap, false);
                if (userRole2 == null || userRole2.size() == 0) {
                    userRole = new UserRole();
                    userRole.setRoleId(r);
                    userRole.setUserId(userId);
                    userRole.setCreateDate(new Date());
                    this.addUserRole(userRole);
                    merchantsRole = this.initialMerchantsRole(r);
                    roleName = roleName + "[" + merchantsRole.getRoleName() + "] ";
                }
            }
        }
        /**  Modifier by yang.mq **/
        MerchantOperationLog operationLog = new MerchantOperationLog();
        operationLog.setMerchantCode(merchantCode);
        operationLog.setOperator(opertor);
        operationLog.setOperated(new Date());
        operationLog.setOperationType(OperationType.ACCOUNT);
        operationLog.setOperationNotes("????(" + roleName + ")");
        merchantOperationLogService.saveMerchantOperationLog(operationLog);
    }

    @Transactional
    public void addUserRole(UserRole userRole) throws Exception {
        userAuthorityDao.save(userRole);
    }

    /**
     * 
     * 
     * @author wang.m
     * @Date 2012-03-27
     * 
     */
    @Transactional
    public boolean addMerchantsRole(MerchantsRole merchantsRole, String[] authritys) {
        boolean bool = false;
        try {
            String roleid = (String) merchantsRoleDaoImpl.save(merchantsRole);
            if (authritys != null && authritys.length > 0) {
                for (String authrity : authritys) {
                    this.addRoleAuthority(roleid, authrity);
                }
            }
            bool = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * 
     * 
     * @author wang.m
     * @Date 2012-03-27
     * 
     */
    @Transactional
    public boolean update_merchants_role(MerchantsRole merchantsRole, String[] authritys) {
        boolean bool = false;
        try {
            merchantsRoleDaoImpl.merge(merchantsRole);

            List<RoleAuthority> roleAuthorityList = this.findRoleAuthoriryList(merchantsRole.getId());
            //?
            for (RoleAuthority roleAuthority : roleAuthorityList) {
                boolean exist = false;
                for (String authrity : authritys) {
                    if (roleAuthority.getAuthorityId().equals(authrity)) {
                        exist = true;
                        break;
                    }
                }
                if (!exist) {
                    roleAuthorityDaoImpl.removeById(roleAuthority.getId());
                }
            }

            for (String authrity : authritys) {
                int count = findRoleAuthoriryExits(merchantsRole.getId(), authrity);
                if (count == 0) {
                    this.addRoleAuthority(merchantsRole.getId(), authrity);
                }
            }
            bool = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ???
     * 
     * @author wang.m
     * @Date 2012-03-27
     * 
     */
    public MerchantsRole initialMerchantsRole(String rid) {
        MerchantsRole merchantsRole = null;
        CritMap critMap = new CritMap();
        critMap.addEqual("id", rid);
        List<MerchantsRole> merchantsRoleList = merchantsRoleDaoImpl.findByCritMap(critMap);
        if (merchantsRoleList != null && merchantsRoleList.size() > 0) {
            merchantsRole = merchantsRoleList.get(0);
        }
        return merchantsRole;
    }

    /**
     * ??
     * 
     * @throws SQLException
     */
    public List<Map<String, Object>> getRoleAuthorityList(String rid) throws SQLException {
        String sql = "SELECT t2.authrity_name FROM tbl_merchant_role_authority t1 INNER JOIN tbl_merchant_authority t2 ON t1.authority_id=t2.id  WHERE authrity_module<>0 AND t1.role_id='"
                + rid + "'";
        List<Map<String, Object>> maps = getMapBysql(sql, null);
        return maps;
    }

    /**
     * sql?
     * 
     * @author wang.m
     * @throws SQLException
     */
    private List<Map<String, Object>> getMapBysql(String sql, Object[] param) throws SQLException {
        List<Map<String, Object>> maps = null;
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            if (null != param && param.length > 0) {
                for (int i = 0; i < param.length; i++) {
                    pstmt.setObject(i + 1, param[i]);
                }
            }
            rs = pstmt.executeQuery();
            Map<String, Object> map = null;
            maps = new ArrayList<Map<String, Object>>();
            while (rs.next()) {
                map = new HashMap<String, Object>();
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 0; i < rsmd.getColumnCount();) {
                    ++i;
                    String key = rsmd.getColumnLabel(i).toLowerCase();
                    if (map.containsKey(key)) {
                        throw new IllegalArgumentException("?key  " + key);
                    }
                    map.put(key, rs.getObject(i));
                }
                maps.add(map);
            }
        } catch (Exception e) {
            // TODO: handle exception
            logger.error("sql?!", e);
        } finally {
            close(conn, pstmt, rs);
        }
        return maps;
    }

    /**
     * ??
     * 
     * @author wang.m
     * 
     */
    @Transactional
    public boolean addRoleAuthority(String roleId, String authorityId) {
        boolean bool = false;
        if (StringUtils.isNotBlank(roleId) && StringUtils.isNotBlank(authorityId)) {
            String[] aid = authorityId.split(";");
            if (aid.length > 0) {
                for (String str : aid) {
                    try {
                        // ??
                        Integer counts = findRoleAuthoriryExits(roleId, str);
                        if (counts < 1) {
                            RoleAuthority roleAuthoriry = new RoleAuthority();
                            roleAuthoriry.setAuthorityId(str);
                            roleAuthoriry.setRoleId(roleId);
                            roleAuthoriry.setCreateDate(new Date());
                            roleAuthoriry.setRemark("");
                            roleAuthorityDaoImpl.save(roleAuthoriry);
                            bool = true;
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        logger.error("??!", e);
                        bool = false;
                    }
                }
            }
        }
        return bool;
    }

    /**
     * ???
     * 
     */
    public Integer findRoleAuthoriryExits(String roleId, String authorityId) {
        CritMap critMap = new CritMap();
        critMap.addEqual("roleId", roleId);
        critMap.addEqual("authorityId", authorityId);
        List<RoleAuthority> roleAuthorityList = roleAuthorityDaoImpl.findByCritMap(critMap);
        return roleAuthorityList.size();
    }

    /**
     * ???
     * 
     */
    public List<RoleAuthority> findRoleAuthoriryList(String roleId) {
        CritMap critMap = new CritMap();
        critMap.addEqual("roleId", roleId);
        List<RoleAuthority> roleAuthorityList = roleAuthorityDaoImpl.findByCritMap(critMap);
        return roleAuthorityList;
    }

    /**
     * ????
     * 
     * @author wang.m
     * @throws Exception 
     * @Date 2012-03-29
     */
    public Integer existMerchantSupplieName(String supplieName) {
        Integer counts = 0;
        try {
            SupplierVo vo = supplierService.getSupplierByName(supplieName.trim());
            if (null != vo && "".equals(vo.getSupplierType())) {
                counts = 1;
            } else if (null != vo && "".equals(vo.getSupplierType())) {
                counts = 2;
            } else if (null != vo && "".equals(vo.getSupplierType())) {//?
                counts = 3;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return counts;
    }

    public void update_roleStatus(String id) throws Exception {
        MerchantsRole merchantsRole = merchantsRoleDaoImpl.findUniqueBy("id", id, false);
        if (merchantsRole.getStatus() == null || "".equals(merchantsRole.getStatus())
                || "0".equals(merchantsRole.getStatus())) {
            merchantsRole.setStatus("1");
        } else {
            merchantsRole.setStatus("0");
        }
        String sql = "update tbl_merchant_role set status = ? where id=? ";
        Object[] obj = new Object[2];
        obj[0] = merchantsRole.getStatus();
        obj[1] = id;
        sqlService.updateObject(sql, obj);
    }

    /**
     * 
     * 
     * @author wang.m
     */
    public boolean delete_role(String id) {
        boolean bool = false;
        try {

            String sql0 = "select count(1) from tbl_merchant_user_role where role_id=? ";
            List<Object> obj0 = new ArrayList<Object>();
            obj0.add(id);
            Long count = sqlService.getCountBySql(sql0, null, obj0);
            if (count == 0) {
                String sql1 = "delete from tbl_merchant_role_authority where role_id=? ";
                Object[] obj1 = new Object[1];
                obj1[0] = id;
                sqlService.updateObject(sql1, obj1);

                String sql2 = "delete from tbl_merchant_role where id=? ";
                Object[] obj2 = new Object[1];
                obj2[0] = id;
                sqlService.updateObject(sql2, obj2);
                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ?
     * 
     * @author wang.m
     */
    public boolean delete_authority(String id) {
        boolean bool = false;
        try {
            Object[] objects = { id };
            if ("0".equals(id)) {
                logger.error("??");
                return false;
            }
            // ???
            sqlService.updateObject("delete from tbl_merchant_user_authority where authority_id = ?", objects);
            // ???
            sqlService.updateObject("delete from tbl_merchant_role_authority where authority_id = ?", objects);
            // ??
            sqlService.updateObject("delete from tbl_merchant_authority where id = ?", objects);
            bool = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("?!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ???
     */
    public MerchantUser getMerchantsBySuppliceCode(String supplierCode) {
        MerchantUser merchantUser = null;
        CritMap critMap = new CritMap();
        critMap.addEqual("merchantCode", supplierCode);
        critMap.addEqual("deleteFlag", 1);//  1
        critMap.addEqual("isAdministrator", 1);// ?
        List<MerchantUser> merchantUserList = merchantUserDaoImpl.findByCritMap(critMap);
        if (merchantUserList != null && merchantUserList.size() > 0) {
            merchantUser = merchantUserList.get(0);
        }
        return merchantUser;
    }

    /**
     * 
     * ?Id??
     * 
     * @author wang.m
     * @DATE 2012-03-31
     */
    public String getSupplerNameById(String supplierId) {
        String supplierName = "";
        SupplierVo supplierSp = null;

        SupplierVo vo = new SupplierVo();
        vo.setId(supplierId);
        List<SupplierVo> list;
        try {
            list = supplierService.querySupplierByVo(vo);
        } catch (Exception e) {
            logger.error("Id??", e);
            return supplierName;
        }
        if (CollectionUtils.isNotEmpty(list)) {
            supplierSp = list.get(0);
            if (null != supplierSp) {
                supplierName = supplierSp.getSupplier();
            }
        }
        return supplierName;
    }

    /**
     * ?
     * 
     * @author wang.m
     * @DATE 2012-04-06
     * 
     */
    @Transactional
    public boolean updatePassword(MerchantUser merchantUser, SystemmgtUser systemmgtUser) {
        boolean bool = false;
        try {
            // ?MD5
            String password = Md5Encrypt.md5(merchantUser.getPassword());

            MerchantUser merchantUserInfo = merchantUserDaoImpl.getById(merchantUser.getId());

            String sql = "update tbl_merchant_user set password=? where id=? and delete_flag=1";
            Object[] obj = new Object[2];
            obj[0] = password;
            obj[1] = merchantUser.getId();
            sqlService.updateObject(sql, obj);
            bool = true;

            /**  Modifier by yang.mq **/
            MerchantOperationLog operationLog = new MerchantOperationLog();
            operationLog.setMerchantCode(merchantUserInfo.getMerchantCode());
            operationLog.setOperator(systemmgtUser.getUsername());
            operationLog.setOperated(new Date());
            operationLog.setOperationType(OperationType.ACCOUNT);
            operationLog.setOperationNotes("???");
            merchantOperationLogService.saveMerchantOperationLog(operationLog);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("?!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * 
     * ???Id?
     * 
     * @throws SQLException
     */
    public List<Map<String, Object>> getMerchantsAuthorityByUserId(String userId) throws SQLException {
        String sql = "SELECT t1.id,t1.authrity_name FROM tbl_merchant_authority t1 INNER JOIN tbl_merchant_user_authority t2 ON t1.id=t2.authority_id WHERE t1.authrity_module<>0 AND t2.user_id='"
                + userId + "'";
        List<Map<String, Object>> maps = getMapBysql(sql, null);
        return maps;
    }

    /**
     * ?????
     * 
     * @author wang.m
     * @Date 2012-03-26
     */
    @Transactional
    public boolean addUserAuthority(String userid, String authority, SystemmgtUser systemmgtUser) throws Exception {
        boolean bool = false;
        try {
            if (StringUtils.isNotBlank(userid)) {
                String diffSql = "select group_concat(t2.authrity_name separator '?') from tbl_merchant_user_authority t1 inner join tbl_merchant_authority t2 on(t1.authority_id = t2.id) where t1.user_id = ?";

                Object ownPermissions = JDBCUtils.getInstance().uniqueResult(diffSql, new Object[] { userid });

                // ?
                deleteUserAuthorityByPramas(userid);
                if (StringUtils.isNotBlank(authority)) {
                    // 
                    String sql = "insert into tbl_merchant_user_authority(id,user_id,authority_id,create_date,remark) values (?,?,?,?,?)";
                    String[] strAdd = authority.split(";");
                    if (strAdd.length > 0) {
                        for (String string : strAdd) {
                            Object[] obj = new Object[5];
                            // ?uuid
                            String uuid = UUIDGenerator.getUUID();
                            obj[0] = uuid;
                            obj[1] = userid;
                            obj[2] = string;
                            obj[3] = formDate();
                            obj[4] = "";
                            sqlService.updateObject(sql, obj);
                            bool = true;
                        }
                        // ????????????
                        sql = "select t3.id, t3.authority_id from tbl_merchant_user t1 inner join tbl_merchant_user t2 on(t1.merchant_code = t2.merchant_code) inner join tbl_merchant_user_authority t3 on(t2.id = t3.user_id) where t1.id = ? and t2.is_administrator = ?";
                        List<Map<String, Object>> resultMaps = JDBCUtils.getInstance().listResultMap(sql,
                                new Object[] { userid, NumberUtils.INTEGER_ZERO });
                        List<Object[]> sqlParams = new ArrayList<Object[]>();
                        for (Map<String, Object> resultMap : resultMaps) {
                            if (!ArrayUtils.contains(strAdd, MapUtils.getString(resultMap, "authority_id"))) {
                                sqlParams.add(new Object[] { MapUtils.getString(resultMap, "id") });
                            }
                        }
                        if (CollectionUtils.isNotEmpty(sqlParams)) {
                            JDBCUtils.getInstance().executeBatch(new JDBCUtils.SQLBatch(
                                    "delete from tbl_merchant_user_authority where id = ?", sqlParams));
                        }
                    }
                }
                Object finalPermissions = JDBCUtils.getInstance().uniqueResult(diffSql, new Object[] { userid });
                if (!ObjectUtils.equals(ownPermissions, finalPermissions)) {
                    MerchantUser merchantUser = merchantUserDaoImpl.getById(userid);
                    /** ? Modifier by yang.mq **/
                    MerchantOperationLog operationLog = new MerchantOperationLog();
                    operationLog.setMerchantCode(merchantUser.getMerchantCode());
                    if (systemmgtUser != null) {
                        operationLog.setOperator(systemmgtUser.getUsername());
                    } else {
                        operationLog.setOperator("system");
                    }
                    operationLog.setOperated(new Date());
                    operationLog.setOperationType(OperationType.ACCOUNT);
                    operationLog.setOperationNotes(MessageFormat.format(
                            "????{0}?{1}", ownPermissions, finalPermissions));
                    merchantOperationLogService.saveMerchantOperationLog(operationLog);
                }
                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("?????!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ?Id ??
     * 
     * @author wang.m
     * @Date 2012-03-27
     */
    private void deleteUserAuthorityByPramas(String userId) {
        try {
            String sql = "delete from tbl_merchant_user_authority where user_id=? ";
            Object[] obj = new Object[1];
            obj[0] = userId;
            sqlService.updateObject(sql, obj);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("?Id ??!", e);
            e.printStackTrace();
        }
    }

    /**
     * ????
     * 
     * @param contractNo
     *            ???
     */
    public boolean exits_contractNo(String contractNo, String supplierSpId) {
        boolean bool = false;
        CritMap critMap = new CritMap();
        critMap.addEqual("contractNo", contractNo);
        critMap.addFech("supplier", "supplier");
        critMap.addEqual("supplier.id", supplierSpId);
        List<SupplierContract> supplierSpList = supplierContractDaoImpl.findByCritMap(critMap);
        if (supplierSpList != null && supplierSpList.size() > 0) {
            bool = true;
        }
        return bool;
    }

    /**
     * 
     * ?Id?Id
     * 
     * @throws SQLException
     */
    public String getMerchantUserBySupplierId(String id) throws SQLException {
        String userId = "";
        String sql = "SELECT t1.id FROM tbl_merchant_user t1 INNER JOIN tbl_sp_supplier t2 ON t1.merchant_code=t2.supplier_code WHERE t2.id='"
                + id + "' AND t1.is_administrator=1 and t1.delete_flag=1 and t2.delete_flag=1";
        List<Map<String, Object>> maps = getMapBysql(sql, null);
        if (maps != null && maps.size() > 0) {
            for (Map<String, Object> map : maps) {
                userId = map.get("id").toString();
            }
        }
        return userId;
    }

    /**
     * 
     * ?Id
     */
    public MerchantUser getMerchantUserById(String merchantUserId) throws SQLException {
        return merchantUserDaoImpl.getById(merchantUserId);
    }

    /**
     * 
     * ?
     * @throws Exception 
     */
    @Transactional
    public void saveMerchantUser(MerchantUser merchantUser) throws Exception {
        merchantUserDaoImpl.save(merchantUser);
    }

    /**
     * 
     * ? ???????(??)
     * 
     * @Date 2012-03-07
     * @author wang.m
     */
    @Deprecated
    @Transactional
    public boolean update_historyMerchants(SupplierSp supplierSp, HttpServletRequest req, String bankNameHidden,
            String catNameHidden, String brandList, String catList) {
        boolean bool = false;
        try {
            if (supplierSp != null) {
                // 
                bool = updateSupplierById(supplierSp.getId(), req);

                // ?
                MerchantUser merchantUser = new MerchantUser();
                merchantUser.setLoginName(supplierSp.getLoginAccount());// ??
                // ?MD5
                String password = Md5Encrypt.md5(supplierSp.getLoginPassword());
                merchantUser.setPassword(password);// ?
                merchantUser.setMerchantCode(supplierSp.getSupplierCode());// ?
                merchantUser.setUserName("");// ?
                merchantUser.setCreateTime(formDate());
                merchantUser.setStatus(1);// ? 1?
                merchantUser.setIsAdministrator(1); // 1?
                merchantUser.setDeleteFlag(1);//  1?
                merchantUserDaoImpl.save(merchantUser);

                String username = GetSessionUtil.getSystemUser(req).getUsername();

                /** ? Modifier by yang.mq **/
                MerchantOperationLog operationLog = new MerchantOperationLog();
                operationLog.setMerchantCode(supplierSp.getSupplierCode());
                operationLog.setOperator(username);
                operationLog.setOperated(new Date());
                operationLog.setOperationType(OperationType.ACCOUNT);
                operationLog.setOperationNotes(
                        merchantOperationLogService.buildMerchantAccountOperationNotes(null, merchantUser));
                merchantOperationLogService.saveMerchantOperationLog(operationLog);

                // ?Id???
                deleteMerchantBankAndCat(supplierSp.getId());
                // ???
                addMerchantBankAndCat(supplierSp, req, bankNameHidden, catNameHidden, brandList, catList, "2");

                // ?
                SupplierSp supplierInfo = getSupplierSpById(supplierSp.getId());
                // ????
                String[] brandInfos = getSpLimitBrandBysupplierId(supplierSp.getId());
                // ???
                //String[] catInfos = getSpLimitCatBysupplierId(supplierSp.getId());
                String[] catInfos = getSpLimitBrandCatBysupplierId(supplierSp.getId());

                StringBuilder operationNotes = new StringBuilder();
                if (ArrayUtils.isNotEmpty(brandInfos)) {
                    if (!StringUtils.equals(brandInfos[0], brandList)) {
                        operationNotes.append(MessageFormat.format(
                                "????{0}?{1}", brandList, brandInfos[0]));
                    }
                }
                if (ArrayUtils.isNotEmpty(catInfos)) {
                    if (!StringUtils.equals(catInfos[0], catList)) {
                        operationNotes.append(MessageFormat.format(
                                "???{0}?{1}", catList, catInfos[0]));
                    }
                }
                if (operationNotes.length() > 0) {
                    /**  Modifier by yang.mq **/
                    operationLog = new MerchantOperationLog();
                    operationLog.setMerchantCode(supplierInfo.getSupplierCode());
                    operationLog.setOperator(GetSessionUtil.getSystemUser(req).getUsername());
                    operationLog.setOperated(new Date());
                    operationLog.setOperationType(OperationType.BASIC_DATA);
                    operationLog.setOperationNotes(operationNotes.toString());
                    merchantOperationLogService.saveMerchantOperationLog(operationLog);
                }

                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("???????(??)!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * 
     * ? ???????(??)
     * 
     * @Date 2012-03-07
     * @author wang.m
     */
    @Deprecated
    @Transactional
    public boolean update_merchantsBankAndCat(SupplierSp supplierSp, HttpServletRequest req, String bankNameHidden,
            String catNameHidden, String brandList, String catList) {
        boolean bool = false;
        try {
            if (supplierSp != null) {
                // 
                bool = updateSupplierById(supplierSp.getId(), req);
                // ?Id???
                deleteMerchantBankAndCat(supplierSp.getId());
                // ???
                addMerchantBankAndCat(supplierSp, req, bankNameHidden, catNameHidden, brandList, catList, "2");

                // ?
                SupplierSp supplierInfo = getSupplierSpById(supplierSp.getId());
                // ????
                String[] brandInfos = getSpLimitBrandBysupplierId(supplierSp.getId());
                // ???
                //String[] catInfos = getSpLimitCatBysupplierId(supplierSp.getId());
                String[] catInfos = this.getSpLimitBrandCatBysupplierId(supplierSp.getId());

                StringBuilder operationNotes = new StringBuilder();
                if (ArrayUtils.isNotEmpty(brandInfos)) {
                    if (!StringUtils.equals(brandInfos[0], brandList)) {
                        operationNotes.append(MessageFormat.format(
                                "????{0}?{1}", brandList, brandInfos[0]));
                    }
                }
                if (ArrayUtils.isNotEmpty(catInfos)) {
                    if (!StringUtils.equals(catInfos[0], catList)) {
                        operationNotes.append(MessageFormat.format(
                                "???{0}?{1}", catList, catInfos[0]));
                    }
                }
                if (operationNotes.length() > 0) {
                    /**  Modifier by yang.mq **/
                    MerchantOperationLog operationLog = new MerchantOperationLog();
                    operationLog.setMerchantCode(supplierInfo.getSupplierCode());
                    operationLog.setOperator(GetSessionUtil.getSystemUser(req).getUsername());
                    operationLog.setOperated(new Date());
                    operationLog.setOperationType(OperationType.BASIC_DATA);
                    operationLog.setOperationNotes(operationNotes.toString());
                    merchantOperationLogService.saveMerchantOperationLog(operationLog);
                }

                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("???????(??)!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ?Id??? id ID
     */
    private void deleteMerchantBankAndCat(String id) {
        try {
            //??
            List<Map<String, Object>> spLimitBrandCatMaps = sqlService.getDatasBySql(
                    "SELECT bc.id FROM tbl_sp_limit_cat c INNER JOIN tbl_sp_limit_brand_cat bc ON c.id = bc.cat_id INNER JOIN tbl_sp_limit_brand b ON bc.brand_id = b.id WHERE c.supply_id = '"
                            + id + "'");
            if (CollectionUtils.isNotEmpty(spLimitBrandCatMaps)) {
                for (Map<String, Object> map : spLimitBrandCatMaps) {
                    String brand_cat_id = MapUtils.getString(map, "id");
                    update_SpLimitBrand_Cat(brand_cat_id);
                }
            }

            // ??? 
            if (StringUtils.isNotBlank(id)) {
                List<SpLimitBrand> brank = this.getBrankSupplier(id);
                if (brank != null && brank.size() > 0) {
                    for (SpLimitBrand spLimitBrand : brank) {
                        update_SpLimitBrand(spLimitBrand.getId());
                    }
                }
            }

            // ?? 
            if (StringUtils.isNotBlank(id)) {
                List<SpLimitCat> spCat = this.getCatSupplier(id);
                if (spCat != null && spCat.size() > 0) {
                    for (SpLimitCat spLimitCat : spCat) {
                        update_SpLimitCat(spLimitCat.getId());
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("?Id???!", e);
        }
    }

    /**
     * ?Id??? id ID
     * 
     * @flag 1 2 
     */
    @Transactional
    private void addMerchantBankAndCat(SupplierSp supplierSp, HttpServletRequest req, String bankNoHidden,
            String catNameHidden, String brandList, String catList, String flag) {
        try {
            // ?
            if (StringUtils.isNotBlank(flag) && "2".equals(flag)) {
                SystemmgtUser user = GetSessionUtil.getSystemUser(req);
                String loginUser = "";
                if (user != null) {
                    loginUser = user.getUsername();
                }
                // ????
                String[] str = getSpLimitBrandBysupplierId(supplierSp.getId());
                // ???
                //String[] str1 = getSpLimitCatBysupplierId(supplierSp.getId());
                String[] str1 = this.getSpLimitBrandCatBysupplierId(supplierSp.getId());

                // ??
                SupplierSp supplierInfo = getSupplierSpById(supplierSp.getId());
                if (supplierInfo != null) {
                    if (str != null && str.length > 0) {
                        String brandStr = str[0];
                        if (StringUtils.isNotBlank(brandStr)) {
                            // ?
                            if (!brandStr.trim().equals(brandList.trim())) {
                                addMerhcantlog(supplierSp.getId(), "????",
                                        "???", brandStr, brandList, loginUser);
                            }
                        }
                    }
                }
                if (str1 != null && str1.length > 0) {
                    String catStr = str1[0];
                    if (StringUtils.isNotBlank(catStr)) {
                        // 
                        if (!catStr.trim().equals(catList.trim())) {
                            addMerhcantlog(supplierSp.getId(), "???",
                                    "??", catStr, catList, loginUser);
                        }
                    }
                }
            }
            //brand_no, key=uuid ???
            Map<String, String> brand_uuid_key = new HashMap<String, String>();
            Map<String, String> cat_uuid_key = new HashMap<String, String>();
            // ??
            if (StringUtils.isNotBlank(bankNoHidden)) {
                String[] brandNos = bankNoHidden.split(";");
                for (String brandNo : brandNos) {
                    if (StringUtils.isNotBlank(brandNo)) {
                        brand_uuid_key.put(brandNo, UUIDUtil.getUUID());
                        sqlService.updateObject(
                                "insert into tbl_sp_limit_brand(id, brand_no, supply_id) values(?, ?, ?)",
                                new Object[] { brand_uuid_key.get(brandNo), brandNo, supplierSp.getId() });
                    }
                }
            }
            /*
             *  [brand_no;struct_name]
             * ??-?
             */
            if (StringUtils.isNotBlank(catNameHidden)) {
                //[struct_name;brand_no]
                Set<String> cat_brand_list = new HashSet<String>();
                Set<String> struct_name_list = new HashSet<String>();
                String[] catNameStr = catNameHidden.split("_");

                for (String string : catNameStr) {
                    String[] catStr = string.split(";");
                    List<Category> temp_cats = null;
                    if (catStr.length >= 2) {
                        temp_cats = commodityBaseApiService.getCategoryListLikeStructName(catStr[1], (short) 1,
                                (short) 3);
                    }
                    if (CollectionUtils.isNotEmpty(temp_cats)) {
                        for (Category category : temp_cats) {
                            cat_brand_list.add(category.getStructName() + ";" + catStr[0]);
                            struct_name_list.add(category.getStructName());//StructName??
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(struct_name_list)) {
                    for (String struct_name : struct_name_list) {
                        Category _c = commodityBaseApiService.getCategoryByStructName(struct_name);
                        if (null == _c)
                            continue;

                        cat_uuid_key.put(struct_name, UUIDUtil.getUUID());
                        sqlService.updateObject(
                                "insert into tbl_sp_limit_cat(id, cat_no, supply_id, struct_name) values(?, ?, ?, ?)",
                                new Object[] { cat_uuid_key.get(struct_name), _c.getCatNo(), supplierSp.getId(),
                                        _c.getStructName() });
                    }
                }
                //??tbl_sp_limit_brandtbl_sp_limit_catid
                for (String string : cat_brand_list) {
                    if (StringUtils.isNotBlank(string)) {
                        String[] a = string.split(";");
                        sqlService.updateObject(
                                "insert into tbl_sp_limit_brand_cat(id, brand_id, cat_id) values(?, ?, ?)",
                                new Object[] { UUIDUtil.getUUID(), brand_uuid_key.get(a[1]),
                                        cat_uuid_key.get(a[0]) });
                    }
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("?Id???!", e);
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("?Id???!", e);
            e.printStackTrace();
        }
    }

    /**
     * ?? ?
     * 
     */
    private String formDate() {
        Date da = new Date();
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sim.format(da);
        return str;
    }

    /**
     * ?? Date?
     * 
     */
    private Date stringFormDate() {
        Date date = null;
        try {
            Date da = new Date();
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = sim.parse(sim.format(da));
            return date;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            logger.error("?? Date?!", e);
            e.printStackTrace();
        }
        return date;
    }

    /**
     * ????
     * 
     * @return
     * @throws Exception
     */
    @Deprecated
    public List<CostSetofBooks> getCostSetofBooksList() throws Exception {
        //List<CostSetofBooks> listCostSetOfBooks = costSetOfBooksDao.queryAllCostSetOfBooks();
        return null;
    }

    /**
     * ???
     * 
     * @author wang.m
     * @Date 2012-04-28
     */
    public PageFinder<SupplierSp> getSupplierSpList(SupplierSp supplierSp, Query query) {
        CritMap critMap = new CritMap();
        critMap.addEqual("supplierType", "");
        critMap.addEqual("isValid", 1);
        critMap.addEqual("deleteFlag", 1);//  1
        PageFinder<SupplierSp> supplierSpList = null;//supplierDaoImpl.pagedByCritMap(critMap, query.getPage(), query.getPageSize());
        //TODO
        return supplierSpList;
    }

    /**
     * ????
     * 
     * @author wang.m
     * @Date 2012-05-02
     */
    @Transactional
    public boolean saveExpressTemplate(HttpServletRequest req, MerchantExpressTemplate merchantExpressTemplate) {
        boolean bool = false;
        try {
            MerchantExpressTemplate template = new MerchantExpressTemplate();
            if (null != merchantExpressTemplate && StringUtils.isNotBlank(merchantExpressTemplate.getId())) {
                template.setId(merchantExpressTemplate.getId());
            }
            template.setBackGroundImage(merchantExpressTemplate.getBackGroundImage());
            template.setLogisticsId(merchantExpressTemplate.getLogisticsId());
            template.setWidth(merchantExpressTemplate.getWidth());
            template.setHeigth(merchantExpressTemplate.getHeigth());
            template.setCommodityNum(merchantExpressTemplate.getCommodityNum());
            template.setConsigneeAdress(merchantExpressTemplate.getConsigneeAdress());
            template.setConsigneeDay(merchantExpressTemplate.getConsigneeDay());
            template.setConsigneeEmail(merchantExpressTemplate.getConsigneeEmail());
            template.setConsigneeMonth(merchantExpressTemplate.getConsigneeMonth());
            template.setConsigneeName(merchantExpressTemplate.getConsigneeName());
            template.setConsigneeOneArea(merchantExpressTemplate.getConsigneeOneArea());
            template.setConsigneePhone(merchantExpressTemplate.getConsigneePhone());
            template.setConsigneeTell(merchantExpressTemplate.getConsigneeTell());
            template.setConsigneeThreeArea(merchantExpressTemplate.getConsigneeThreeArea());
            template.setConsigneeTwoArea(merchantExpressTemplate.getConsigneeTwoArea());
            template.setConsigneeYear(merchantExpressTemplate.getConsigneeYear());
            template.setExpressName(merchantExpressTemplate.getExpressName());
            template.setMoney(merchantExpressTemplate.getMoney());
            template.setNumber(merchantExpressTemplate.getNumber());
            template.setOrderSourceId(merchantExpressTemplate.getOrderSourceId());
            template.setOrderSubNo(merchantExpressTemplate.getOrderSubNo());
            template.setRemark(merchantExpressTemplate.getRemark());
            template.setShipmentsAdress(merchantExpressTemplate.getShipmentsAdress());
            template.setShipmentsEmail(merchantExpressTemplate.getShipmentsEmail());
            template.setShipmentsName(merchantExpressTemplate.getShipmentsName());
            template.setShipmentsOneArea(merchantExpressTemplate.getShipmentsOneArea());
            template.setShipmentsPhone(merchantExpressTemplate.getShipmentsPhone());
            template.setShipmentsTell(merchantExpressTemplate.getShipmentsTell());
            template.setShipmentsThreeArea(merchantExpressTemplate.getShipmentsThreeArea());
            template.setShipmentsTwoArea(merchantExpressTemplate.getShipmentsTwoArea());
            template.setIsBold(merchantExpressTemplate.getIsBold());
            template.setFontSize(merchantExpressTemplate.getFontSize());
            template.setTbody(merchantExpressTemplate.getTbody());
            merchantExpressTemplateDaoImpl.merge(template);
            bool = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("????!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * ???Id???
     */
    public MerchantExpressTemplate getExpressTemplateByLogisticsId(String id) {
        MerchantExpressTemplate merchantExpressTemplate = null;
        CritMap critMap = new CritMap();
        if (StringUtils.isNotBlank(id)) {
            critMap.addEqual("logisticsId", id);
            List<MerchantExpressTemplate> templateList = merchantExpressTemplateDaoImpl.findByCritMap(critMap);
            if (templateList != null && templateList.size() > 0) {
                merchantExpressTemplate = templateList.get(0);
            }
        }

        return merchantExpressTemplate;
    }

    /**
     * ????
     */
    public Map<String, Object> getMerchantConsignmentadress(String supplyid) {
        String sql = " SELECT t1.id,t1.consignment_name,t1.phone,t1.tell,t1.post_code,t1.area, "
                + " t1.adress FROM tbl_merchant_consignmentadress t1 where t1.supply_id='" + supplyid + "'";
        Map<String, Object> orderMap = sqlService.getDataBySql(sql, null, null);
        return orderMap;
    }

    /**
     * ??
     * 
     * @author wang.m
     * @date 2012-05-11
     */
    public PageFinder<MerchantRejectedAddress> getMerchantRejectedAddressList(Query query,
            MerchantRejectedAddress merchantRejectedAddress, String brand) {
        CritMap critMap = new CritMap();
        if (null != merchantRejectedAddress) {
            // ??
            if (StringUtils.isNotBlank(merchantRejectedAddress.getSupplierName())) {
                critMap.addLike("supplierName", merchantRejectedAddress.getSupplierName());
            }
            // ?
            if (StringUtils.isNotBlank(merchantRejectedAddress.getSupplierCode())) {
                critMap.addLike("supplierCode", merchantRejectedAddress.getSupplierCode());
            }
            // ??
            if (StringUtils.isNotBlank(merchantRejectedAddress.getConsigneeName())) {
                critMap.addLike("consigneeName", merchantRejectedAddress.getConsigneeName());
            }
            // 
            if (StringUtils.isNotBlank(merchantRejectedAddress.getConsigneePhone())) {
                critMap.addLike("consigneePhone", merchantRejectedAddress.getConsigneePhone());
            }
            // ?
            if (StringUtils.isNotBlank(merchantRejectedAddress.getConsigneeTell())) {
                critMap.addLike("consigneeTell", merchantRejectedAddress.getConsigneeTell());
            }
            // 
            List<String> merchantCodes = new ArrayList<String>();
            if (StringUtils.isNotBlank(merchantRejectedAddress.getSupplierYgContacts())) {
                merchantCodes = supplierYgContactService
                        .getSupplierList(merchantRejectedAddress.getSupplierYgContacts());

            }
            // ?
            List<String> merchantCodes_brand = new ArrayList<String>();
            if (StringUtils.isNotBlank(brand)) {
                List<Brand> brandList = commodityBaseApiService.getBrandListLikeBrandName("%" + brand, (short) 1);
                StringBuffer brand_in = new StringBuffer();
                if (CollectionUtils.isNotEmpty(brandList)) {
                    for (Brand brandVo : brandList) {
                        brand_in.append("\"" + brandVo.getBrandNo() + "\",");
                    }
                    if (brand_in.length() > 0) {
                        brand_in.setLength(brand_in.length() - 1);
                    }
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("brands", brand_in.toString());
                    merchantCodes_brand = merchantBrandMapper.queryMerchantByBrands(map);
                }
            }
            // ??merchantCodelist
            if (CollectionUtils.isNotEmpty(merchantCodes) && CollectionUtils.isNotEmpty(merchantCodes_brand)) {
                merchantCodes.retainAll(merchantCodes_brand);
                if (null != merchantCodes && merchantCodes.size() > 0) {
                    critMap.addIN("supplierCode", merchantCodes.toArray());
                }
            } else if (CollectionUtils.isNotEmpty(merchantCodes)) {
                critMap.addIN("supplierCode", merchantCodes.toArray());
            } else if (CollectionUtils.isNotEmpty(merchantCodes_brand)) {
                critMap.addIN("supplierCode", merchantCodes_brand.toArray());
            }

            critMap.addDesc("createrTime");
        }

        PageFinder<MerchantRejectedAddress> pageFinder = merchantRejectedAddressDaoImpl.pagedByCritMap(critMap,
                query.getPage(), query.getPageSize());

        // PageFinder<MerchantRejectedAddress> pageFinder =
        // merchantRejectedAddressDaoImpl.pagedByHQL(hql, toPage, pageSize,
        // values)
        return pageFinder;
    }

    /**
     * ????
     * 
     * @author wang.m
     * @date 2012-05-11
     */
    @Transactional
    public boolean saveMerchantRejectedAddress(HttpServletRequest req,
            MerchantRejectedAddress merchantRejectedAddress) {
        boolean bool = false;
        try {
            MerchantRejectedAddress reject = new MerchantRejectedAddress();
            // ?
            if (null != merchantRejectedAddress) {
                reject.setConsigneeName(merchantRejectedAddress.getConsigneeName());
                reject.setConsigneePhone(merchantRejectedAddress.getConsigneePhone());
                reject.setConsigneeTell(merchantRejectedAddress.getConsigneeTell());
                SystemmgtUser user = GetSessionUtil.getSystemUser(req);
                String loginUser = "";
                if (user != null) {
                    loginUser = user.getUsername();
                }
                reject.setCreaterPerson(loginUser);
                reject.setCreaterTime(formDate());
                reject.setSupplierName(merchantRejectedAddress.getSupplierName());
                reject.setSupplierCode(merchantRejectedAddress.getSupplierCode());
                reject.setWarehousePostcode(merchantRejectedAddress.getWarehousePostcode());
                reject.setWarehouseArea(merchantRejectedAddress.getWarehouseArea());
                reject.setWarehouseAdress(merchantRejectedAddress.getWarehouseAdress());

                String operationNotes;

                // ,
                if (StringUtils.isNotBlank(merchantRejectedAddress.getId())) {
                    reject.setId(merchantRejectedAddress.getId());
                    MerchantRejectedAddress rejectInfo = merchantRejectedAddressDaoImpl
                            .getById(merchantRejectedAddress.getId());
                    operationNotes = merchantOperationLogService
                            .buildMerchantAfterServiceAddrOperationNotes(rejectInfo, reject);
                    merchantRejectedAddressDaoImpl.merge(reject);

                } else {// ?
                    merchantRejectedAddressDaoImpl.save(reject);
                    operationNotes = merchantOperationLogService.buildMerchantAfterServiceAddrOperationNotes(null,
                            reject);
                }
                if (StringUtils.isNotBlank(operationNotes)) {
                    /** ? Modifier by yang.mq **/
                    MerchantOperationLog operationLog = new MerchantOperationLog();
                    operationLog.setMerchantCode(reject.getSupplierCode());
                    operationLog.setOperator(loginUser);
                    operationLog.setOperated(new Date());
                    operationLog.setOperationType(OperationType.AFTER_SERVICE);
                    operationLog.setOperationNotes(operationNotes);
                    merchantOperationLogService.saveMerchantOperationLog(operationLog);
                }

                bool = true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("????!", e);
            bool = false;
        }
        return bool;
    }

    /**
     * id??
     * 
     * @author wang.m
     * @date 2012-05-11
     */
    public MerchantRejectedAddress getMerchantRejectedAddressById(String id) {
        MerchantRejectedAddress merchantRejectedAddress = null;
        CritMap critMap = new CritMap();
        // ??
        if (StringUtils.isNotBlank(id)) {
            critMap.addEqual("id", id);
        }

        List<MerchantRejectedAddress> addressList = merchantRejectedAddressDaoImpl.findByCritMap(critMap);
        if (addressList != null && addressList.size() > 0) {
            merchantRejectedAddress = addressList.get(0);
        }
        return merchantRejectedAddress;
    }

    @Override
    public MerchantRejectedAddress getMerchantRejectedAddressByCode(String supplierCode) {
        MerchantRejectedAddress merchantRejectedAddress = null;
        CritMap critMap = new CritMap();
        // ??
        if (StringUtils.isNotBlank(supplierCode)) {
            critMap.addEqual("supplierCode", supplierCode);
        }

        List<MerchantRejectedAddress> addressList = merchantRejectedAddressDaoImpl.findByCritMap(critMap);
        if (addressList != null && addressList.size() > 0) {
            merchantRejectedAddress = addressList.get(0);
        }
        return merchantRejectedAddress;
    }

    /**
     * ?ID?
     * 
     * @param id
     * @return
     */
    public List<Map<String, Object>> getChildAreaByNo(String no, Integer level) {
        //      no = no + "-";
        //      String sql = " SELECT t1.name,t1.no FROM tbl_systemmg_area t1 WHERE t1.level= " + level + " and t1.no like '%" + no + "%'";
        //      List<Map<String, Object>> areaList = sqlService.getDatasBySql(sql, null, null, null);
        //      return areaList;
        List<Map<String, Object>> relist = new ArrayList<Map<String, Object>>();
        List<Area> areaList = areaApi.getChildAreaByNo(no);
        if (null != areaList && 0 < areaList.size()) {

            for (com.yougou.component.area.model.Area area : areaList) {
                if (area.getLevel() == level) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("name", area.getName());
                    map.put("no", area.getNo());
                    relist.add(map);
                }
            }
        }
        return relist;

    }

    /*
     * ???
     */
    public List<Map<String, Object>> getAreaList() {
        //      String sql = "SELECT t1.name,t1.no FROM tbl_systemmg_area t1 WHERE t1.level=1 ";
        //      List<Map<String, Object>> areaList = sqlService.getDatasBySql(sql, null, null, null);
        //      return areaList;
        List<Map<String, Object>> relist = new ArrayList<Map<String, Object>>();
        for (com.yougou.component.area.model.Area area : areaApi.getAreaByLevel(1)) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", area.getName());
            map.put("no", area.getNo());
            relist.add(map);
        }
        return relist;
    }

    /**
     * ???
     * 
     * @throws Exception
     */
    public boolean exictRejectedAddressCount(String supplierCode) {
        boolean bool = false;
        CritMap critMap = new CritMap();
        // ??
        if (StringUtils.isNotBlank(supplierCode)) {
            critMap.addEqual("supplierCode", supplierCode);
        } else {
            return bool;
        }
        List<MerchantRejectedAddress> addressList = merchantRejectedAddressDaoImpl.findByCritMap(critMap);
        if (addressList != null && addressList.size() > 0) {
            bool = true;
        }
        return bool;
    }

    /**
     * ??id
     * 
     * @author wang.m
     * @Date 2012-03-07
     */
    public String getSupplierSpBySupplier(String supplier) {
        String supplierId = null;
        if (StringUtils.isNotBlank(supplier)) {
            SupplierVo vo = new SupplierVo();
            vo.setSupplier(supplier);
            List<SupplierVo> list;
            try {
                list = supplierService.querySupplierByVo(vo);
            } catch (Exception e) {
                logger.error("Id??", e);
                return supplierId;
            }
            if (CollectionUtils.isNotEmpty(list)) {
                supplierId = list.get(0).getId();
            }
        }

        return supplierId;
    }

    /**
     * ?Id
     * 
     * @id Id
     * @author wang.m
     * @throws Exception
     */
    private boolean updateSupplierById(String id, HttpServletRequest req) {
        boolean bool = false;
        if (StringUtils.isNotBlank(id)) {
            try {
                String sql = "update tbl_sp_supplier set update_user=?,update_date=? where id=? and delete_flag=1 ";
                Object[] obj = new Object[3];
                SystemmgtUser user = GetSessionUtil.getSystemUser(req);
                String updateUser = "";
                if (user != null) {
                    updateUser = user.getUsername();
                }
                obj[0] = updateUser;// 
                // ??
                obj[1] = new Date();
                obj[2] = id;
                bool = sqlService.updateObject(sql, obj);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                logger.error("?Id!", e);
                bool = false;
            }
        }
        return bool;
    }

    /**
     * ??
     * 
     * @author wang.m
     * @param conductType
     *            
     * @param operateField
     *            ??
     * @param conductBeforeInfo
     *            ?
     * @param conductAfterInfo
     *            ?
     * @param updateUser
     *            
     */
    public Integer addMerhcantlog(String supplierId, String conductType, String operateField,
            String conductBeforeInfo, String conductAfterInfo, String updateUser) {
        Integer count = 0;
        try {
            String sql = "INSERT INTO tbl_sp_supplier_update_history VALUES(?,?,?,?,?,?,?,?)";
            Object[] obj = new Object[8];
            String uuid = UUIDGenerator.getUUID();
            obj[0] = uuid;
            obj[1] = supplierId;
            obj[2] = updateUser;// 
            obj[3] = formDate();// 
            obj[4] = conductType;// 
            obj[5] = operateField;// ??
            obj[6] = conductBeforeInfo;// ?
            obj[7] = conductAfterInfo;// ?
            boolean bool = sqlService.insertObject(sql, obj);
            if (bool) {
                count = 1;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("??!", e);
            e.printStackTrace();
        }
        return count;
    }

    /**
     * ??
     * 
     * @author wang.m
     * @param model
     * @return
     * @throws Exception
     */
    public PageFinder<Map<String, Object>> getSupplierUpdateHistoryList(Query query, MerchantsVo merchantsVo,
            String id) {
        PageFinder<Map<String, Object>> pageFinder = null;
        if (StringUtils.isNotBlank(id)) {
            String sql = "SELECT t2.supplier,t2.supplier_code,t1.update_field,t1.operator,t1.operation_time,t1.processing,t1.update_before,"
                    + " t1.update_after FROM tbl_sp_supplier_update_history t1 "
                    + " INNER JOIN tbl_sp_supplier t2 ON t1.supplier_id=t2.id "
                    + " WHERE t2.delete_flag=1 and t1.supplier_id='" + id + "'";

            // ?
            if (merchantsVo != null) {
                if (StringUtils.isNotBlank(merchantsVo.getSupplier())) {// ??
                    sql += " and t2.supplier like '%" + merchantsVo.getSupplier().trim() + "%' ";
                }
                if (StringUtils.isNotBlank(merchantsVo.getSupplierCode())) {// ?
                    sql += " and t2.supplier_code like '" + merchantsVo.getSupplierCode().trim() + "%'";
                }
            }

            sql += " ORDER BY t1.operation_time DESC";
            pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);

        }
        return pageFinder;
    }

    /*
     * ??
     * 
     * @author wang.m
     * 
     * @throws Exception
     */
    public List<Map<String, Object>> getTraderMaintainList() {
        String sql = "SELECT t1.id,t1.balance_trader_code,t1.balance_trader_name FROM TBL_FIN_TRADER_MAINTAIN t1 WHERE t1.is_del=1 ";
        List<Map<String, Object>> map = sqlService.getDatasBySql(sql, null, null, null);
        return map;
    }

    /**
     * ?
     * 
     * @author zhuang.rb
     * @Date 2013-01-18
     */
    public PageFinder<Map<String, Object>> queryYougouAdminMerchantList(Query query, String merchantUserId,
            String merchantCode, String merchantName, Integer isInputYougouWarehouse) {
        String sql = "SELECT t2.id,t1.supplier,t1.supplier_code,t1.is_input_yougou_warehouse,t1.delete_flag,t1.is_valid"
                + " FROM tbl_sp_supplier t1 INNER JOIN tbl_merchant_user_supplier t2 ON t1.supplier_code = t2.merchant_code"
                + " WHERE t2.merchant_user_id = '" + merchantUserId + "' AND t1.supplier_type=''";
        if (StringUtils.isNotBlank(merchantCode)) {
            sql += " AND t1.supplier_code LIKE '" + merchantCode.trim() + "%'";
        }
        if (StringUtils.isNotBlank(merchantName)) {
            sql += " AND t1.supplier LIKE '" + merchantName.trim() + "%'";
        }
        if (isInputYougouWarehouse != null) {
            sql += " AND t1.is_input_yougou_warehouse = '" + isInputYougouWarehouse + "'";
        }
        sql += " ORDER BY CONVERT(t1.supplier USING GBK)";
        PageFinder<Map<String, Object>> pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);
        return pageFinder;
    }

    /**
     * ??
     * 
     * @author zhuang.rb
     * @Date 2013-01-18
     */
    public PageFinder<Map<String, Object>> queryMerchantNotHadList(Query query, String merchantUserId,
            String merchantCode, String merchantName, Integer isInputYougouWarehouse) {
        String sql = "SELECT t1.supplier,t1.supplier_code,t1.is_input_yougou_warehouse,t1.delete_flag,t1.is_valid"
                + " FROM tbl_sp_supplier t1 WHERE NOT EXISTS"
                + " (SELECT t2.merchant_code FROM tbl_merchant_user_supplier t2 WHERE t1.supplier_code = t2.merchant_code AND t2.merchant_user_id = '"
                + merchantUserId + "')" + " AND t1.supplier_type='' AND t1.delete_flag = 1";
        if (StringUtils.isNotBlank(merchantCode)) {
            sql += " AND t1.supplier_code LIKE '" + merchantCode.trim() + "%'";
        }
        if (StringUtils.isNotBlank(merchantName)) {
            sql += " AND t1.supplier LIKE '%" + merchantName.trim() + "%'";
        }
        if (isInputYougouWarehouse != null) {
            sql += " AND t1.is_input_yougou_warehouse = '" + isInputYougouWarehouse + "'";
        }
        sql += " ORDER BY CONVERT(t1.supplier USING GBK)";
        PageFinder<Map<String, Object>> pageFinder = sqlService.getObjectsBySql(sql, query, null, null, null);
        return pageFinder;
    }

    /**
     * ?id??
     */
    @Transactional
    public boolean delYougouAdminsMerchant(String id) {
        boolean isDeleteSuccess = false;
        try {
            String sql = "DELETE FROM tbl_merchant_user_supplier WHERE id = ?";
            Object[] obj = new Object[1];
            obj[0] = id;
            sqlService.deleteObject(sql, obj);
            isDeleteSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("?id??!", e);
            isDeleteSuccess = false;
        }
        return isDeleteSuccess;
    }

    /**
     * ???
     */
    public boolean saveYougouAdminMerchant(String merchantUserId, String[] merchantCodes) throws Exception {
        boolean isSaveSuccess = false;
        try {
            if (StringUtils.isNotBlank(merchantUserId) && merchantCodes != null) {
                int length = merchantCodes.length;
                Map<String, List<Object[]>> mapYougouAdminMerchant = new HashMap<String, List<Object[]>>(1);
                List<Object[]> lstYougouAdminMerchant = new ArrayList<Object[]>(length);
                String sql = "INSERT INTO tbl_merchant_user_supplier (id, merchant_user_id, merchant_code) VALUES (?,?,?)";
                if (merchantCodes.length > 0) {
                    for (String merchantCode : merchantCodes) {
                        Object[] obj = new Object[3];
                        String uuid = UUIDGenerator.getUUID();
                        obj[0] = uuid;
                        obj[1] = merchantUserId;
                        obj[2] = merchantCode;
                        lstYougouAdminMerchant.add(obj);
                    }
                }
                mapYougouAdminMerchant.put(sql, lstYougouAdminMerchant);
                sqlService.batchAllSaveOrUpdate(mapYougouAdminMerchant);
                isSaveSuccess = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("???!", ex);
            isSaveSuccess = false;
        }
        return isSaveSuccess;
    }

    @Override
    public boolean update_user_auth(String roleId) {
        boolean flag = false;
        try {
            List<UserRole> userRoles = userAuthorityDao.findBy("roleId", roleId, false);
            for (UserRole ur : userRoles) {
                loadAuthResource(ur.getUserId());
            }
            flag = true;
        } catch (Exception e) {
            logger.error("????{}", e);
        }
        return flag;
    }

    /**
     * distributeAuthResourceToChildRen:?????? 
     * @author li.n1 
     * @param userId ?ID
     * @param id ??ID
     * @throws Exception 
     * @since JDK 1.6
     */
    private void distributeAuthResourceToChildRen(String userId, String id) throws Exception {
        // ?
        long enter = System.currentTimeMillis();
        Set<String> authrityUrls = null;
        Set<String> childauthrityUrls = null;
        Document document = XmlTool
                .createDocument(MerchantsService.class.getClassLoader().getResource("authority.xml").getPath());
        Map<String, List<MerchantsAuthorityVo>> _map = null;
        Map<String, List<MerchantsAuthorityVo>> _childmap = null;
        List<MerchantsAuthorityVo> auths = this.getMerchantAuthorityById(id);
        Map<String, Set<String>> authReseMap = (Map<String, Set<String>>) redisTemplate.opsForHash()
                .get(Constant.C_USER_REOURCE_AUTH, "authReourecesMap");
        //????url
        if (authReseMap != null) {
            authrityUrls = authReseMap.get(userId);
            childauthrityUrls = authReseMap.get(id);
        }
        Map<String, Map<String, List<MerchantsAuthorityVo>>> aMap = (Map<String, Map<String, List<MerchantsAuthorityVo>>>) redisTemplate
                .opsForHash().get(Constant.C_USER_AUTH, "authMap");
        //?????
        if (aMap != null) {
            _map = aMap.get(userId);
            _childmap = aMap.get(id);
        }
        for (MerchantsAuthorityVo _authority : auths) {
            if (authrityUrls != null && !(authrityUrls.contains("/" + _authority.getAuthrityURL()))) {
                //????????????
                DefaultElement node = (DefaultElement) XmlTool.findElementByProperty(document, "url",
                        _authority.getAuthrityURL());
                if (node != null) {
                    for (Object obj : node.elements()) {
                        childauthrityUrls.remove(XmlTool.getAttributeVal((Element) obj, "url"));
                    }
                }
                childauthrityUrls.remove("/" + _authority.getAuthrityURL());
            }
            MerchantsAuthority auth = merchantsAuthorityDaoImpl.findUniqueBy("id", _authority.getParentAuthrityId(),
                    false);
            if (_map != null && !(_map.containsKey(auth.getAuthrityName() + "@~" + auth.getSortNo()))) {
                //????????????
                _childmap.remove(auth.getAuthrityName() + "@~" + auth.getSortNo());
            }
        }
        if (authReseMap != null) {
            authReseMap.remove(id);
            authReseMap.put(id, childauthrityUrls);
            redisTemplate.opsForHash().put(Constant.C_USER_REOURCE_AUTH, "authReourecesMap", authReseMap);
        }
        if (aMap != null) {
            aMap.remove(id);
            aMap.put(id, _childmap);
            redisTemplate.opsForHash().put(Constant.C_USER_AUTH, "authMap", aMap);
        }
        //this.addUserAuthority(id, id, null);
        System.out.println("======spent time(unit:s):=======" + (System.currentTimeMillis() - enter) / 1000.0);
    }

    @Override
    public void loadAuthResource(String userId) throws Exception {
        long enter = System.currentTimeMillis();
        Set<String> authrityUrls = null;
        Document document = XmlTool
                .createDocument(MerchantsService.class.getClassLoader().getResource("authority.xml").getPath());
        Element root = XmlTool.getRootElement(document);
        Element indexElement = root.element("index");
        Element menuEle = null;
        String key = "";
        List<MerchantsAuthorityVo> childAuthorityList = null;
        Map<String, List<MerchantsAuthorityVo>> _map = null;
        List<MerchantsAuthorityVo> auths = this.getMerchantAuthorityById(userId);
        _map = new TreeMap<String, List<MerchantsAuthorityVo>>(new AuthorityComparator());
        authrityUrls = new HashSet<String>();
        for (MerchantsAuthorityVo _authority : auths) {
            //parenAuth = merchantsAuthorityDaoImpl.findUniqueBy("id", _authority.getParentId(), false);
            if (StringUtils.isNotBlank(_authority.getAuthrityURL())) {
                for (Iterator<Element> it = root.elementIterator(); it.hasNext();) {
                    menuEle = it.next();
                    if (_authority.getAuthrityURL().indexOf(XmlTool.getAttributeVal(menuEle, "url")) != -1) {
                        for (Iterator<Element> eit = menuEle.elementIterator(); eit.hasNext();) {
                            authrityUrls.add(XmlTool.getAttributeVal(eit.next(), "url"));
                        }
                        break;
                    }
                }
                authrityUrls.add("/" + _authority.getAuthrityURL());
            }
            key = _authority.getParentAuthrityName() + "@~" + _authority.getSortNo();
            childAuthorityList = _map.get(key);
            if (childAuthorityList == null) {
                childAuthorityList = new ArrayList<MerchantsAuthorityVo>();
                _map.put(key, childAuthorityList);
            }
            childAuthorityList.add(_authority);
        }

        for (Iterator<Element> indexIt = indexElement.elementIterator(); indexIt.hasNext();) {
            authrityUrls.add(XmlTool.getAttributeVal(indexIt.next(), "url"));
        }

        Map<String, Set<String>> authReseMap = (Map<String, Set<String>>) redisTemplate.opsForHash()
                .get(Constant.C_USER_REOURCE_AUTH, "authReourecesMap");
        if (authReseMap != null) {
            authReseMap.remove(userId);
            authReseMap.put(userId, authrityUrls);
            redisTemplate.opsForHash().put(Constant.C_USER_REOURCE_AUTH, "authReourecesMap", authReseMap);
        }
        Map<String, Map<String, List<MerchantsAuthorityVo>>> aMap = (Map<String, Map<String, List<MerchantsAuthorityVo>>>) redisTemplate
                .opsForHash().get(Constant.C_USER_AUTH, "authMap");
        if (aMap != null) {
            aMap.remove(userId);
            aMap.put(userId, _map);
            redisTemplate.opsForHash().put(Constant.C_USER_AUTH, "authMap", aMap);
        }

        //???redis
        //??
        //????????????
        //??????
        MerchantUser user = merchantUserDaoImpl.findUniqueBy("id", userId, false);
        CritMap map = new CritMap();
        map.addEqual("deleteFlag", 1);//  1
        map.addEqual("status", 1); //??
        map.addEqual("isAdministrator", 0);// ??
        map.addEqual("merchantCode", user.getMerchantCode());// ??
        List<MerchantUser> childMerUser = merchantUserDaoImpl.findByCritMap(map, false);
        for (MerchantUser u : childMerUser) {
            distributeAuthResourceToChildRen(user.getId(), u.getId());
        }
        System.out.println("======spent time(unit:s):=======" + (System.currentTimeMillis() - enter) / 1000.0);
    }

    private List<MerchantsAuthorityVo> getMerchantAuthorityById(String id) {
        List<MerchantsAuthorityVo> authList = new ArrayList<MerchantsAuthorityVo>();
        StringBuffer sb = new StringBuffer();
        sb.append(
                "SELECT * FROM ( SELECT t2.authrity_name,t2.authrity_url,t2.parent_id,t3.authrity_name AS parent_authrityname,");
        sb.append("t3.sort_no,t2.sort_no as c_sort_no FROM tbl_merchant_user_authority t1");
        sb.append(
                " INNER JOIN tbl_merchant_authority t2 ON t1.authority_id = t2.id LEFT JOIN tbl_merchant_authority t3 ON t2.parent_id = t3.id");
        sb.append(" WHERE t1.user_id = '" + id
                + "' AND t2.authrity_module != 0 UNION SELECT t22.authrity_name,t22.authrity_url,t22.parent_id,");
        sb.append(
                " t23.authrity_name AS parent_AuthrityName,t23.sort_no,t22.sort_no as c_sort_no FROM tbl_merchant_role_authority t11");
        sb.append(
                " INNER JOIN tbl_merchant_authority t22 ON t11.authority_id = t22.id LEFT JOIN tbl_merchant_authority t23 ON t22.parent_id = t23.id");
        sb.append(
                " INNER JOIN tbl_merchant_user_role r11 ON t11.role_id = r11.role_id INNER JOIN tbl_merchant_role r22 ON t11.role_id = r22.id");
        sb.append(" WHERE r11.user_id = '" + id + "' AND r22.`status` = '1' ) AS s ORDER BY s.sort_no,s.c_sort_no");
        List<Map<String, Object>> listMap = sqlService.getDatasBySql(sb.toString());
        MerchantsAuthorityVo methAuth = null;
        for (Map<String, Object> map : listMap) {
            methAuth = new MerchantsAuthorityVo();
            methAuth.setAuthrityURL((String) map.get("authrity_url"));
            methAuth.setAuthrityName((String) map.get("authrity_name"));
            methAuth.setParentAuthrityId((String) map.get("parent_id"));
            methAuth.setParentAuthrityName((String) map.get("parent_authrityname"));
            methAuth.setSortNo((Integer) map.get("sort_no"));
            authList.add(methAuth);
        }
        return authList;
    }

    /**
     * ??? 
     * @see com.belle.yitiansystem.merchant.service.IMerchantsService#existsTelePhoneInMerchants(java.lang.String)
     * @param ????
     * @param ????
     * @return true  ??  false ???
     */
    @Override
    public boolean existsTelePhoneInMerchants(String mobileCode, String name) {
        // ?
        if (StringUtils.isNotBlank(mobileCode)) {
            CritMap critMap = new CritMap();
            critMap.addEqual("mobileCode", mobileCode.trim());
            critMap.addEqual("deleteFlag", 1);//  1
            if (StringUtils.isNotBlank(name)) {
                critMap.addNotEqual("loginName", name);//?? 
            }
            List<MerchantUser> merchantUser = merchantUserDaoImpl.findByCritMap(critMap);
            if (merchantUser != null && merchantUser.size() > 0) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public void delAuthResource(String userId) throws Exception {
        long enter = System.currentTimeMillis();
        Set<String> authrityUrls = null;
        Document document = XmlTool
                .createDocument(MerchantsService.class.getClassLoader().getResource("authority.xml").getPath());
        Element root = XmlTool.getRootElement(document);
        Element indexElement = root.element("index");
        authrityUrls = new HashSet<String>();
        List<MerchantsAuthorityVo> auths = this.getMerchantAuthorityById(userId);
        for (Iterator<Element> indexIt = indexElement.elementIterator(); indexIt.hasNext();) {
            authrityUrls.add(XmlTool.getAttributeVal(indexIt.next(), "url"));
        }

        Map<String, Set<String>> authReseMap = (Map<String, Set<String>>) redisTemplate.opsForHash()
                .get(Constant.C_USER_REOURCE_AUTH, "authReourecesMap");
        if (authReseMap != null) {
            authReseMap.remove(userId);
            authReseMap.put(userId, authrityUrls);
            redisTemplate.opsForHash().put(Constant.C_USER_REOURCE_AUTH, "authReourecesMap", authReseMap);
        }
        Map<String, Map<String, List<MerchantsAuthorityVo>>> aMap = (Map<String, Map<String, List<MerchantsAuthorityVo>>>) redisTemplate
                .opsForHash().get(Constant.C_USER_AUTH, "authMap");
        if (aMap != null) {
            aMap.remove(userId);
            aMap.put(userId, new TreeMap<String, List<MerchantsAuthorityVo>>(new AuthorityComparator()));
            redisTemplate.opsForHash().put(Constant.C_USER_AUTH, "authMap", aMap);
        }
        Map<String, Integer> userAuthCountMap = (Map<String, Integer>) redisTemplate.opsForHash()
                .get(CacheConstant.C_USERS_AUTH_COUNT, "authCount");

        if (userAuthCountMap != null) {
            userAuthCountMap.remove(userId);
            userAuthCountMap.put(userId, auths != null ? auths.size() : 0);
            redisTemplate.opsForHash().put(CacheConstant.C_USERS_AUTH_COUNT, "authCount", userAuthCountMap);
        }
        //???redis
        //??
        //????????????
        //??????
        MerchantUser user = merchantUserDaoImpl.findUniqueBy("id", userId, false);
        CritMap map = new CritMap();
        map.addEqual("deleteFlag", 1);//  1
        map.addEqual("status", 1); //??
        map.addEqual("isAdministrator", 0);// ??
        map.addEqual("merchantCode", user.getMerchantCode());// ??
        List<MerchantUser> childMerUser = merchantUserDaoImpl.findByCritMap(map, false);
        for (MerchantUser u : childMerUser) {
            distributeAuthResourceToChildRen(user.getId(), u.getId());
        }
        System.out.println("======spent time(unit:s):=======" + (System.currentTimeMillis() - enter) / 1000.0);
    }

    @Override
    public int deleteCacheByKey(String key) {
        int result = 0;
        Long len1 = 0L, len2 = 0L, len3 = 0L, len4 = 0L, len5 = 0L;
        try {
            len1 = redisTemplate.opsForHash().size(key);
        } catch (Exception e) {
            len1 = 0L;
            logger.error("redisTemplate.opsForHash()?");
        }
        try {
            len2 = redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            len2 = 0L;
            logger.error("redisTemplate.opsForList()?");
        }
        try {
            len3 = redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            len3 = 0L;
            logger.error("redisTemplate.opsForSet()?");
        }
        try {
            len4 = redisTemplate.opsForValue().size(key);
        } catch (Exception e) {
            len4 = 0L;
            logger.error("redisTemplate.opsForValue()?");
        }
        try {
            len5 = redisTemplate.opsForZSet().size(key);
        } catch (Exception e) {
            len5 = 0L;
            logger.error("redisTemplate.opsForZSet()?");
        }
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            logger.error("redisTemplate.delete??", e);
        }
        if (NumberUtils.toInt(String.valueOf(len1)) > 0) {
            result += len1;
        }
        if (NumberUtils.toInt(String.valueOf(len2)) > 0) {
            result += len2;
        }
        if (NumberUtils.toInt(String.valueOf(len3)) > 0) {
            result += len3;
        }
        if (NumberUtils.toInt(String.valueOf(len4)) > 0) {
            result += len4;
        }
        if (NumberUtils.toInt(String.valueOf(len5)) > 0) {
            result += len5;
        }
        return result;
    }

    @Override
    public List<Cat> buildBrandCatSecondLevelList(String supplierId) throws Exception {
        List<Cat> result = null;
        if (StringUtils.isNotEmpty(supplierId)) {

            // ??
            List<com.yougou.kaidian.common.commodity.pojo.Brand> resultList = merchantBrandMapper
                    .querySecondLevelCatsBySupplierId(supplierId);
            if (null != resultList && 0 < resultList.size()) {
                result = new ArrayList<Cat>();
                Map<String, Brand> accordingMapForBrand = new HashMap<String, Brand>();
                Map<String, Category> accordingMapForCatFirst = new HashMap<String, Category>();
                for (com.yougou.kaidian.common.commodity.pojo.Brand brand : resultList) {
                    String brand_NO = brand.getBrandNo();
                    String cat_struct = brand.getBrandName();
                    if (StringUtils.isEmpty(brand_NO) || StringUtils.isEmpty(cat_struct)) {
                        continue;
                    }
                    String first_cat_struct = cat_struct.substring(0, 2);
                    Cat category = new Cat();

                    Brand brandVo = null;
                    if (accordingMapForBrand.containsKey(brand_NO)) {
                        brandVo = accordingMapForBrand.get(brand_NO);
                    } else {
                        brandVo = commodityBaseApiService.getBrandByNo(brand_NO);
                        accordingMapForBrand.put(brand_NO, brandVo);
                    }

                    Category catFirst = null;
                    if (accordingMapForCatFirst.containsKey(first_cat_struct)) {
                        catFirst = accordingMapForCatFirst.get(first_cat_struct);
                    } else {
                        catFirst = commodityBaseApiService.getCategoryByStructName(first_cat_struct);
                        accordingMapForCatFirst.put(first_cat_struct, catFirst);
                    }

                    Category catSecond = commodityBaseApiService.getCategoryByStructName(cat_struct);

                    if (null != brandVo) {
                        category.setNo(brandVo.getBrandName());
                    }
                    if (null != catFirst) {
                        category.setCatName(catFirst.getCatName());
                    }
                    if (null != catSecond) {
                        category.setStructName(catSecond.getCatName());
                    }
                    result.add(category);
                }
            }

        }
        return result;
    }

}

/**
 * ??
 * @author zhuang.rb
 *
 */
class GBKOrder extends Order {
    private static final long serialVersionUID = 1L;
    private String encoding = "GBK";
    private boolean ascending;
    private boolean ignoreCase;
    private String propertyName;

    @Override
    public String toString() {
        return "CONVERT( " + propertyName + " USING " + encoding + " ) " + (ascending ? "asc" : "desc");
    }

    @Override
    public Order ignoreCase() {
        ignoreCase = true;
        return this;
    }

    protected GBKOrder(String propertyName, boolean ascending) {
        super(propertyName, ascending);
        this.propertyName = propertyName;
        this.ascending = ascending;
    }

    @Override
    public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
        String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);
        Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName);
        StringBuffer fragment = new StringBuffer();
        for (int i = 0; i < columns.length; i++) {
            SessionFactoryImplementor factory = criteriaQuery.getFactory();
            boolean lower = ignoreCase && type.sqlTypes(factory)[i] == Types.VARCHAR;
            if (lower) {
                fragment.append(factory.getDialect().getLowercaseFunction()).append('(');
            }
            fragment.append("CONVERT( " + columns[i] + " USING " + encoding + " )");
            if (lower)
                fragment.append(')');
            fragment.append(ascending ? " asc" : " desc");
            if (i < columns.length - 1)
                fragment.append(", ");
        }
        return fragment.toString();
    }

    /**  
     * Ascending order  
     *   
     * @param propertyName  
     * @return Order  
     */
    public static Order asc(String propertyName) {
        return new GBKOrder(propertyName, true);
    }

    /**  
     * Descending order  
     *   
     * @param propertyName  
     * @return Order  
     */
    public static Order desc(String propertyName) {
        return new GBKOrder(propertyName, false);
    }

}