<?php
/**
 * @desc 物流报价生效
 */
class Process_ShipFeeProcess
{
    protected static $_date;
    protected static $_date_end;
    protected static $_userId;
    private static $_instance;

    public function __construct()
    {
        self::$_userId = Service_User::getUserId();
        self::$_date = date('Y-m-d');
        self::$_date_end = date('Y-m-d', strtotime("-1 days"));
    }

    public static function getInstance() 
    { 
        if ( is_null(self::$_instance) ) {
            self::$_instance = new self();
        } 
        return self::$_instance; 
    }
    
    /**
     * [ description]
     * @return [type] [description]
     */
    public static function run($type = 'price'){
        //$data = serviceClass
        switch ($type) {
            //区间计费
            case 'price':
                self::makeShipPriceActive();
                break;
            //首续重
            case 'weight':
                self::makeShipWeightPriceActive();
                break;
            //客户价格
            case 'customerPrice':
                self::makeCustomerShipPriceActive();
                break;
            //客户首续重
            case 'customerWeight';
                self::makeCustomerShipWeightPriceActive();
                break;
            default:
                self::makeShipPriceActive();
                break;
        }
    }

    /**
     * [makeShipPriceActive 处理区间计费报价]
     * @return [type] [description]
     */
    private static function makeShipPriceActive(){
        $condition = array(
            'date_start_day' => self::$_date
        );
        $count = Service_ShipPriceTemp::getByCondition($condition, 'count(*)');
        if($count > 0){
            $tempData = Service_ShipPriceTemp::getByCondition($condition, array('warehouse_code', 'sm_code', 'area'), 0, 0, array('date_start asc', 'warehouse_code', 'area'), array('warehouse_code', 'sm_code', 'area'));
            if(!empty($tempData) && is_array($tempData)){
                foreach ($tempData as $tempRow) {
                    $db = Common_Common::getAdapter();
                    $db->beginTransaction();
                    try {
                        $doChangeDataArr = $tempToActiveIdArr =  array();

                        $tempCondition = array(
                            'warehouse_code' => $tempRow['warehouse_code'],
                            'sm_code' => $tempRow['sm_code'],
                            'area' => $tempRow['area'],
                            'date_start_day' => self::$_date
                        );
                        $tempAllData = Service_ShipPriceTemp::getByCondition($tempCondition);
                    
                        $activeCondition = array(
                            'warehouse_code' => $tempRow['warehouse_code'],
                            'sm_code' => $tempRow['sm_code'],
                            'area' => $tempRow['area'],
                            //排除永久生效数据
                            'date_start_no_day' => '0000-00-00',
                            'date_end_no_day' => '9999-12-31'
                        );
                        $activeData = Service_ShipPrice::getByCondition($activeCondition);
                        if(is_array($activeData) && !empty($activeData)){
                            //throw new Exception('查询生效数据条件'.var_export($activeCondition, true).'暂无数据处理');
                            foreach ($activeData as $activeRow) {
                                if(!in_array($activeRow['sp_id'], $doChangeDataArr)){
                                    $doChangeDataArr[] = $activeRow['sp_id'];
                                }
                            }
                            if(is_array($tempAllData) && !empty($tempAllData)){
                                self::$_date_end = date('Y-m-d', strtotime($tempAllData[0]['date_start']) - 86400 );
                            }
                            //更新原有数据有效期为失效
                            if(Service_ShipPrice::batchUpdate(array('date_end' => self::$_date_end), $doChangeDataArr, 'sp_id') === false){
                                throw new Exception('更新有效期失败');
                            }
                            //失效数据移动
                            if(Service_ShipPrice::batchCopyToHistory($doChangeDataArr, 'sp_id') === false){
                                throw new Exception('移动报价到历史表失败');
                            }
                            //删除原始数据
                            if(Service_ShipPrice::batchDelete($doChangeDataArr, 'sp_id') === false){
                                throw new Exception('删除生效原始数据失败');
                            }
                        }

                        if(is_array($tempAllData) && !empty($tempAllData)){
                            //throw new Exception('查询临时数据条件'.var_export($tempCondition, true).'暂无数据处理');
                            foreach ($tempAllData as $tempAllRow) {
                                if(!in_array($tempAllRow['sp_id'], $tempToActiveIdArr)){
                                    $tempToActiveIdArr[] = $tempAllRow['sp_id'];
                                }
                            }
                            //生效数据移动
                            if(Service_ShipPrice::batchCopyTempToActive($tempToActiveIdArr, 'sp_id') === false){
                                throw new Exception('临时数据表移动至生效数据表失败');
                            }
                            //删除临时数据
                            if(Service_ShipPriceTemp::batchDelete($tempToActiveIdArr, 'sp_id') === false){
                                throw new Exception('删除临时数据失败');   
                            }
                        }
                        self::debug('数据表ship_price_temp条件'.var_export($tempCondition, true).'处理结果：本次总共生效'.count($tempToActiveIdArr).'条报价,生效报价ID'.var_export($tempToActiveIdArr, true).',失效'.count($doChangeDataArr).'条报价,失效报价ID'.var_export($doChangeDataArr, true));
                        //$db->rollBack();
                        $db->commit();
                    } catch (Exception $e) {
                        $db->rollBack();
                        self::debug($e->getMessage());
                        continue;
                    }
                }
            }

        }        
    }

