<?php
class Service_ProductProcess
{
    protected $_error = array();
    protected $_cache = array();//用于缓存数据
    protected $_date = '';

    //状态
    public static function getProductStatus()
    {
        /*return array(
            0 => '删除',
            1 => '确认',
        );*/
        return array(
        	0 => '备案中',
        	1 => '已备案',
			2 => '草稿',
        );
    }

    //类型
    public static function getProductType()
    {
        return array(
            0 => '普通产品',
            1 => '组合产品',
        );
    }


    public static function getProductReceivingStatus()
    {
        return array(
            0 => '新产品',
            1 => '已收货',
        );
    }

    public static function getProductQc()
    {
        return array(
            0 => '质检',
            1 => '不质检',
        );
    }
    public function __construct()
    {
        $this->_date = date('Y-m-d H:i:s');
    }
    public function changeDecalarValidate($productInfo){
         if($productInfo['product_status']!=1){
                throw new Exception('产品必须是已备案状态');
        }
        $noChangCondition=array(
            'product_id'=>$productInfo['product_id'],
            'order_status'=>array('1','2','3','4','5','6','7','8','9','10','14'),
        );
        $isExit=  Service_Orders::getOrderByProduct($noChangCondition,'count(*)');
        if($isExit){
            throw new Exception('产品存在物流未完成订单');
        }
        $isExitReceiving=Service_ReceivingDetail::checkReceivingDetail($productInfo['product_id']);
        if($isExitReceiving){
             throw new Exception('产品存在未收货完成入库单');
        }
    }
    /* @desc:根据料件号更新产品重量
     *
     */
    public function editWeightByGoodsId( $goodsId, $weight ) {
        $return = array( 'ask' => 0, 'msg' => '' );
        if( empty( $goodsId ) ) {
            $return['msg'] = '料件号不能为空';
            return $return;
        }
        if( empty( $weight ) || !is_numeric( $weight ) || $weight <= 0 ) {
            $return['msg'] = '重量必须是大于0的数字';
            return $return;
        }
        $weight = sprintf("%.4f",$weight);
        $total = Service_Product::getByCondition( array( 'goods_id' => $goodsId ), '*',1,1 );
        if( empty( $total ) ) {
            $return['msg'] = '没有找到产品';
            return $return;
        }
        $date = date('Y-m-d H:i:s');
        $adapter = Common_Common::getAdapter();
        $adapter->beginTransaction();
        try {
            //写日志
            $page = 1;
            $pageSize = 20;
            $ip = Common_Common::getIP();
            $user = Service_User::getLoginUser();
            $condition = array( 'goods_id' => $goodsId );
            while( $products = Service_Product::getByCondition( $condition, '*',$pageSize,$page, 'product_id' ) ) {
                $condition['product_id_gt'] = $products[count($products)-1]['product_id'];
                foreach( $products as $product) {
                    $log = array(
                        'product_id'            => $product['product_id'],
                        'pl_type'               => 0,
                        'user_id'               => $user['user_id'],
                        'customer_id'          => $product['customer_id'],
                        'pl_statu_pre'         => $product['product_status'],
                        'pl_statu_now'         => $product['product_status'],
                        'pl_note'               => ' Weight:'.$product['product_weight'].' to  '.$weight,
                        'pl_add_time'          => $date,
                        'pl_ip'                 => $ip,
                        'account_id'           => 0,
                    );
                    $result = Service_ProductLog::add( $log );
                    if( !$result )
                        throw new Exception( 'sku:'.$product['product_sku'].'写入日志失败');
                }
            }
            $result = Service_Product::update( array( 'product_weight' => $weight, 'product_update_time' => $date ), $goodsId, 'goods_id' );
            if( !$result )
                throw new Exception( '更新产品重量失败');

            $adapter->commit();
            $return['ask'] = 1;
            $return['msg'] = '更新成功';
        } catch( Exception $e ) {
            $adapter->rollBack();
            $return['msg'] = $e->getMessage();
        }
        return $return;
    }

    protected function addError( $error ) {
        $this->_error[] = $error;
    }

    public function getError() {
        return $this->_error;
    }

    protected function getResult() {
        $result = array( 'ask' => 0, 'msg' => '操作失败' );
        if( !empty( $this->_error ) ) {
            $result['msg'] = implode( ',', $this->_error );
        } else {
            $result['ask'] = 1;
            $result['msg'] = '操作成功';
        }
        return $result;
    }

