<?php
class Service_CustomerWarehouseFee extends Common_Service
{
    /**
     * @var null
     */
    public static $_modelClass = null;

    /**
     * @return Table_CustomerBalanceLog|null
     */
    public static function getModelInstance()
    {
        if (is_null(self::$_modelClass)) {
            self::$_modelClass = new Table_CustomerWarehouseFee();
        }
        return self::$_modelClass;
    }

    /**
     * @param $row
     * @return mixed
     */
    public static function add($row)
    {
        $model = self::getModelInstance();
        return $model->add($row);
    }


    /**
     * @param $row
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function update($row, $value, $field = "cwf_id")
    {
        $model = self::getModelInstance();
        return $model->update($row, $value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function delete($value, $field = "cwf_id")
    {
        $model = self::getModelInstance();
        return $model->delete($value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @param string $colums
     * @return mixed
     */
    public static function getByField($value, $field = 'cwf_id', $colums = "*")
    {
        $model = self::getModelInstance();
        return $model->getByField($value, $field, $colums);
    }

    /**
     * @return mixed
     */
    public static function getAll()
    {
        $model = self::getModelInstance();
        return $model->getAll();
    }
    
    public static function getByWhere($where)
    {
    	$model = self::getModelInstance();
    	return $model->getByWhere($where);
    }

    /**
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getByCondition($condition, $type, $pageSize, $page, $order);
    }

    /**
     * @param $val
     * @return array
     */
    public static function validator($val)
    {
        $validateArr = $error = array();
        return  Common_Validator::formValidator($validateArr);
    }


    /**
     * @param array $params
     * @return array
     */
    public  function getFields()
    {
        $row = array(
        
              'E0'=>'cwf_id',
              'E1'=>'customer_code',
              'E2'=>'product_sku',
              'E3'=>'receiving_code',
              'E4'=>'cwf_fifo_time',
              'E5'=>'inventory_pics',
              'E6'=>'limit_time',
              'E7'=>'fee',
              'E8'=>'currency_code',
              'E9'=>'add_time'
        );
        return $row;
    }
    