    /**
     * [makeShipPriceActive 客户区间计费报价]
     * @return [type] [description]
     */
    private static function makeCustomerShipPriceActive(){
        $condition = array(
            'date_start_day' => self::$_date
        );
        $configs = array();
        $count = Service_ShipCustomerPriceTemp::getByCondition($condition, 'count(*)');
        if($count > 0){
            $tempData = Service_ShipCustomerPriceTemp::getByCondition($condition, array('customer_code','warehouse_id', 'sm_code', 'area'), 0, 0, array('date_start asc', 'customer_code', 'warehouse_id', 'area'), array('customer_code','warehouse_id', 'sm_code', 'area'));
            if(!empty($tempData) && is_array($tempData)){
                foreach ($tempData as $tempRow) {
                    $db = Common_Common::getAdapter();
                    $db->beginTransaction();
                    try {
                        $doChangeDataArr = $tempToActiveIdArr =  array();

                        $tempCondition = array(
                            'warehouse_id' => $tempRow['warehouse_id'],
                            'sm_code' => $tempRow['sm_code'],
                            'area' => $tempRow['area'],
                            'customer_code' => $tempRow['customer_code'],
                            'date_start_day' => self::$_date
                        );
                        $tempAllData = Service_ShipCustomerPriceTemp::getByCondition($tempCondition);

                        $activeCondition = array(
                            'warehouse_id' => $tempRow['warehouse_id'],
                            'sm_code' => $tempRow['sm_code'],
                            'area' => $tempRow['area'],
                            'customer_code' => $tempRow['customer_code'],
                            //排除永久生效数据
                            'date_start_no_day' => '0000-00-00',
                            'date_end_no_day' => '9999-12-31'
                        );
                        $activeData = Service_ShipCustomerPrice::getByCondition($activeCondition);
                        if(is_array($activeData) && !empty($activeData)){
                            //throw new Exception('查询生效数据条件'.var_export($activeCondition, true).'暂无数据处理');
                            foreach ($activeData as $activeRow) {
                                if(!in_array($activeRow['scp_id'], $doChangeDataArr)){
                                    $doChangeDataArr[] = $activeRow['scp_id'];
                                }
                            }
                            if(is_array($tempAllData) && !empty($tempAllData)){
                                self::$_date_end = date('Y-m-d', strtotime($tempAllData[0]['date_start']) - 86400 );
                            }
                            //更新原有数据有效期为失效
                            if(Service_ShipCustomerPrice::batchUpdate(array('date_end' => self::$_date_end), $doChangeDataArr, 'scp_id') === false){
                                throw new Exception('ship_customer_price更新有效期失败');
                            }
                            //失效数据移动
                            if(Service_ShipCustomerPrice::copyToHistory($doChangeDataArr, 'scp_id') === false){
                                throw new Exception('ship_customer_price移动报价到历史表失败');
                            }
                            //删除原始数据
                            if(Service_ShipCustomerPrice::batchDeleteCustomerPrice($doChangeDataArr, 'scp_id') === false){
                                throw new Exception('ship_customer_price删除生效原始数据失败');
                            }
                        }

                        if(is_array($tempAllData) && !empty($tempAllData)){
                            //throw new Exception('查询临时数据条件'.var_export($tempCondition, true).'暂无数据处理');
                            foreach ($tempAllData as $tempAllRow) {
                                if(!in_array($tempAllRow['scpt_id'], $tempToActiveIdArr)){
                                    $tempToActiveIdArr[] = $tempAllRow['scpt_id'];
                                }
                            }
                            //生效数据移动
                            if(Service_ShipCustomerPrice::batchCopyTempToActive($tempToActiveIdArr, 'scpt_id') === false){
                                throw new Exception('ship_customer_price临时数据表移动至生效数据表失败');
                            }
                            //删除临时数据
                            if(Service_ShipCustomerPriceTemp::batchDelete($tempToActiveIdArr, 'scpt_id') === false){
                                throw new Exception('ship_customer_price_temp删除临时数据失败');
                            }
                        }

                        $k = $tempRow['warehouse_id'].$tempRow['customer_code'].$tempRow['sm_code'];
                        if( !isset($configs[$k]) ) {
                            $configs[$k] = 1;
                            $config = array(
                                'warehouse_id' => $tempRow['warehouse_id'],
                                'customer_code' => $tempRow['customer_code'],
                                'sm_code' => $tempRow['sm_code']
                            );
                            self::addCustomerConfig( $config );
                        }

                        self::debug('数据表ship_customer_price_temp条件'.var_export($tempCondition, true).'处理结果：本次总共生效'.count($tempToActiveIdArr).'条报价,生效报价ID'.var_export($tempToActiveIdArr, true).',失效'.count($doChangeDataArr).'条报价,失效报价ID'.var_export($doChangeDataArr, true));

                        $db->commit();
                    } catch (Exception $e) {
                        $db->rollBack();
                        print_r($e);
                        self::debug($e->getMessage());
                        continue;
                    }
                }
            }

        }
    }

