<?php
class Service_BilRebillingSetting extends Common_Service
{
    /**
     * @var null
     */
    public static $_modelClass = null;

    /**
     * @return Table_BilRebillingSetting|null
     */
    public static function getModelInstance()
    {
        if (is_null(self::$_modelClass)) {
            self::$_modelClass = new Table_BilRebillingSetting();
        }
        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 = "brs_id")
    {
        $model = self::getModelInstance();
        return $model->update($row, $value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function delete($value, $field = "brs_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 = 'brs_id', $colums = "*")
    {
        $model = self::getModelInstance();
        return $model->getByField($value, $field, $colums);
    }

    /**
     * @return mixed
     */
    public static function getAll()
    {
        $model = self::getModelInstance();
        return $model->getAll();
    }

    /**
     * @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);
    }
    /**
     * [getByWhere 多条件获取]
     * @param  [type] $where  [description]
     * @param  string $colums [description]
     * @return [type]         [description]
     */
    public static function getByWhere($where, $colums = "*")
    {
        if(empty($where) || !is_array($where)){
            return false;
        }
        $model = self::getModelInstance();
        return $model->getByWhere($where, $colums);
    }
    /**
     * 数据验证
     * @param $val
     * @return array
     */
    public static function validator($val, $paramId = 0)
    {
        $validateArr = $error = array();
        $customerData = Service_Customer::getByField($val['customer_code'], 'customer_code', array('customer_id'));
        $shippingMethodData = Service_ShippingMethod::getByField($val['sm_code'], 'sm_code', array('sm_id'));
        
        if(!$customerData){
            $error[] = '客户代码['.$val['customer_code'].']不存在';
        }
        if(!$shippingMethodData){
            $error[] = '运输方式['.$val['sm_code'].']不存在';
        }
        if(!empty($paramId)){
            $billingData = self::getByCondition(array('brs_id_not' => $paramId, 'customer_code' => $val['customer_code'], 'sm_code'=>$val['sm_code']));
            if($billingData){
                $error[] = '客户代码['.$val['customer_code'].']-运输方式['.$val['sm_code'].']已存在';
            }
        }
        if(!empty($error)){
            return $error;
        }
        return Common_Validator::formValidator($validateArr);
    }

    /**
     * @param array $params
     * @return array
     */
    public  function getFields()
    {
        $row = array(
            'E0' => 'brs_id',
            'E1' => 'customer_code',
            'E2' => 'sm_code',
            'E3' => 'creater_id',
            'E4' => 'creat_time',
            'E5' => 'update_user',
            'E6' => 'update_time'
        );
        return $row;
    }

    /**
     * @author william-fan
     * @todo 读取数据
     */
    public static function getData($field){
        $orderUpload = new Zend_Session_Namespace('orderRefee');
        //$field = 'batchfee';
        $path = APPLICATION_PATH.'/../data/upload/';
        if(!file_exists($path)){
            if(!mkdir($path,0777,true)){
                $result = array("ask"=>0, "message"=>"上传文件失败", 'error'=>array('上传目录不存在创建文件目录失败'));
                return $result;
            }
        }
        $config = array();
        $config['upload_path']      = $path;
        $config['allowed_types']    = 'xls|xlsx|csv';
        $config['max_size']         = '10000';
        $config['encrypt_name']     = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        $uploadResult = $upload->do_upload($_FILES, $field);
        if ( ! $uploadResult ){
            $result['ask'] = '0';
            $result['message'] = '上传文件失败';
            $result['error'] =  $upload->display_errors();
            return $result;
        }
        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if(empty($resultArray) || empty($full_path)){
            $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('数据不存在'));
            return $result;
        }
        switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":
                $resultArray = Common_Upload::readEXCEL($full_path);
                break;
            case ".csv":
                $resultArray = Common_Upload::readCSV($full_path);
                break;
            default:
                $resultArray = array();
                break;
        }
        if(empty($resultArray) || !is_array($resultArray)){
            $result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
            //echo json_encode($result);
            //exit;
        }
        @unlink($full_path);
        return $resultArray;
    }
    /**
     * @todo 得到有效数据
     */
    public static function getDataArr($rows){
        $result = array();
        if(!empty($rows)){
            foreach($rows as $key=>$value){
                $row = array();
                //排除表头
                if($key > 0){
                    $customerCode = $value[0];
                    $smCode = $value[1];
                    $trackingNumber = $value[2];
                    //计费重
                    $soServiceProviderWeight = $value[3];
                    $shipOrderRow = Service_ShipOrder::getByField($trackingNumber, 'tracking_number', array('order_id', 'sm_code'));
                    if(!empty($shipOrderRow)){
                        $orderRow = Service_Orders::getByField($shipOrderRow['order_id'], 'order_id');
                        $row['order_code'] = $orderRow['order_code'];
                        $row['so_service_provider_weight'] = $soServiceProviderWeight;
                        $row['customer_code'] = $orderRow['customer_code'];
                        $row['sm_code'] = $orderRow['sm_code'];
                        $isPriv = self::getByWhere(array('customer_code'=> $orderRow['customer_code'], 'sm_code'=>$orderRow['sm_code']), array('brs_id'));
                        $row['is_valid'] = '0';
                        if(!in_array($orderRow['order_status'], array(11, 13))){
                            $row['error'] = array('订单['.$orderRow['order_code'].']状态不是物流发货[12]或者已签收[13]');
                        }else if(empty($isPriv) || !$isPriv){
                            $row['error'] = array('运单号['.$trackingNumber.']-订单号['.$orderRow['order_code'].'], 暂未配置客户代码['.$orderRow['customer_code'].']-运输代码['.$orderRow['sm_code'].'], 请添加相关配置后再试;');
                        }else if(strtoupper($orderRow['customer_code']) != strtoupper($customerCode)){
                            $row['error'] = array('订单['.$orderRow['order_code'].']对应的客户代码['.$orderRow['customer_code'].']与模板客户代码['.$customerCode.']不一致');
                        }else if(strtoupper($orderRow['sm_code']) != strtoupper($smCode)){
                            $row['error'] = array('订单['.$orderRow['order_code'].']对应的运输方式['.$orderRow['sm_code'].']与模板运输方式['.$smCode.']不一致');
                        }else {
                            $row['is_valid'] = '1';
                        }
                    }else {
                        $row['is_valid'] = '0';
                        $row['error'] = array('运单号['.$trackingNumber.']对应订单不存在;');
                    }
                    $result[] = $row;
                }
            }
        }
        return $result;
    }
}