    /**
     * 定时收取仓租
     * @param string $feeDate 收租日期
     * @throws Exception
     */
    public static function autoRunFeeByDate($feeDate){
    	//收租日期
    	$feeDate = empty($feeDate) ? date('Y-m-d') : $feeDate;
    	//仓储费条件
    	$condition = array(
    			//杂费ID
    			'other_fee.fee_code' => 'CANGCHU3',
    			'customer_other_fee.status' => 1,
    			'customer_other_fee.fee_value' =>
    			array(
    					'gt' => 0
    			),
    			//	正常用户扣费
    			//	'customer.customer_status' => 2,
    	);
    	$otherFee = Service_OtherFee::getByField('CANGCHU3', 'fee_code');
    	//杂费币种当前汇率
    	$currencyData = Service_Currency::getByField($otherFee['fee_currency_code'], 'currency_code', 'currency_rate');
    	$feeunit = Service_OtherFee::getFeeUnit();
    	//杂费表单价 价格减去成本
    	$otherUnitPrice = $otherFee['fee_value'] ;
    	$counts = Service_CustomerOtherFee::leftJoinCustomerByCondition($condition, 'count(*)');
        if(!$counts) exit;
        $pageSize = 200;
        $pages = ceil($counts/$pageSize);
        $db = Common_Common::getAdapter();
        for($page=1; $page<=$pages; $page++){
            $customerSettingList = Service_CustomerOtherFee::leftJoinCustomerByCondition($condition, '*', $pageSize, $page, array('customer_other_fee.cof_id ASC'));
            if(empty($customerSettingList)) break;
            foreach($customerSettingList as $customerData){
                $inventoryBatchCondition = array(
                    'customer_code' => $customerData['customer_code'],
                    'warehouse_id'=> $customerData['warehouse_id'],
                    'ib_quantity_gt0'=>1,
                    //	'ib_status' 	=> 1
                );
                $inventoryBathchList = Service_InventoryBatch::getByCondition($inventoryBatchCondition,"*",0,0,'ib_fifo_time asc');
                if(empty($inventoryBathchList)) continue;
                $calLocation = array();
                foreach($inventoryBathchList as $inventoryBathch){
                    //`ib_fifo_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '上架时间',
                    $nowtimespace = strtotime(date("Y-m-d H:i:s"));
                    $fftAddLimit = strtotime("+".$customerData['limit_time']." days",strtotime($inventoryBathch['ib_fifo_time']));
                    if($fftAddLimit>$nowtimespace) continue;
                    $location = Service_Location::getByField($inventoryBathch['lc_code'],"lc_code","*");
                    $locationType = Service_LocationType::getByField($location['lt_code'],'lt_code',"*");
                    if(empty($locationType)) continue;
                    if($locationType['is_charge']=="0") continue;
                    if(!in_array($inventoryBathch['lc_code'],$calLocation)){
                        $calLocation[] = $inventoryBathch['lc_code'];
                        $fee = ($locationType['lt_width']/100)*($locationType['lt_length']/100)*($locationType['lt_height']/100)*$otherUnitPrice*$customerData['discount'];
                        $isDone = self::getByCondition(array('left_add_time'=>$feeDate, 'ib_id'=>$inventoryBathch['ib_id']), 'count(*)');
                        //if($isDone) continue;
                        $db->beginTransaction();
                        try{
                            $customerFee = Service_Currency::converByCode($otherFee['fee_currency_code'], $customerData['customer_currency'], $fee);
                            //扣除余额
                            $newCbValue = $customerData['cb_value'] - $customerFee;
                            $cbRes = Service_CustomerBalance::update(array('cb_value'=>$newCbValue), $customerData['cb_id'], 'cb_id');
                            $warehouseData = Service_Warehouse::getByField($inventoryBathch['warehouse_id'], 'warehouse_id', 'warehouse_code');

                            /*if(!$cbRes){
                                throw new Exception("客户编码".$customerData['customer_code']."更新余额失败\r\n");
                            }*/
                            $now = date('Y-m-d H:i:s');
                            $cwfCode = 'CWF'.date('ymd').strtoupper(uniqid());
                            $cwfData = array(
                                'cwf_code' 			=> $cwfCode,
                                'customer_code' 	=> $customerData['customer_code'],
                                'fee_id' 			=> $otherFee['fee_id'],
                                'cof_id' 			=> $customerData['cof_id'],
                                'limit_time' 		=> $customerData['limit_time'],
                                'ib_id'				=> $inventoryBathch['ib_id'],
                                'warehouse_id' 		=> $inventoryBathch['warehouse_id'],
                                'warehouse_code'	=> $warehouseData['warehouse_code'],
                                'product_sku' 		=> "",
                                'product_id' 		=> $inventoryBathch['product_id'],
                                'receiving_code'	=> $inventoryBathch['receiving_code'],
                                'lot_number'		=> $inventoryBathch['lot_number'],
                                'lc_code'			=> $inventoryBathch['lc_code'],
                                'cwf_fifo_time' 	=> $inventoryBathch['ib_fifo_time'],
                                'inventory_pics'	=> "",
                                'unit_price'		=> $otherFee['fee_value']*$customerData['discount'],
                                'fee'				=> $fee,
                                'customer_fee'		=> $customerFee,
                                'currency_code'		=> $otherFee['fee_currency_code'],
                                'customer_currency'	=> $customerData['customer_currency'],
                                'add_time'			=> $now
                            );
                            $cwfRes = self::add($cwfData);
                            if(!$cwfRes){
                                throw new Exception('库存ID为:'.$inventoryBathch['ib_id'].'生成仓储费3流水失败');
                            }
                            $cblData = array(
                                'customer_code' 		=> $customerData['customer_code'],
                                'customer_id'			=> $customerData['customer_id'],
                                'cbl_type'				=> 2,
                                'cbl_transaction_value'	=> $customerFee,
                                'cbl_value'				=> $fee,
                                'currency_rate'			=> $currencyData['currency_rate'],
                                'currency_code'			=> $otherFee['fee_currency_code'],
                                'fee_id'				=> $otherFee['fee_id'],
                                'cbl_current_value'		=> $newCbValue,
                                'cbl_current_hold_value'=> $customerData['cb_hold_value'],
                                'application_code'		=> '',
                                'cbl_refer_type'		=> 2,
                                'cbl_refer_code'		=> "CC3".$inventoryBathch['ib_id'].date("YmdHis"), //sku
                                'cbl_cus_code'			=> "", //product_barcode
                                'cbl_add_time'			=> $now,
                                'cbl_note'=>"入区单[".$inventoryBathch['receiving_code'].']产品条码['.$inventoryBathch['product_barcode'].']货架['.$inventoryBathch['lc_code'].']上架时间['.$inventoryBathch['ib_fifo_time'].']扣仓储费3',
                            );
                            $cblRes = Service_CustomerBalanceLog::add($cblData);
                            if(!$cblRes){
                                throw new Exception('库存ID为:'.$inventoryBathch['ib_id'].'生成余额流水失败');
                            }
                            //插入bil_business 结算业务表
                            $bbData = array(
                                'bt_code'		=> '',
                                //来源种类（仓储费）
                                'ds_code'		=> 'pr',
                                'customer_code'	=> $customerData['customer_code'],
                                'warehouse_id'	=> $inventoryBathch['warehouse_id'],
                                'sm_code'		=> '',
                                'bb_charge_time'=> $now,
                                'bb_add_time'	=> $now,
                                'bb_update_time'=> $now
                            );
                            $bbId = Service_BilBusiness::add($bbData);
                            if($bbId){
                                //bil_business_attach 结算业务附加表
                                $bbaData = array(
                                    'bb_id' 			=> $bbId,
                                    'bb_refer_code'		=> "CC3".$inventoryBathch['ib_id'].date("YmdHis"),
                                    'bb_service_number'	=> '',
                                    'bb_reference_no'	=> ''
                                );
                                Service_BilBusinessAttach::add($bbaData);
                                //bil_income 客户费用表
                                $bilNcomeData = array(
                                    'bcb_id'				=> '',
                                    'customer_code'			=> $customerData['customer_code'],
                                    'bb_id'					=> $bbId,
                                    'ft_code'				=> $otherFee['fee_code'],
                                    'ut_code'				=> $feeunit[$otherFee['fee_unit']],
                                    'sm_code'				=> '',
                                    'bi_amount'				=> $customerFee,
                                    'bi_org_amount'			=> $fee,
                                    'currency_code'			=> $otherFee['fee_currency_code'],
                                    'currency_rate'			=> $currencyData['currency_rate'],
                                    'bi_status'				=> 2,
                                    'bi_chargeable_time'	=> $now,
                                    'bi_add_time'			=> $now
                                );
                                Service_BilIncome::add($bilNcomeData);
                            }
                            $db->commit();
                        }catch (Exception $e){
                            $db->rollBack();
                            echo $e->getMessage()."\r\n";
                        }

                    }
                }
            }
        }
        exit;
    }