    /**
     * [makeShipWeightPriceActive 处理首续重报价]
     * @return [type] [description]
     */
    private static function makeShipWeightPriceActive(){
        $condition = array(
            'date_start_day' => self::$_date
        );
        $count = Service_ShipWeightPriceTemp::getByCondition($condition, 'count(*)');
        if($count > 0){
            $tempData = Service_ShipWeightPriceTemp::getByCondition($condition, array('warehouse_code', 'sm_code', 'area'), 0, 0, array('date_start', 'warehouse_code', 'area'), array('warehouse_code', 'sm_code', 'area'));
            if(!empty($tempData) && is_array($tempData)){
                foreach ($tempData as $tempRow) {
                    $db = Common_Common::getAdapter();
                    $db->beginTransaction();
                    try {
                        $doChangeDataArr = $tempToActiveIdArr =  array();
                        
                        $tempCondition = array(
                            'warehouse_code' => $tempRow['warehouse_code'],
                            'sm_code' => $tempRow['sm_code'],
                            'area' => $tempRow['area'],
                            'date_start_day' => self::$_date
                        );
                        $tempAllData = Service_ShipWeightPriceTemp::getByCondition($tempCondition);
                        
                        $activeCondition = array(
                            'warehouse_code' => $tempRow['warehouse_code'],
                            'sm_code' => $tempRow['sm_code'],
                            'area' => $tempRow['area'],
                            //排除永久生效数据
                            'date_start_no_day' => '0000-00-00',
                            'date_end_no_day' => '9999-12-31'
                        );
                        $activeData = Service_ShipWeightPrice::getByCondition($activeCondition);
                        if(is_array($activeData) && !empty($activeData)){
                            //throw new Exception('查询生效数据条件'.var_export($activeCondition, true).'暂无数据处理');
                            foreach ($activeData as $activeRow) {
                                if(!in_array($activeRow['swp_id'], $doChangeDataArr)){
                                    $doChangeDataArr[] = $activeRow['swp_id'];
                                }
                            }
                            if(is_array($tempAllData) && !empty($tempAllData)){
                                self::$_date_end =  date('Y-m-d', strtotime($tempAllData[0]['date_start']) - 86400 );
                            }
                            //更新原有数据有效期为失效
                            if(Service_ShipWeightPrice::batchUpdate(array('date_end' => self::$_date_end), $doChangeDataArr, 'swp_id') === false){
                                throw new Exception('更新有效期失败');
                            }
                            //失效数据移动
                            if(Service_ShipWeightPrice::batchCopyToHistory($doChangeDataArr, 'swp_id') === false){
                                throw new Exception('移动报价到历史表失败');
                            }
                            //删除原始数据
                            if(Service_ShipWeightPrice::batchDelete($doChangeDataArr, 'swp_id') === false){
                                throw new Exception('删除生效原始数据失败');
                            }
                        }

                        if(is_array($tempAllData) && !empty($tempAllData)){
                            //throw new Exception('查询临时数据条件'.var_export($tempCondition, true).'暂无数据处理');
                            foreach ($tempAllData as $tempAllRow) {
                                if(!in_array($tempAllRow['swp_id'], $tempToActiveIdArr)){
                                    $tempToActiveIdArr[] = $tempAllRow['swp_id'];
                                }
                            }
                            //生效数据移动
                            if(Service_ShipWeightPrice::batchCopyTempToActive($tempToActiveIdArr, 'swp_id') === false){
                                throw new Exception('临时数据表移动至生效数据表失败');
                            }
                            //删除临时数据
                            if(Service_ShipWeightPriceTemp::batchDelete($tempToActiveIdArr, 'swp_id') === false){
                                throw new Exception('删除临时数据失败');   
                            }
                        }
                        self::debug('数据表ship_weight_price_temp条件'.var_export($tempCondition, true).'处理结果：本次总共生效'.count($tempToActiveIdArr).'条报价,生效报价ID'.var_export($tempToActiveIdArr, true).',失效'.count($doChangeDataArr).'条报价,失效报价ID'.var_export($doChangeDataArr, true));
                        //$db->rollBack();
                        $db->commit();
                    } catch (Exception $e) {
                        $db->rollBack();
                        self::debug($e->getMessage());
                        continue;
                    }
                }
            }
        }    
    }


