package com.foc.office.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang3.StringUtils;

import com.foc.conf.Constants;
import com.foc.conf.GConstants;
import com.foc.office.entity.OfficeEntity;
import com.foc.util.DBHandler;
import com.foc.util.DBHelper;
import com.foc.util.DateUtil;
import com.foc.util.IdWorker;

public class OfficeService {

    QueryRunner run = null;
    public OfficeService() {
        try {
            this.run = new QueryRunner(DBHelper.getDataSource());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public OfficeService(QueryRunner run) {
        
        this.run = run;
    }
    public OfficeEntity getOfficedById(String officeId) {
        
        try {
            ResultSetHandler<List<OfficeEntity>> handler = new BeanListHandler<OfficeEntity>(OfficeEntity.class);
//            String query = "SELECT * FROM sys_office WHERE id ='" + officeId + "'";
            
            String query = "SELECT o.id,o.`name`,o.parent_id AS parentId,o.parent_ids AS parentIds,o.create_date AS createDate "
                    + "FROM sys_office o WHERE o.id ='" + officeId + "'";
            
            List<OfficeEntity> list = this.run.query(query, handler);
            if (list != null && list.size() > 0) {
                
                return list.get(0);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }
    
    public String findFullName(String officeId){
        String fullName = null;
        OfficeEntity office = this.getOfficedById(officeId);
        while (office != null) {
            if(fullName == null){
                fullName = office.getName();
            } else {
                fullName = office.getName()+"-"+fullName;
            }
            office = this.getOfficedById(office.getParentId());
        }
        return fullName;
    }
    public OfficeEntity getOfficeByName(String name, String parentId){
        try {
            if(StringUtils.isBlank(parentId))
                parentId = "0";
            ResultSetHandler<List<OfficeEntity>> handler = new BeanListHandler<OfficeEntity>(OfficeEntity.class);
            String query = "SELECT o.id,o.`name`,o.parent_id AS parentId,o.parent_ids AS parentIds,o.create_date AS createDate "
                    + "FROM sys_office o WHERE o.name ='" + name + "' AND o.parent_id='"+parentId+"'";
            List<OfficeEntity> list = this.run.query(query, handler);
            if (list != null && list.size() > 0) {
                
                return list.get(0);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }
    public String findOfficeByName(String name, String parentId){
        String fullName = null;
        OfficeEntity office = this.getOfficeByName(name, parentId);
        while (office != null) {
            if(fullName == null){
                fullName = office.getName();
            } else {
                fullName = office.getName()+"-"+fullName;
            }
            office = this.getOfficedById(office.getParentId());
        }
        return fullName;
    }
    /**
     * 添加一个部门信息
     * 
     * @author renmb
     * @time  2016年10月3日
     * @param fullName
     * @return
     */
    public OfficeEntity addOffice(String fullName){
        if(StringUtils.isBlank(fullName)){
            
            fullName = "其他";
        }
        fullName = fullName.replaceAll("[\\+|\\s+]", "");
        String[] species = fullName.split("-");
        String parentId = null;
        String parentIds = null;
        OfficeEntity office = null;
        for(int i=0;i<species.length;i++){
            if(i == 0){// 公司
                
                office = this.insertOffice(species[i], "1", parentId, parentIds);
                parentId  = office.getId();
                parentIds = office.getParentIds()+parentId+",";
            } else {// 部门
                
                office = this.insertOffice(species[i], "2", parentId, parentIds);
                parentId = office.getId();
                parentIds = office.getParentIds()+parentId+",";
            }
        }
        return office;
    }
    /**
     * type:
     * 1   公司
     * 2   部门
     * 3   小组
     * 4   其它
     * 
     * @author renmb
     * @time  2016年10月3日
     * @param name
     * @param type
     * @param parentId
     * @param parentIds
     */
    private OfficeEntity insertOffice(String name, String type, String parentId, String parentIds) {

        OfficeEntity office = this.getOfficeByName(name, parentId);
        if(office == null){
            
            List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();

            String officeId = IdWorker.getNextId();
            Map<String, Object> columnMap = new TreeMap<String, Object>();
            // 字段和值绑定
            columnMap.put("name", name);
            columnMap.put("id",   officeId);
            if (parentId == null) {
                columnMap.put("parent_id", "0");
                columnMap.put("parent_ids", "0,");
                columnMap.put("type", "1");
            } else {
                columnMap.put("parent_id", parentId);
                columnMap.put("parent_ids", parentIds);
                columnMap.put("type", "2");
            }
            columnMap.put("area_id", GConstants.getValue("default.area.id", "1"));
            columnMap.put("USEABLE", "1");
            columnMap.put("type", type);
            columnMap.put("sort", "30");
            columnMap.put("grade", "1");
            columnMap.put("create_by", "1");
            columnMap.put("create_date", DateUtil.dateToStr(new Date(), DateUtil.TIMEF_FORMAT));
            columnMap.put("update_by", "1");
            columnMap.put("update_date", DateUtil.dateToStr(new Date(), DateUtil.TIMEF_FORMAT));
            columnMap.put("del_flag", "0");

            columnMapList.add(columnMap);

            // 批量插入数据
            DBHandler dBHandler = new DBHandler();
            dBHandler.batchInsert(Constants.SYS_OFFICE, columnMapList);
            
            return this.getOfficedById(officeId);
        }
        return office;
    }
    public static void main(String[] args){
        
        String fullName = "北京首都航空有限公司A-电商事业部A-IT中心A";
        OfficeService officeService = new OfficeService();
        officeService.addOffice(fullName);
    }
}
