/**
 *
 */
package com.foc.flight.assignment;

import java.sql.SQLException;
import java.util.ArrayList;
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.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foc.conf.HistoryConfig;
import com.foc.util.DBHandler;
import com.foc.util.DBHelper;
import com.foc.util.DateUtil;
import com.foc.util.IdWorker;
import com.foc.version.VersionService;

/**
 * 
 * @team IT Team
 * @author renmb
 * @version 1.0
 * @time  2016年11月28日
 */
public class FlightAssignmentService {
    private QueryRunner run = null;

    private VersionService versionService = new VersionService();
    
    public FlightAssignmentService() {
        try {
            this.run = new QueryRunner(DBHelper.getDataSource());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void finish(String flightDate, String lastVersion, String currentVersion){
        if(StringUtils.isBlank(lastVersion)){
            lastVersion = "";
            versionService.addCurrentVersion("ASSIGNMENT", flightDate, currentVersion);
        } else {
            
            versionService.updateCurrentVersion("ASSIGNMENT", flightDate, currentVersion);
        }
        long startTime = System.nanoTime();
        this.updateVersionStatus(flightDate, lastVersion, "0");// 将上次的所有数据设置为0
        this.updateVersionStatus(flightDate, currentVersion, "1");// 设置本次本为可用
        this.deleteLastAssignmentVersion(flightDate, lastVersion, "0");// 删除删除版本的数据
        this.deleteLastAssignmentFlightNoVersion(flightDate, lastVersion);// 删除对照表信息
        this.deleteLastAssignmentToOdsVersion(flightDate, lastVersion);
        
        long endTime  = System.nanoTime();
        long duration = endTime - startTime;
        System.out.println("【finish】处理时间：" + DateUtil.getDurationTime(duration));
        HistoryConfig.put("assignment.last.version", lastVersion);// 上次版本号
        HistoryConfig.put("assignment.current.use.version", currentVersion);// 当前使用版本
        HistoryConfig.saveHistory();
    }
    public boolean handle(final String currentVersion, final String flightDate, final JSONObject result, final String modified) {
        JSONObject dataJson = (JSONObject) result.get("data");
        JSONArray jsonArray = (JSONArray) dataJson.get("result");

        if (jsonArray != null && jsonArray.size()>0) {
            List<FlightAssignmentEntity> list = JSON.parseArray(jsonArray.toJSONString(), FlightAssignmentEntity.class);
            int index = 1;
            int size = list.size();
            for (int i=0;i<size;i++) {
                System.out.println("版本号【"+currentVersion+"】第【"+index+"】行");
                FlightAssignmentEntity entity = list.get(i);
                this.addFlightAssignment(currentVersion, flightDate, entity, modified);
                index++;
            }
            return size>0;
        }
        return false;
    }
    
    public void addFlightAssignment(String currentVersion, String flightDate, FlightAssignmentEntity entity, final String modified){
        List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> columnMap = new TreeMap<String, Object>();
        
        String assignmentId = IdWorker.getNextId();
        columnMap.put("id", assignmentId);
        columnMap.put("accd", getStringValue(entity.getAccd(), null));
        columnMap.put("flight_report_id", getStringValue(entity.getFlightReportId(), null));
        columnMap.put("steward_deadhead_ops_staff_no", getStringValue(entity.getStewardDeadheadOpsStaffNo(), null));
        columnMap.put("steward_cap1", getStringValue(entity.getStewardCap1(), null));
        columnMap.put("flt_ids", getStringValue(entity.getFltIds(), null));
        columnMap.put("captain", getStringValue(entity.getCaptain(), null));
        columnMap.put("signature_date", getStringValue(entity.getSignatureDate(), null));
        columnMap.put("chief_steward_captain", getStringValue(entity.getChiefStewardCaptain(), null));
        columnMap.put("inspected_pilot_staff_no", getStringValue(entity.getInspectedPilotStaffNo(), null));
        columnMap.put("pub_id", getStringValue(entity.getPubId(), null));
        columnMap.put("steward_checker_staff_no", getStringValue(entity.getStewardCheckerStaffNo(), null));
        columnMap.put("first_vice1_remark", getStringValue(entity.getFirstVice1Remark(), null));
        columnMap.put("safer1_staff_no", getStringValue(entity.getSafer1StaffNo(), null));
        columnMap.put("steward_deadhead_ops", getStringValue(entity.getStewardDeadheadOps(), null));
        columnMap.put("stewards_staff_no", getStringValue(entity.getStewardsStaffNo(), null));
        columnMap.put("captain_staff_no", getStringValue(entity.getCaptainStaffNo(), null));
        columnMap.put("pilot_checker_staff_no", getStringValue(entity.getPilotCheckerStaffNo(), null));
        columnMap.put("signature_image_url", getStringValue(entity.getSignatureImageUrl(), null));
        columnMap.put("steward_deadhead_other", getStringValue(entity.getStewardDeadheadOther(), null));
        columnMap.put("check_type", getStringValue(entity.getCheckType(), null));
        columnMap.put("updated_time", getStringValue(entity.getUpdatedTime(), null));
        columnMap.put("dep_times", getStringValue(entity.getDepTimes(), null));
        columnMap.put("crw_pilot_inf", getStringValue(entity.getCrwPilotInf(), null));
        columnMap.put("safer1", getStringValue(entity.getSafer1(), null));
        columnMap.put("stcs", getStringValue(entity.getStcs(), null));
        columnMap.put("flt_date", getStringValue(entity.getFltDate(), null));
        columnMap.put("flight_date", flightDate);
        columnMap.put("std", getStringValue(entity.getStd(), null));
        columnMap.put("chief_steward_captain_staff_no", getStringValue(entity.getChiefStewardCaptainStaffNo(), null));
        columnMap.put("first_vice1", getStringValue(entity.getFirstVice1(), null));
        columnMap.put("first_vice1_staff_no", getStringValue(entity.getFirstVice1StaffNo(), null));
        columnMap.put("company_name", getStringValue(entity.getCompanyName(), null));
        columnMap.put("deleted", getStringValue(entity.getDeleted(), null));
        columnMap.put("company_code", getStringValue(entity.getCompanyCode(), null));
        columnMap.put("pilot_checker", getStringValue(entity.getPilotChecker(), null));
        columnMap.put("fly_times", getStringValue(entity.getFlyTimes(), null));
        columnMap.put("steward_cap1_staff_no", getStringValue(entity.getStewardCap1StaffNo(), null));
        columnMap.put("crw_steward_inf", getStringValue(entity.getCrwStewardInf(), null));
        columnMap.put("routes", getStringValue(entity.getRoutes(), null));
        columnMap.put("captain_remark", getStringValue(entity.getCaptainRemark(), null));
        columnMap.put("steward_checker", getStringValue(entity.getStewardChecker(), null));
        columnMap.put("ac", getStringValue(entity.getAc(), null));
        columnMap.put("moddt", getStringValue(entity.getModdt(), null));
        columnMap.put("company_id", getStringValue(entity.getCompanyId(), null));
        columnMap.put("steward_deadhead_other_staff_no", getStringValue(entity.getStewardDeadheadOtherStaffNo(), null));
        columnMap.put("stewards", getStringValue(entity.getStewards(), null));
        columnMap.put("ods_id", getStringValue(entity.getOdsId(), null));
        columnMap.put("arr_times", getStringValue(entity.getArrTimes(), null));
        
        columnMap.put("pilot_deadhead_ops", getStringValue(entity.getPilotDeadheadOps(), ""));
        columnMap.put("pilot_deadhead_ops_staff_no", getStringValue(entity.getPilotDeadheadOpsStaffNo(), ""));
        
        columnMap.put("version_name", currentVersion);
        columnMap.put("version_status", 0);
        
        columnMap.put("modified", modified);
        
        columnMapList.add(columnMap);

        // 批量插入数据
        DBHandler dBHandler = new DBHandler();
        dBHandler.batchInsert("foc_flight_assignment", columnMapList);
        
        if(entity.getFltIds() != null && entity.getFltIds().length()>0){
//            String[] routes = null;
//            if(entity.getRoutes() != null && entity.getRoutes().length()>0)
//                routes = entity.getRoutes().split("/");
            String[] ids = entity.getFltIds().split("/");
            for (String flightNo:ids) {
                
                this.addFlightToAssignment(assignmentId, flightNo, flightDate,currentVersion);
            }
        }
        String stewar = getStringValue(entity.getStewardDeadheadOpsStaffNo(), null);
        if(StringUtils.isNotEmpty(stewar)){
            
            String[] stewars = stewar.split("/");
            for (String userId:stewars) {
                
                userId = userId.replaceAll("[^\\d]", "");
//                userId = userId.split("\\*")[0];
                this.addAssignmentToOds(assignmentId, flightDate, userId, "STEWARD", currentVersion);
            }
        }
        String pilot = getStringValue(entity.getPilotDeadheadOpsStaffNo(), "");
        if(StringUtils.isNotEmpty(pilot)){
            
            String[] pilots = pilot.split("/");
            for (String userId:pilots) {
                
                userId = userId.replaceAll("[^\\d]", "");
//                userId = userId.split("\\*")[0];
                this.addAssignmentToOds(assignmentId, flightDate, userId, "PILOT", currentVersion);
            }
        }
    }
    public String getStringValue(Object object, String want){
        
        if(object == null || StringUtils.isEmpty(String.valueOf(object)))
            return want;
        return String.valueOf(object);
    }
    /**
     * 修改计划书的状态
     * 
     * @author renmb
     * @time  2016年12月12日
     * @param flightDate
     * @param versionName
     * @param versionStatus
     * @return
     */
    public boolean updateVersionStatus(String flightDate, String versionName, String versionStatus){
        try {
            if(StringUtils.isNotEmpty(versionName)){
                String sql = "UPDATE foc_flight_assignment SET version_status=? WHERE version_name=? AND flight_date=?";
                System.out.println(sql+"["+versionStatus+","+versionName+","+flightDate+"]");
                int count = run.update(sql, versionStatus, versionName, flightDate);
                if(count>0)
                    return true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    public boolean deleteLastAssignmentVersion(String flightDate, String versionName, String versionStatus){
        try {
            if(StringUtils.isNotEmpty(versionName)){
                String sql = "DELETE FROM foc_flight_assignment WHERE version_status=? AND version_name=? AND flight_date=?";
                System.out.println(sql+"["+versionStatus+","+versionName+","+flightDate+"]");
                int count = run.update(sql, versionStatus, versionName, flightDate);
                if(count>0)
                    return true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    public boolean deleteLastAssignmentFlightNoVersion(String flightDate, String versionName){
        try {
            if(StringUtils.isNotEmpty(versionName)){
                String sql = "DELETE FROM foc_flight2assignment WHERE version_name=? AND flight_date=?";
                System.out.println(sql+"["+versionName+"]["+flightDate+"]");
                int count = run.update(sql, versionName, flightDate);
                if(count>0)
                    return true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    public void addFlightToAssignment(String assignmentId, String flightNo,String flightDate, String currentVersion){
        try {
            if(StringUtils.isBlank(flightNo) || existFlightToAssignment(assignmentId, flightNo))
                return ;
            
            List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
            Map<String, Object> columnMap = new TreeMap<String, Object>();
            
            columnMap.put("assignment_id", assignmentId);
            columnMap.put("flight_date",   flightDate);
            columnMap.put("flight_no", flightNo);
            columnMap.put("version_name", currentVersion);
            
            columnMapList.add(columnMap);
            
            // 批量插入数据
            DBHandler dBHandler = new DBHandler();
            dBHandler.batchInsert("foc_flight2assignment", columnMapList);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
//    public boolean updateLastAssignmentFlightNoVersion(String assignmentId, String flightNo, String versionName){
//        try {
//            if(StringUtils.isNotEmpty(versionName)){
//                String sql = "UPDATE foc_flight2assignment SET version_name=? WHERE assignment_id=? AND flight_no = ?";
//                System.out.println(sql+"["+versionName+"]["+assignmentId+"]["+flightNo+"]");
//                int count = run.update(sql, versionName, assignmentId, flightNo);
//                if(count>0)
//                    return true;
//            }
//        } catch (Exception e) {
//            // TODO: handle exception
//        }
//        return false;
//    }
    public boolean existFlightToAssignment(String assignmentId, String flightNo) {
        
        try {
            ResultSetHandler<List<FlightToAssignmentEntity>> handler = new BeanListHandler<FlightToAssignmentEntity>(
                    FlightToAssignmentEntity.class);
            String query = "SELECT assignment_id AS assignmentId, flight_no AS flightNo"
                    + " FROM foc_flight2assignment WHERE assignment_id ='" + assignmentId
                    + "' and flight_no = '" + flightNo+"'";
            List<FlightToAssignmentEntity> list = null;
            
            list = run.query(query, handler);
            if (list != null && list.size() > 0) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    /**
     * STEWARD steward_deadhead_ops_staff_no
     * PILOT  pilot_deadhead_ops_staff_no
     * 
     * @author renmb
     * @time  2017年1月6日
     * @param assignmentId
     * @param flightDate
     * @param userId
     * @param currentVersion
     */
    public void addAssignmentToOds(String assignmentId, String flightDate, String userId, String type, String currentVersion){
        try {
            if(StringUtils.isEmpty(userId) || existAssignmentToOds(assignmentId, userId))
                return ;
            List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
            Map<String, Object> columnMap = new TreeMap<String, Object>();
            
            columnMap.put("assignment_id", assignmentId);
            columnMap.put("flight_date",   flightDate);
            columnMap.put("user_id",   userId);
            columnMap.put("assignment_type",   type);// STEWARD PILOT
            columnMap.put("version_name", currentVersion);
            
            columnMapList.add(columnMap);
            
            // 批量插入数据
            DBHandler dBHandler = new DBHandler();
            dBHandler.batchInsert("foc_assignment2ods", columnMapList);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    public boolean existAssignmentToOds(String assignmentId,String userId) {
        
        try {
            ResultSetHandler<List<FlightToAssignmentEntity>> handler = new BeanListHandler<FlightToAssignmentEntity>(
                    FlightToAssignmentEntity.class);
            String query = "SELECT assignment_id AS assignmentId, flight_date AS flightDate, user_id as userId"
                    + " FROM foc_assignment2ods WHERE assignment_id = ? AND user_id = ?";
            List<FlightToAssignmentEntity> list = null;
            
            list = run.query(query, handler, assignmentId, userId);
            if (list != null && list.size() > 0) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    public boolean deleteLastAssignmentToOdsVersion(String flightDate, String versionName){
        try {
            if(StringUtils.isNotEmpty(versionName)){
                String sql = "DELETE FROM foc_assignment2ods WHERE version_name=?  AND flight_date = ?";
                System.out.println(sql+"["+versionName+"]["+flightDate+"]");
                int count = run.update(sql, versionName, flightDate);
                if(count>0)
                    return true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    
//    public static void main(String[] args){
//        String pilot = "1000807279*(CKG-CGO)/1000195581*(CKG-CGO)/1000854416*(CKG-CGO)/1000191428*(CKG-CGO)/1000833089*(CKG-CGO)/1000189822*(CKG-CGO)/1000025909*(CKG-CGO)/1000104116*(CKG-CGO)";//getStringValue(entity.getPilotDeadheadOpsStaffNo(), "");
//        if(StringUtils.isNotEmpty(pilot)){
//            
//            String[] pilots = pilot.split("/");
//            for (String userId:pilots) {
//                
////                userId = userId.replaceAll("[^\\d]", "");
//                System.out.println(userId.split("\\*")[0]);
////                this.addAssignmentToOds(assignmentId, flightDate, userId, "PILOT", currentVersion);
//            }
//        }
//    }
}