    /**
     * [makeShipWeightPriceActive 处理首续重报价]
     * @return [type] [description]
     */
    private static function makeCustomerShipWeightPriceActive(){
        $condition = array(
            'date_start_day' => self::$_date
        );
        $configs = array();
        $count = Service_ShipCustomerWeightPriceTemp::getByCondition($condition, 'count(*)');
        if($count > 0){
            $tempData = Service_ShipCustomerWeightPriceTemp::getByCondition($condition, array('customer_code','warehouse_id', 'sm_code', 'area'), 0, 0, array('date_start', 'customer_code','warehouse_id', 'area'), array('customer_code','warehouse_id', 'sm_code', 'area'));
            if(!empty($tempData) && is_array($tempData)){
                foreach ($tempData as $tempRow) {
                    $db = Common_Common::getAdapter();
                    $db->beginTransaction();
                    try {
                        $doChangeDataArr = $tempToActiveIdArr =  array();

                        $tempCondition = array(
                            'warehouse_id' => $tempRow['warehouse_id'],
                            'sm_code' => $tempRow['sm_code'],
                            'area' => $tempRow['area'],
                            'customer_code' => $tempRow['customer_code'],
                            'date_start_day' => self::$_date
                        );
                        $tempAllData = Service_ShipCustomerWeightPriceTemp::getByCondition($tempCondition);

                        $activeCondition = array(
                            'warehouse_code' => $tempRow['warehouse_code'],
                            'sm_code' => $tempRow['sm_code'],
                            'area' => $tempRow['area'],
                            'customer_code' => $tempRow['customer_code'],
                            //排除永久生效数据
                            'date_start_no_day' => '0000-00-00',
                            'date_end_no_day' => '9999-12-31'
                        );
                        $activeData = Service_ShipCustomerWeightPrice::getByCondition($activeCondition);
                        if(is_array($activeData) && !empty($activeData)){
                            //throw new Exception('查询生效数据条件'.var_export($activeCondition, true).'暂无数据处理');
                            foreach ($activeData as $activeRow) {
                                if(!in_array($activeRow['scwp_id'], $doChangeDataArr)){
                                    $doChangeDataArr[] = $activeRow['scwp_id'];
                                }
                            }
                            if(is_array($tempAllData) && !empty($tempAllData)){
                                self::$_date_end =  date('Y-m-d', strtotime($tempAllData[0]['date_start']) - 86400 );
                            }
                            //更新原有数据有效期为失效
                            if(Service_ShipCustomerWeightPrice::batchUpdate(array('date_end' => self::$_date_end), $doChangeDataArr, 'scwp_id') === false){
                                throw new Exception('更新有效期失败');
                            }
                            //失效数据移动
                            if(Service_ShipCustomerWeightPrice::batchCopyToHistory($doChangeDataArr, 'scwp_id') === false){
                                throw new Exception('移动报价到历史表失败');
                            }
                            //删除原始数据
                            if(Service_ShipCustomerWeightPrice::batchDelete($doChangeDataArr, 'scwp_id') === false){
                                throw new Exception('删除生效原始数据失败');
                            }
                        }

                        if(is_array($tempAllData) && !empty($tempAllData)){
                            //throw new Exception('查询临时数据条件'.var_export($tempCondition, true).'暂无数据处理');
                            foreach ($tempAllData as $tempAllRow) {
                                if(!in_array($tempAllRow['scwpt_id'], $tempToActiveIdArr)){
                                    $tempToActiveIdArr[] = $tempAllRow['scwpt_id'];
                                }
                            }
                            //生效数据移动
                            if(Service_ShipCustomerWeightPrice::batchCopyTempToActive($tempToActiveIdArr, 'scwpt_id') === false){
                                throw new Exception('临时数据表移动至生效数据表失败');
                            }
                            //删除临时数据
                            if(Service_ShipCustomerWeightPriceTemp::batchDelete($tempToActiveIdArr, 'scwpt_id') === false){
                                throw new Exception('删除临时数据失败');
                            }
                        }

                        $k = $tempRow['warehouse_id'].$tempRow['customer_code'].$tempRow['sm_code'];
                        if( !isset($configs[$k]) ) {
                            $configs[$k] = 1;
                            $config = array(
                                'warehouse_id' => $tempRow['warehouse_id'],
                                'customer_code' => $tempRow['customer_code'],
                                'sm_code' => $tempRow['sm_code']
                            );
                            self::addCustomerConfig( $config );
                        }

                        self::debug('数据表ship_customer_weight_price_temp条件'.var_export($tempCondition, true).'处理结果：本次总共生效'.count($tempToActiveIdArr).'条报价,生效报价ID'.var_export($tempToActiveIdArr, true).',失效'.count($doChangeDataArr).'条报价,失效报价ID'.var_export($doChangeDataArr, true));

                        $db->commit();
                    } catch (Exception $e) {
                        $db->rollBack();
                        self::debug($e->getMessage());
                        continue;
                    }
                }
            }
        }
    }