    public function isAllow( $customer ) {
        return empty( $customer ) ? false : ( $customer['customer_platform'] == 'LT' ? true : false );
    }
    /* @desc 更新特定用户的产品尺寸和重量，只有尺寸或重量为0时才会去更新，不为0则不更新
     *
     */
    public function updateSizeWeight() {
        $date = date('Y-m-d H:i:s');
        $ip   = Common_Common::getIP();
        $user = Service_User::getLoginUser();

        $data = $this->getSizeWeight();
        if( !empty( $data ) && count($data) > 1 ) {
            $adapter = Common_Common::getAdapter();
            foreach( $data as $key => $value ) {
                if( $key == 0 )
                    continue;
                if( false === ($check = $this->checkSizeWeight($value,$key+1)) )
                    continue;

                $product = $this->_cache['product'][ $check['customer_code'] ][ $check['product_sku'] ];
                $update  = array();
                $log     = array();
                //长度可能为空
                if( $product['product_length'] == 0 && $check['product_length'] && $check['product_length'] > 0 ) {
                    $update['product_length'] = $check['product_length'];
                    $log[] = 'Length: '.$product['product_length'].' to '.$check['product_length'];
                }
                if( $product['product_width'] == 0 && $check['product_width'] && $check['product_width'] > 0 ) {
                    $update['product_width'] = $check['product_width'];
                    $log[] = 'width: '.$product['product_width'].' to '.$check['product_width'];
                }
                if( $product['product_height'] == 0 && $check['product_height'] && $check['product_height'] > 0 ) {
                    $update['product_height'] = $check['product_height'];
                    $log[] = 'Height: '.$product['product_height'].' to '.$check['product_height'];
                }
                if( $product['product_weight'] == 0 && $check['product_weight'] && $check['product_weight'] > 0 ) {
                    $update['product_weight'] = $check['product_weight'];
                    $log[] = 'Weight: '.$product['product_weight'].' to '.$check['product_weight'];
                }
                if( empty( $update ) ) {
                    $this->addError( '第'.($key+1).'行，sku:'. $check['product_sku'] .'无需更新' );
                    continue;
                }
                $adapter->beginTransaction();
                try{
                    $update['product_update_time'] = $date;
                    $result = Service_Product::update( $update, $product['product_id'], 'product_id' );
                    if( !$result )
                        throw new Exception('更新产品表失败');

                    $customer = $this->_cache['customer'][$check['customer_code']];
                    $log = array(
                        'product_id'        => $product['product_id'],
                        'pl_type'           => 0,
                        'user_id'           => $user['user_id'],
                        'customer_id'       => $customer['customer_id'],
                        'pl_statu_pre'      => $product['product_status'],
                        'pl_statu_now'      => $product['product_status'],
                        'pl_note'            => '后台更新,'.implode( ' ', $log ),
                        'pl_add_time'       => $date,
                        'pl_ip'              => $ip,
                    );
                    $result = Service_ProductLog::add( $log );
                    if( !$result )
                        throw new Exception('添加日志失败');

                    $adapter->commit();

                    $this->addError( '第'.($key+1).'行，'. $check['product_sku'] .'更新成功');

                } catch( Exception $e ) {
                    $adapter->rollBack();
                    $this->addError( '第'.($key+1).'行，'. $check['product_sku'] .'更新失败，'.$e->getMessage() );
                }
            }
        }
        return $this->getResult();
    }
    /* @desc 检查数据
     * @param array $data 从excel表读出的一行数据
     * @param int   $line 第几行数据
     * @return boolean
     */
    protected function checkSizeWeight( $data, $line ) {
        $customer = isset( $data[0] ) ? trim( $data[0] ) : '';
        $sku      = isset( $data[1] ) ? trim( $data[1] ) : '';
        $length   = isset( $data[2] ) ? trim( $data[2] ) : 0;
        $width    = isset( $data[3] ) ? trim( $data[3] ) : 0;
        $height   = isset( $data[4] ) ? trim( $data[4] ) : 0;
        $weight   = isset( $data[5] ) ? trim( $data[5] ) : 0;

        $allow = false;
        $msg = array();
        if( $customer === '') {
            $this->addError( '第'.$line.'行,客户不能为空');
        } else {
            if( !isset( $this->_cache['customer'][$customer] ) ) {
                $customerRow = Service_Customer::getByField( $customer, 'customer_code');
                if( !empty( $customerRow ) ) {
                    $this->_cache['customer'][$customer] = array(
                        'customer_id'        => $customerRow['customer_id'],
                        'customer_platform' => $customerRow['customer_platform'],
                    );
                } else {
                    $this->_cache['customer'][$customer] = array();
                }
            }
            if( !$this->_cache['customer'][$customer] ) {
                $this->addError( '第'.$line.'行,用户'.$customer.'不存在');
            } else {
                if( !$this->isAllow( $this->_cache['customer'][$customer] ) ) {
                    $this->addError( '第'.$line.'行,'.$customer.'不是允许的用户，不作更新');
                } else {
                    $allow = true;
                }
            }
        }
        //不允许就直接返回
        if( !$allow )
            return false;

        if( $sku === '') {
            $msg[] = 'sku不能为空';
        } else {
             if( !isset( $this->_cache['product'][$customer][$sku] ) ) {
                 $productRow = Service_Product::getByCondition( array( 'product_sku' => $sku, 'customer_code'=> $customer ) );
                 if( !empty( $productRow ) ) {
                    $this->_cache['product'][$customer][$sku] = array(
                        'product_id'      => $productRow[0]['product_id'],
                        'product_length' => $productRow[0]['product_length'],
                        'product_width'  => $productRow[0]['product_width'],
                        'product_height' => $productRow[0]['product_height'],
                        'product_weight' => $productRow[0]['product_weight'],
                        'product_status' => $productRow[0]['product_status']
                    );
                 } else {
                     $this->_cache['product'][$customer][$sku] = array();
                 }
            }
            if( !$this->_cache['product'][$customer][$sku] ) {
                $msg[] = 'sku:'.$sku.'不存在';
            }
        }
        if( $length !== '' && ( !is_numeric( $length ) || $length < 0 ) ) {
            $msg[] = '长度必须大于0或者不填';
        }
        if( $width !== '' && (!is_numeric( $width ) || $width < 0 ) ) {
            $msg[] = '宽度必须大于0或者不填';
        }
        if( $height !== '' && (!is_numeric( $height ) || $height < 0 ) ) {
            $msg[] = '高度必须大于0或者不填';
        }
        if( $weight !== '' && (!is_numeric( $weight ) || $weight < 0 ) ) {
            $msg[] = '重量必须大于0或者不填';
        }
        if( !empty( $msg ) ) {
            $this->addError( '第'.$line.'行,'.implode( ',', $msg ) );
        }
        $check = array(
            'customer_code'  => $customer,
            'product_sku'    => $sku,
            'product_length' => $length,
            'product_width'  => $width,
            'product_height' => $height,
            'product_weight' => $weight,
        );
        return $msg ? false : $check;
    }
    /* @desc 读出excel的数据
     *
     */
    protected function getSizeWeight() {
        $data = array();
        $user = Service_User::getLoginUser();
        $path = APPLICATION_PATH.'/../data/cache/update-product/'.$user['user_id'];

        if(!file_exists($path)){
            if(!mkdir($path,0700,true)){
                $this->addError('上传目录不存在创建文件目录失败');
                return $data;
            }
        }
        $config = array();
        $config['upload_path']      = $path;
        $config['allowed_types']    = 'xls|xlsx';
        $config['max_size']         = '10000';
        $config['encrypt_name']     = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if ( ! $upload->do_upload($_FILES,'file') ){
            $this->addError( $upload->display_errors() );
            return $data;
        }

        $resultArray = $upload->data();
        $fullPath = $resultArray['full_path'];
        if(empty($resultArray) || empty( $fullPath )){
            $this->addError( '数据不存在' );
            return $data;
        }
        switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":
                $data = Common_Upload::readEXCEL($fullPath);
                break;
            case ".csv":
                $data = Common_Upload::readCSV($fullPath);
                break;
            default:
                $data = array();
                break;
        }
        if(empty($data) || !is_array($data)){
            $this->addError('文件内容不符合格式或数据为空');
        }
        @unlink($fullPath);
        return $data;
    }

}