    public static  function autoRunCangchu2Fee($feeDate=""){
        $feeDate = empty($feeDate) ? date('Y-m-d') : $feeDate;
        $condition = array(
            //杂费ID
            'other_fee.fee_code' => 'CANGCHU2',
            'customer_other_fee.status' => 1,
            'customer_other_fee.fee_value' =>
            array(
                'gt' => 0
            ),
            //	正常用户扣费
            //	'customer.customer_status' => 2,
        );
        $otherFee = Service_OtherFee::getByField('CANGCHU2', 'fee_code');
        //杂费币种当前汇率
        $currencyData = Service_Currency::getByField($otherFee['fee_currency_code'], 'currency_code', 'currency_rate');
        $feeunit = Service_OtherFee::getFeeUnit();
        //杂费表单价 价格减去成本
        $otherUnitPrice = $otherFee['fee_value'] - $otherFee['fee_amount'];
        $counts = Service_CustomerOtherFee::leftJoinCustomerByCondition($condition, 'count(*)');
        $nowtime = strtotime("-1 months",strtotime(date("Y-m-d")));
        if($counts){
            $pageSize = 200;
            $pages = ceil($counts/$pageSize);
            if($pages){
                for($page=1; $page<=$pages; $page++){
                    $customerSettingList = Service_CustomerOtherFee::leftJoinCustomerByCondition($condition, '*', $pageSize, $page, array('customer_other_fee.cof_id ASC'));
                    if(!empty($customerSettingList) && is_array($customerSettingList)){
                        foreach ($customerSettingList as $customerData){
                            $customerWarehouse = Service_CustomerWarehouse::getByCondition(array('customer_code'=>$customerData['customer_code']),"*");
                            if(!empty($customerWarehouse)){
                                foreach($customerWarehouse as $cw){
                                    $warehouse = Service_Warehouse::getByField($cw['warehouse_id'],"warehouse_id","*");
                                    if($warehouse['warehouse_code']!="SZ01") continue;
                                    if($cw['calfee_time']=="0000-00-00"){
                                        $timespace = strtotime($cw['warehouse_time']);
                                    }else{
                                        $timespace = strtotime($cw['calfee_time']);
                                    }
                                    if($nowtime<$timespace) continue;
                                    $db = Common_Common::getAdapter();
                                    $db->beginTransaction();
                                    $customerRow = Service_Customer::getByField($cw['customer_code'],"customer_code","*");
                                    $customerBalance = Service_CustomerBalance::getByField($customerRow['customer_id'],"customer_id","*");
                                    try{
                                        $upCw = array(
                                            'calfee_time'=>date("Y-m-d"),
                                        );
                                        Service_CustomerWarehouse::update($upCw,$cw['cw_id'],"cw_id");
                                        //设置了折扣
                                        /*if($customerData['discount']>0&&$customerData['discount']<1){
                                            $fee = $customerData['discount']*$customerData['fee_value']*$cw['warehouse_area'];
                                            $customerFee = Service_Currency::converByCode($otherFee['fee_currency_code'], $customerRow['customer_currency'], $fee);
                                            //echo "discount=".$customerData['discount']."&fee_value=".$customerData['fee_value']."&warehouse_area=".$cw['warehouse_area']."<br>";
                                            $now = date('Y-m-d H:i:s');
                                            $newCbValue = $customerData['cb_value'] - $customerFee;
                                            $cbRes = Service_CustomerBalance::update(array('cb_value'=>$newCbValue), $customerData['cb_id'], 'cb_id');
                                        }else{
                                            $fee = $otherFee['fee_value']*$cw['warehouse_area'];
                                            $customerFee = Service_Currency::converByCode($otherFee['fee_currency_code'], $customerRow['customer_currency'], $fee);
                                            //echo "fee_value=".$customerData['fee_value']."&warehouse_area=".$cw['warehouse_area']."<br>";
                                            $now = date('Y-m-d H:i:s');
                                            $newCbValue = $customerData['cb_value'] - $customerFee;
                                            $cbRes = Service_CustomerBalance::update(array('cb_value'=>$newCbValue), $customerData['cb_id'], 'cb_id');
                                        }*/

                                        $fee = $customerData['fee_value']*$cw['warehouse_area'];
                                        $customerFee = Service_Currency::converByCode($otherFee['fee_currency_code'], $customerRow['customer_currency'], $fee);
                                        //echo "discount=".$customerData['discount']."&fee_value=".$customerData['fee_value']."&warehouse_area=".$cw['warehouse_area']."<br>";
                                        $now = date('Y-m-d H:i:s');
                                        $newCbValue = $customerData['cb_value'] - $customerFee;
                                        $cbRes = Service_CustomerBalance::update(array('cb_value'=>$newCbValue), $customerData['cb_id'], 'cb_id');

                                        $cwfCode = 'CWF'.date('ymd').strtoupper(uniqid());
                                        $cwfData = array(
                                            'cwf_code' 			=> $cwfCode,
                                            'customer_code' 	=> $customerData['customer_code'],
                                            'fee_id' 			=> $otherFee['fee_id'],
                                            'cof_id' 			=> $customerData['cof_id'],
                                            'limit_time' 		=> $customerData['limit_time'],
                                            'ib_id'				=> "",
                                            'warehouse_id' 		=> $cw['warehouse_id'],
                                            'warehouse_code'	=> $warehouse['warehouse_code'],
                                            'product_sku' 		=> "",
                                            'product_id' 		=> "",
                                            'receiving_code'	=> "",
                                            'lot_number'		=> "",
                                            'lc_code'			=>"",
                                            'cwf_fifo_time' 	=> "",
                                            'inventory_pics'	=> "",
                                            'unit_price'		=> $customerData['fee_value'],
                                            'fee'				=> $fee,
                                            'customer_fee'		=> $customerFee,
                                            'currency_code'		=> $otherFee['fee_currency_code'],
                                            'customer_currency'	=> $customerRow['customer_currency'],
                                            'add_time'			=> $now
                                        );
                                        $cwfRes = self::add($cwfData);
                                        if(!$cwfRes){
                                            throw new Exception( $customerData['customer_code'].'仓储费2生成杂费流水失败');
                                        }
                                        $cblData = array(
                                            'customer_code' 		=> $customerData['customer_code'],
                                            'customer_id'			=> $customerRow['customer_id'],
                                            'cbl_type'				=> 2,
                                            'cbl_transaction_value'	=> $customerFee,
                                            'cbl_value'				=> $fee,
                                            'currency_rate'			=> $currencyData['currency_rate'],
                                            'currency_code'			=> $otherFee['fee_currency_code'],
                                            'fee_id'				=> $otherFee['fee_id'],
                                            'cbl_current_value'		=> $newCbValue,
                                            'cbl_current_hold_value'=> $customerBalance['cb_hold_value'],
                                            'application_code'		=> '',
                                            'cbl_refer_type'		=> 2,
                                            'cbl_refer_code'		=> $customerRow['customer_id']."CC2".$warehouse['warehouse_id'].date("Ymd"), //sku
                                            'cbl_cus_code'			=> "", //product_barcode
                                            'cbl_add_time'			=> $now
                                        );
                                        $cblRes = Service_CustomerBalanceLog::add($cblData);
                                        if(!$cblRes){
                                            throw new Exception($customerData['customer_code'].'生成余额流水失败');
                                        }
                                        //插入bil_business 结算业务表
                                        $bbData = array(
                                            'bt_code'		=> '',
                                            //来源种类（仓储费）
                                            'ds_code'		=> 'pr',
                                            'customer_code'	=> $customerData['customer_code'],
                                            'warehouse_id'	=> $cw['warehouse_id'],
                                            'sm_code'		=> '',
                                            'bb_charge_time'=> $now,
                                            'bb_add_time'	=> $now,
                                            'bb_update_time'=> $now
                                        );
                                        $bbId = Service_BilBusiness::add($bbData);
                                        if($bbId){
                                            //bil_business_attach 结算业务附加表
                                            $bbaData = array(
                                                'bb_id' 			=> $bbId,
                                                'bb_refer_code'		=> $customerData['customer_code'].".CANGCHU2.".$warehouse['warehouse_code'].date("YmdHis"),
                                                'bb_service_number'	=> '',
                                                'bb_reference_no'	=> ''
                                            );
                                            Service_BilBusinessAttach::add($bbaData);
                                            //bil_income 客户费用表
                                            $bilNcomeData = array(
                                                'bcb_id'				=> '',
                                                'customer_code'			=> $customerData['customer_code'],
                                                'bb_id'					=> $bbId,
                                                'ft_code'				=> $otherFee['fee_code'],
                                                'ut_code'				=> $feeunit[$otherFee['fee_unit']],
                                                'sm_code'				=> '',
                                                'bi_amount'				=> $customerFee,
                                                'bi_org_amount'			=> $fee,
                                                'currency_code'			=> $otherFee['fee_currency_code'],
                                                'currency_rate'			=> $currencyData['currency_rate'],
                                                'bi_status'				=> 2,
                                                'bi_chargeable_time'	=> $now,
                                                'bi_add_time'			=> $now
                                            );
                                            Service_BilIncome::add($bilNcomeData);
                                        }
                                        //提交数据
                                        $db->commit();
                                    }catch (Exception $e){
                                        $db->rollBack();
                                        echo $e->getMessage()."\r\n";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}