    /**
     * [debug 调试输出]
     * @param  [type] $msg [description]
     * @return [type]      [description]
     */
    public static function debug($message = '')
    {
        echo '['.date('Y-m-d H:i:s').']'.$message . "\n\t";
    }

    /**
     * 浏览器友好的变量输出
     * @param mixed $var 变量
     * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
     * @param string $label 标签 默认为空
     * @param boolean $strict 是否严谨 默认为true
     * @return void|string
     */
    public static function dump($var, $echo=true, $label=null, $strict=true) {
        $label = ($label === null) ? '' : rtrim($label) . ' ';
        if (!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            } else {
                $output = $label . print_r($var, true);
            }
        } else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if (!extension_loaded('xdebug')) {
                $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            }
        }
        if ($echo) {
            echo($output);
            return null;
        }else
            return $output;
    }
    /* @todo:添加客户配置
     * @param array $config
     * @return none;
     */
    private static function addCustomerConfig( $config ) {
        if( !isset( $config['customer_code'] ) || empty( $config['customer_code'] )
            || !isset( $config['warehouse_id'] ) || is_null( $config['warehouse_id'] ) || $config['warehouse_id'] === ''
            || !isset( $config['sm_code'] ) || empty( $config['sm_code'] ) ) {
            throw new Exception('ship_customer_price_config添加配置失败');
        }
        $condition = array(
            'customer_code' => $config['customer_code'],
            'warehouse_id' => $config['warehouse_id'],
            'sm_code' => $config['sm_code'],
        );
        $config = Service_ShipCustomerPriceConfig::getByCondition( $condition );
        if( empty( $config ) ) {
            $result = Service_ShipCustomerPriceConfig::add( $condition );
            if( !$result )
                throw new Exception('ship_customer_price_config添加配置失败');
        }
    }
}