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

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;
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 java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author renmb
 * @version 1.0
 * @team IT Team
 * @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.matches("0+")) {
                workPhone = "";
                // 非0开头的号码需要处理
            } else if (workPhone.startsWith("0") == false) {
                if (workPhone.startsWith("1") && workPhone.length() == 11) {
                    workPhone = "";
                }
            }
            // 外国号码前面加拨3个000
            if (workPhone.startsWith("+") == false) {
                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 {
            String workPhone = getWorkPhone(phone);
            // 号码有变化
            if (!workPhone.equals(phone)) {

                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
     *
     * @param mobile
     * @param userId
     * @author renmb
     * @time 2016年10月30日
     */
    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^,^#|+]+", "");
            // 手机号不存在
            if (StringUtils.isBlank(mobile)) {
                return false;
                // 国外手机号，前面加拨3个0
            } else if (mobile.startsWith("+")) {
                columnMap.put("premobile", "000");
                columnMap.put("mobile_nubmer", "000" + mobile.replace("+", ""));
                whereMap.put("id", userId);
                System.out.println(mobile + ":国外号码更改后,mobile_number=" + columnMap.get("mobile_nubmer"));
                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("北京")
                            // 北京前面加拨一个0
                            || (StringUtils.isNotBlank(area.getCity()) && area.getCity().contains("北京"))) {
                        // 加拨1个0
                        columnMap.put("mobile_nubmer", "0" + mobile);
                        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);
                        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);
                    System.out.println(mobile + ":查到归属地,mobile_number=" + columnMap.get("mobile_nubmer"));
                    dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
                    return true;
                }
            }
            //否则mobile=mobile_number
            columnMap.put("mobile_nubmer", mobile);
            columnMap.put("premobile", "");
            columnMap.put("mobile_province", "");
            columnMap.put("mobile_city", "");
            columnMap.put("mobile_sp", "");
            whereMap.put("id", userId);
            System.out.println(mobile + ":手机号码不改变,mobile=mobile_number");
            dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
            return true;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }

    public static void main(String[] args) {
        HRMUpdatePreMobileService service = new HRMUpdatePreMobileService();
//        System.out.println(service.updatePreMobile("00013803779497", "1"));
        System.out.println(service.updateWorkPhone("00016462485041,9694264088,053601046310#", "", "1"));
//        System.out.println(service.getWorkPhone("00016462485041,9694264088,053601046310#"));
//        System.out.println(service.updatePreMobile("00016462485041,9694264088,053601046310#","1"));
    }
}
