/**
 *
 */
package com.foc.hrm.service;

import java.sql.SQLException;
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.hrm.entity.UserEntity;
import com.foc.phone.area.PhoneAreaEntity;
import com.foc.phone.area.PhoneAreaUtil;
import com.foc.seat.entity.SeatEntity;
import com.foc.util.DBHandler;
import com.foc.util.DBHelper;
import com.foc.util.Util;

/**
 * 
 * @team IT Team
 * @author renmb
 * @version 1.0
 * @time  2016年10月30日
 */
public class HRMUpdatePreMobileService {

    QueryRunner run = null;
    public HRMUpdatePreMobileService(){
        
        try {
            this.run = new QueryRunner(DBHelper.getDataSource());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void start(boolean isUpdateMobile) {
        
        ResultSetHandler<List<UserEntity>> handler = new BeanListHandler<UserEntity>(UserEntity.class);
        String query = "SELECT *,phone_number AS phoneNumber,mobile_nubmer AS mobileNubmer,premobile_confirmed AS premobileConfirmed FROM " + Constants.SYS_USER ;
                //+ " WHERE id='1000866011'";//premobile_confirmed='UNCONFIRMED'";// +" WHERE mobile LIKE '%＋%'";
        List<UserEntity> list = null;
        try {
            list = run.query(query, handler);
            if (list != null && list.size() != 0){
                
                for(UserEntity user:list){
                    if(isUpdateMobile && (StringUtils.isBlank(user.getMobileNubmer()) || 
                            !user.getMobileNubmer().contains(user.getMobile()))){// 此手机号未处理过
                        
                        updatePreMobile(user.getMobile(), user.getId());// 格式化手机号码
                    }
                    updateWorkPhone(user.getPhone(), user.getPhoneNumber(), user.getId());// 格式化座机号码
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 席位电话处理
        ResultSetHandler<List<SeatEntity>> seatHandler = new BeanListHandler<SeatEntity>(SeatEntity.class);
        String sql = "SELECT `id`, `seat_name` AS seatName,`seat_phone` AS seatPhone,`seat_phone_number` AS seatPhoneNumber FROM " + Constants.FOC_SEATS ;
                //+ " WHERE id='1000866011'";//premobile_confirmed='UNCONFIRMED'";// +" WHERE mobile LIKE '%＋%'";
        List<SeatEntity> seatList = null;
        try {
            seatList = run.query(sql, seatHandler);
            if (seatList != null && seatList.size() != 0){
                
                for(SeatEntity seat:seatList){
                    
                    updateSeatPhone(seat.getSeatPhone(), seat.getSeatPhoneNumber(), seat.getId());// 格式化座机号码
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public String getWorkPhone(String workPhone) {
        
        if(StringUtils.isNotBlank(workPhone)){
            workPhone = workPhone.replaceAll("[^\\d|+]+", "");
//            if(workPhone.length() < 7 || workPhone.matches("0+"))
            if(workPhone.matches("0+")){
                workPhone = "";
            } else if(workPhone.startsWith("0") == false){// 非0开头的号码需要处理
                if(workPhone.startsWith("1") && workPhone.length() == 11){
                    
                    workPhone = "";
                }
            }
            if(workPhone.startsWith("+") == false){// 外国号码前面加拨3个000
                
                workPhone = workPhone.replace("+", "");
            }
        } else {
            
            workPhone = "";
        }
        return workPhone;
    }
    private boolean updateSeatPhone(String phone, String lastShowPhone, String seatId) {
        try {
            String showPhone = Util.formatedWorkPhone(phone);
            if(showPhone.equals(lastShowPhone) == false){// 号码有变化
                
                DBHandler dBHandler = new DBHandler();
                Map<String, Object> columnMap = new TreeMap<String, Object>();
                Map<String, Object> whereMap = new TreeMap<String, Object>();
                
                columnMap.put("seat_phone_number", showPhone);
                whereMap.put("id", seatId);
                dBHandler.update(Constants.FOC_SEATS, columnMap, whereMap);
            }
            return true;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    private boolean updateWorkPhone(String phone, String lastShowPhone, String userId) {
        try {
//            if(StringUtils.isBlank(phone))
//                phone = "";
            String workPhone = getWorkPhone(phone);
//            if(StringUtils.isBlank(phone))
//                return false;
            if(workPhone.equals(phone) == false){// 号码有变化
                
                DBHandler dBHandler = new DBHandler();
                Map<String, Object> columnMap = new TreeMap<String, Object>();
                Map<String, Object> whereMap = new TreeMap<String, Object>();
                
                columnMap.put("phone", workPhone);
                whereMap.put("id", userId);
                dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
            }
            
            String phoneNumber = Util.formatedWorkPhone(workPhone);
            if(phoneNumber.equals(lastShowPhone) == false){// 号码有变化
                
                DBHandler dBHandler = new DBHandler();
                Map<String, Object> columnMap = new TreeMap<String, Object>();
                Map<String, Object> whereMap = new TreeMap<String, Object>();
                
                columnMap.put("phone_number", phoneNumber);
                whereMap.put("id", userId);
                dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
            }
            return true;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    /**
     * 修改手机号前加拨0
     * 1、 北京手机号前加拨1个0
     * 2、 国内非北京手机号加拨2个0
     * 3、 国外手机号前面加拨3个0
     * 
     * @author renmb
     * @time  2016年10月30日
     * @param mobile
     * @param userId
     */
    private boolean updatePreMobile(String mobile, String userId) {
        try {
            if(StringUtils.isBlank(mobile))
                return false;
            DBHandler dBHandler = new DBHandler();
            Map<String, Object> columnMap = new TreeMap<String, Object>();
            Map<String, Object> whereMap = new TreeMap<String, Object>();

            String[] species = mobile.split("\\s+");// 只使用第一个手机号
            if(species.length>1 && species[0].matches("1\\d+") && species[1].matches("1\\d+")){
                
                mobile = species[0];
            }
            mobile = mobile.replaceAll("＋", "+");// 处理错误字符
            mobile = mobile.replaceAll("[^0-9|+]+", "");// 将非电话号码替换为空
            System.out.println("mobile:"+mobile);
            if(StringUtils.isBlank(mobile)){// 手机号不存在
                
                return false;
            } else if(mobile.startsWith("+")){// 国外手机号，前面加拨3个0
                
                columnMap.put("premobile", "000");
                columnMap.put("mobile_nubmer", "000"+mobile.replace("+", ""));
                
                whereMap.put("id", userId);
                dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
                
                return true;
            } else if(mobile.matches("\\d+")){
                PhoneAreaEntity area = PhoneAreaUtil.get360PhoneArea(mobile);
                if(area != null && StringUtils.isNotBlank(area.getProvince())){// 能够查到省份信息
                    
                    if(area.getProvince().contains("北京")
                            || (StringUtils.isNotBlank(area.getCity()) && area.getCity().contains("北京"))){// 北京前面加拨一个0
                        
                        columnMap.put("mobile_nubmer", "0"+mobile);// 加拨1个0
                        columnMap.put("premobile", "0");
                        columnMap.put("mobile_province", "北京");
                        columnMap.put("mobile_city", "北京");
                        columnMap.put("mobile_sp", StringUtils.isBlank(area.getSp()) ? "" : area.getSp());
                    } else {// 非北京号码加拨两个0
                        
                        columnMap.put("mobile_nubmer", "00"+mobile);// 加拨2个0
                        columnMap.put("premobile", "00");
                        columnMap.put("mobile_province", area.getProvince());
                        columnMap.put("mobile_city", StringUtils.isBlank(area.getCity()) ? "" : area.getCity());
                        columnMap.put("mobile_sp", StringUtils.isBlank(area.getSp()) ? "" : area.getSp());
                    }
                    whereMap.put("id", userId);
                    dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
                    
                    return true;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
//    public static void main(String[] args){
//        String getMobileNubmer = null;//"01A212";
//        String getMobile = "1212";
//        boolean isUpdateMobile = true;
//        if(isUpdateMobile && (StringUtils.isBlank(getMobileNubmer) || 
//                !getMobileNubmer.contains(getMobile))){// 此手机号未处理过
//            System.out.println("updatePreMobile(user.getMobile(), user.getId())");
//        }
//        System.out.println("END");
//    }
}
