<?php
/**
 * Express.php
 *
 * Niushop閸熷棗鐓勭化鑽ょ埠 - 閸ャ垽妲﹂崡浣稿嬀閻㈤潧鏅㈢紒蹇涚崣濮瑰洭娉﹀銊у盀!
 * =========================================================
 * Copy right 2015-2025 鐏炶精銈块悧娑㈠徔娣団剝浼呯粔鎴炲Η閺堝妾洪崗顒�寰�, 娣囨繄鏆�閹碉拷閺堝娼堥崚鈹匡拷锟�
 * ----------------------------------------------
 * 鐎规ɑ鏌熺純鎴濇絻: http://www.niushop.com.cn
 * 鏉╂瑤绗夐弰顖欑娑擃亣鍤滈悽杈拫娴犺绱掗幃銊ュ涧閼宠棄婀稉宥囨暏娴滃骸鏅㈡稉姘辨窗閻ㄥ嫮娈戦崜宥嗗絹娑撳顕粙瀣碍娴狅絿鐖滄潻娑滎攽娣囶喗鏁奸崪灞煎▏閻€劊锟斤拷
 * 娴犺缍嶆导浣风瑹閸滃奔閲滄禍杞扮瑝閸忎浇顔忕�靛湱鈻兼惔蹇庡敩閻椒浜掓禒璁崇秿瑜般垹绱℃禒璁崇秿閻╊喚娈戦崘宥呭絺鐢啨锟斤拷
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */
namespace data\service;
/**
 * 閸熷棗鎼ч張宥呭鐏烇拷
 */
use data\service\BaseService as BaseService;
use data\api\IExpress as IExpress;
use data\model\NsOrderShippingFeeModel as NsOrderShippingFeeModel;
use data\model\NsOrderShippingFeeExtendModel as NsOrderShippingFeeExtendModel;
use data\service\Address as Address;
use data\model\NsOrderExpressCompanyModel;
use data\model\NsShopExpressAddressModel;
use data\model\NsExpressShippingItemsLibraryModel;
use data\model\NsExpressShippingModel;
use data\model\NsExpressShippingItemsModel;
use think\Model;
class Express extends BaseService implements IExpress
{
	/* (non-PHPdoc)
     * @see \data\api\IExpress::getShippingFeeList()
     */
    public function getShippingFeeList($page_index = 1, $page_size = 0, $condition = '', $order = '')
    {
        $ns_order_shipping_fee = new NsOrderShippingFeeModel();
        $list = $ns_order_shipping_fee->pageQuery($page_index, $page_size, $condition, $order,'*');
        $address = new Address();
      /*   $province = $address->getProvinceList();
        $city=$address->getCityList(); */
        foreach ($list['data'] as $k => $v)
        {
            $shipping_fee_ext = new NsOrderShippingFeeExtendModel();
            $list_ext = $shipping_fee_ext->where('shipping_fee_id='.$v['shipping_fee_id'])->select();
    
            $list['data'][$k]['ext'] = $list_ext;            
            //閼惧嘲褰囬悧鈺傜ウ閻礁绔�
            $address = new Address();
            foreach($list['data'][$k]['ext'] as $m=>$q){
           
                $province_name = $address->getProvinceName($q["province_id"]);
                $city_name = $address->getCityName($q["city_id"]);
                $q["address_name"] = $province_name. ' '. $city_name;
            }
        }
        return $list;
        // TODO Auto-generated method stub
        
    }

	/* (non-PHPdoc)
     * @see \data\api\IExpress::addShippingFee()
     */
    public function addShippingFee($shipping_fee_name, $shipping_fee_ext)
    {
        $order_shipping_fee = new NsOrderShippingFeeModel();       
        $order_shipping_fee->startTrans();
         try{
                $data = array(
                    'shipping_fee_name' => $shipping_fee_name,
                    'shop_id' => $this->instance_id,
                    'create_time' => date('Y-m-d H:i:s', time())
                );
                $order_shipping_fee->save($data);
                $new_shipping_fee_id = $order_shipping_fee->shipping_fee_id; 
                if(!empty($new_shipping_fee_id))
                {
                    $shipping_fee_ext_array = explode('|', $shipping_fee_ext);
                    foreach ($shipping_fee_ext_array as $k => $v)
                    {
                        $shipping_fee_ext_data = explode(';', $v);
                       
                        $data_ext = array(
                            'shipping_fee_id' => $new_shipping_fee_id,
                            'province_id' => $shipping_fee_ext_data[0],
                            'city_id' => $shipping_fee_ext_data[1],
                            'snum' => $shipping_fee_ext_data[2],
                            'sprice' => $shipping_fee_ext_data[3],
                            'xnum' => $shipping_fee_ext_data[4],
                            'xprice' => $shipping_fee_ext_data[5],
                            'is_default'=>$shipping_fee_ext_data[6]
                        );
                        $order_shipping_fee_ext = new NsOrderShippingFeeExtendModel();
                        $order_shipping_fee_ext->save($data_ext);                       
                    }                                  
                    $order_shipping_fee->commit();
                    return 1;
                }
                return -1;
               
          
        }catch (\Exception $e) {
            $order_shipping_fee->rollback();
            return $e->getMessage();
        }
        return -1; 
        
        // TODO Auto-generated method stub
        
    }

	/* (non-PHPdoc)
     * @see \data\api\IExpress::updateShippingFee()
     */
    public function updateShippingFee($shipping_fee_id, $shipping_fee_name, $shipping_fee_ext)
    {
        $order_shipping_fee = new NsOrderShippingFeeModel();
        $order_shipping_fee_ext = new NsOrderShippingFeeExtendModel();
        $order_shipping_fee->startTrans();
        try{
            $data = array(
                'shipping_fee_name' => $shipping_fee_name,
                'shop_id' => $this->instance_id,
                'create_time' => date('Y-m-d H:i:s', time())
            );
            $new_shipping_fee_id = $order_shipping_fee->save($data,['shipping_fee_id' => $shipping_fee_id]);
            $new_shipping_fee_id=$shipping_fee_id;
            if(!empty($new_shipping_fee_id))
            {
                  $order_shipping_fee_ext->destroy(['shipping_fee_id' => $shipping_fee_id]);
                  $shipping_fee_ext_array = explode('|', $shipping_fee_ext);
                  
                    foreach ($shipping_fee_ext_array as $k => $v)
                    {
                        $shipping_fee_ext_data = explode(';', $v);
                        $data_ext = array(
                            'shipping_fee_id' => $new_shipping_fee_id,
                            'province_id' => $shipping_fee_ext_data[0],
                            'city_id' => $shipping_fee_ext_data[1],
                            'snum' => $shipping_fee_ext_data[2],
                            'sprice' => $shipping_fee_ext_data[3],
                            'xnum' => $shipping_fee_ext_data[4],
                            'xprice' => $shipping_fee_ext_data[5],
                            'is_default'=>$shipping_fee_ext_data[6]
                        );
                        $order_shipping_fee_ext = new NsOrderShippingFeeExtendModel();
                        $order_shipping_fee_ext-> save($data_ext);
                    }
                   
                    
                    $order_shipping_fee->commit();
                    return 1;
            }
            return -1;
             
        
        }catch (\Exception $e) {
            $order_shipping_fee->rollback();
            return $e->getMessage();
        }
        return -1;
        // TODO Auto-generated method stub
        
    }
    /* (non-PHPdoc)
     * @see \data\api\IExpress::shippingFeeDetail()
     */
    public  function shippingFeeDetail($shipping_fee_id){
        $order_shipping_fee = new NsOrderShippingFeeModel();
        $order_shipping_fee_ext = new NsOrderShippingFeeExtendModel();
        $order_shipping_fee_info=$order_shipping_fee->get($shipping_fee_id);
        $order_shipping_fee_ext_info=$order_shipping_fee_ext->all(['shipping_fee_id'=>$shipping_fee_id]);
        $order_shipping_fee_info["order_shipping_fee_ext_info"]=$order_shipping_fee_ext_info;
        //閼惧嘲褰囬悧鈺傜ウ閻礁绔�             
        $address = new Address();
        $province = $address->getProvinceList();
        $city=$address->getCityList();
        foreach($order_shipping_fee_info["order_shipping_fee_ext_info"] as $k=>$v){
            $address_name="";
            $address_id ="";
            $province_array = explode(",", $v["province_id"]);
            $city_array = explode(",", $v["city_id"]);
            foreach($province_array as $e){
                foreach($province as $p){
                    if($e == $p["province_id"]){
                        $address_id = $address_id.$p["province_id"].",";
                        $address_name =$address_name.$p["province_name"].",";
                    }
                }
            }
            foreach($city_array as $c){
                foreach($city as $z){
                    if($c == $z["city_id"]){
                        $address_id = $address_id.$z["province_id"].":100".$z["city_id"].",";
                        $address_name =$address_name.$z["city_name"].",";
                    }
                }
            }
            $v["address_name"] = $address_name;
            $v["address_id"] = $address_id;
        }
        return $order_shipping_fee_info;
    }
    /* (non-PHPdoc)
     * @see \data\api\IExpress::shippingFeeDelete()
     */
    public function shippingFeeDelete($shipping_fee_id){
        $order_shipping_fee = new NsOrderShippingFeeModel();
        $order_shipping_fee_ext = new NsOrderShippingFeeExtendModel();
        $condition = array(
            'shop_id' => $this->instance_id,
            'shipping_fee_id' => $shipping_fee_id
        );
        $order_shipping_return = $order_shipping_fee->destroy($condition);
        if($order_shipping_return >0){
            $order_shipping_fee_ext->destroy(['shipping_fee_id' => $shipping_fee_id]);
            return 1;
        }else{
            return -1;
        }                  
        
    }
    
    /**
     * 鏉╂劘鍨傚Ο鈩冩緲閺屻儴顕�
     * {@inheritDoc}
     * @see \data\api\IExpress::shippingFeeQuery()
     */
    public function shippingFeeQuery($where = "",$fields = "*")
    {
        $order_shipping_fee = new NsOrderShippingFeeModel();
        return $order_shipping_fee->where($where)->field($fields)->select();        
    }
    /**
     * {@inheritDoc}
     * @see \data\api\IExpress::getExpressCompanyList()
     */
    public function getExpressCompanyList($page_index = 1, $page_size = 0, $condition = '', $order = ''){
        $ns_express_company = new NsOrderExpressCompanyModel();
        $list = $ns_express_company->pageQuery($page_index, $page_size, $condition, $order,'*');
        return $list;
    }
    /**
     * {@inheritDoc}
     * @see \data\api\IExpress::addExpressCompany()
     */
    public function addExpressCompany($shop_id, $company_name, $express_logo, $express_no, $is_enabled, $image, $phone, $orders){
        $ns_express_company = new NsOrderExpressCompanyModel();
        $ns_express_company->startTrans();
        try {
            $data = array(
                'shop_id' => $shop_id,
                'company_name' => $company_name,
                'express_logo' => $express_logo,
                'express_no' => $express_no,
                'is_enabled' => $is_enabled,
                'image' => $image,
                'phone' => $phone,
                'orders' => $orders
            );
            $ns_express_company->save($data);
            $co_id=$ns_express_company->co_id;
            $sid=$this->addExpressShipping($shop_id, $company_name, $co_id);
            $this->addExpressShippingItems($sid, $shop_id);
            $ns_express_company->commit();
            return $ns_express_company->co_id;
        } catch (\Exception $e) {
            $ns_express_company->rollback();
            return $e->getCode();
        }
        
    }
    /**
     * 添加物流的模板库
     * @param unknown $shop_id
     * @param unknown $company_name
     * @param unknown $co_id
     */
    private function addExpressShipping($shop_id, $company_name, $co_id){
        $express_model=new NsExpressShippingModel();
        $data=array(
          "shop_id"=>$shop_id,
          "template_name"=>$company_name,
          "co_id"=>$co_id,
          "size_type"=>1,
          "width"=>0,
          "height"=>0,
          "image"=>""  
        );
        $express_model->save($data);
        return $express_model->sid;
    }
    /**
     * 添加大印项
     * @param unknown $sid
     * @param unknown $shop_id
     */
    private function addExpressShippingItems($sid, $shop_id){
        $library_model=new NsExpressShippingItemsLibraryModel();
        $library_list=$library_model->getQuery(["shop_id"=>$shop_id, "is_enabled"=>1], "*", "");
        $x_length=10;
        $y_length=11;
        foreach ($library_list as $library_obj){
            $item_model=new NsExpressShippingItemsModel();
            $data=array(
              "sid"=>$sid,
              "field_name"=>$library_obj["field_name"],
              "field_display_name"=>$library_obj["field_display_name"],
              "is_print"=>1,
              "x"=>$x_length,
              "y"=>$y_length  
            );
            $y_length=$y_length+25;
            $item_model->save($data);
        }
        
    }
    /**
     * {@inheritDoc}
     * @see \data\api\IExpress::updateExpressCompany()
     */
    public function updateExpressCompany($co_id, $shopId, $company_name, $express_logo,$express_no, $is_enabled, $image, $phone, $orders){
        $ns_express_company = new NsOrderExpressCompanyModel();
        $data = array(
            'shop_id' => $shopId,
            'company_name' => $company_name,
            'express_logo' => $express_logo,
            'express_no' => $express_no,
            'is_enabled' => $is_enabled,
            'image' => $image,
            'phone' => $phone,
            'orders' => $orders,
        );
        $res = $ns_express_company->save($data, ['co_id' => $co_id]);
        return $res;
    }
    /**
     * {@inheritDoc}
     * @see \data\api\IExpress::expressCompanyDetail()
     */
    public function expressCompanyDetail($co_id){
        $ns_express_company = new NsOrderExpressCompanyModel();
        return $ns_express_company->get($co_id);
    }
    /**
     * {@inheritDoc}
     * @see \data\api\IExpress::expressCompanyDelete()
     */
    public function expressCompanyDelete($co_id){
        $ns_express_company = new NsOrderExpressCompanyModel();
        $conditon = array(
            'shop_id' => $this->instance_id,
            'co_id'  => $co_id
        );
        $ns_express_company_return = $ns_express_company->destroy($conditon);
        if($ns_express_company_return > 0){
            return 1;
        }else{
            return -1;
        }
    }
    /**
     * {@inheritDoc}
     * @see \data\api\IExpress::expressCompanyQuery()
     */
    public function expressCompanyQuery($where = "", $field = "*"){
        $ns_express_company = new NsOrderExpressCompanyModel();
        return $ns_express_company->where($where)->field($field)->select();
    }
    /**
     * (non-PHPdoc)
     * @see \data\api\IExpress::addShopExpressAddress()
     */
    public function addShopExpressAddress($contact, $mobile, $phone, $company_name, $province, $city, $district, $zipcode, $address){
        $shop_express_address = new NsShopExpressAddressModel();
        $data_consigner = array(
            'is_consigner' => 0,
            'is_receiver'  => 0
        );
        $shop_express_address->save($data_consigner,['shop_id' => $this->instance_id]);
        $shop_express_address = new NsShopExpressAddressModel();
        $data = array(
            'shop_id'      => $this->instance_id,
            'contact'      => $contact,
            'mobile'        => $mobile,
            'phone'        => $phone,
            'company_name' => $company_name,
            'province'     => $province,
            'city'         => $city,
            'district'     => $district,
            'zipcode'      => $zipcode,
            'address'      => $address,
            'is_consigner' => 1,
            'is_receiver'  => 1,
            'create_date'  => date("Y-m-d H:i:s", time())
        );
            $retval = $shop_express_address-> save($data);
            $express_address_id = $shop_express_address->express_address_id;
        return $express_address_id;
    }
    /**
     * (non-PHPdoc)
     * @see \data\api\IExpress::updateShopExpressAddress()
     */
    public function updateShopExpressAddress($express_address_id, $contact, $mobile, $phone, $company_name, $province, $city, $district, $zipcode, $address)
    {
        $shop_express_address = new NsShopExpressAddressModel();
        $data = array(
            'contact'      => $contact,
            'mobile'        => $mobile,
            'phone'        => $phone,
            'company_name' => $company_name,
            'province'     => $province,
            'city'         => $city,
            'district'     => $district,
            'zipcode'      => $zipcode,
            'address'      => $address,
            'modify_date'  => date("Y-m-d H:i:s", time())
        );
        $retval = $shop_express_address-> save($data, ['express_address_id' => $express_address_id]);
        return $retval;
    }
    /**
     * (non-PHPdoc)
     * @see \data\api\IExpress::modifyShopExpressAddressConsigner()
     */
    public function modifyShopExpressAddressConsigner($express_address_id, $is_consigner){
        $shop_express_address = new NsShopExpressAddressModel();
        $shop_express_address->save(['is_consigner' => 0],['shop_id' => $this->instance_id]);
        $retval = $shop_express_address->save(['is_consigner' => 1],['express_address_id' => $express_address_id]);
        return $retval;
        
    }
    /**
     * (non-PHPdoc)
     * @see \data\api\IExpress::modifyShopExpressAddressReceiver()
     */
    public function modifyShopExpressAddressReceiver($express_address_id, $is_receiver){
        $shop_express_address = new NsShopExpressAddressModel();
        $shop_express_address->save(['is_receiver' => 0],['shop_id' => $this->instance_id]);
        $retval = $shop_express_address->save(['is_receiver' => 1],['express_address_id' => $express_address_id]);
        return $retval;
    }
    /**
     * (non-PHPdoc)
     * @see \data\api\IExpress::getShopExpressAddressList()
     */
    public function getShopExpressAddressList($page_index=1, $page_size=0, $condition='', $order = '')
    {
        $shop_express_address = new NsShopExpressAddressModel();
        $list = $shop_express_address->pageQuery($page_index, $page_size, $condition, $order, '*');
        if(!empty($list['data']))
        {
            $address = new Address();
            foreach ($list['data'] as $k => $v)
            {
                
                $address_info = $address->getAddress($v['province'], $v['city'], $v['district']);
                $list['data'][$k]['address_info'] = $address_info;
            }
        }
        return $list;
    }
    /**
     * (non-PHPdoc)
     * @see \data\api\IExpress::getDefaultShopExpressAddress()
     */
    public function getDefaultShopExpressAddress($shop_id){
        $shop_express_address = new NsShopExpressAddressModel();
        $data = $shop_express_address->getInfo(['shop_id' => $shop_id, 'is_receiver' => 1], '*');
        if(!empty($data))
        {
            $address = new Address();
            $address_info = $address->getAddress($data['province'], $data['city'], $data['district']);
            $data['address_info'] = $address_info;
        }
        return $data;
    }
    /**
     * (non-PHPdoc)
     * @see \data\api\IExpress::deleteShopExpressAddress()
     */
    public function deleteShopExpressAddress($express_address_id_array)
    {
        $shop_express_address = new NsShopExpressAddressModel();
        $shop_id = $this->instance_id;
        $condition = array(
            'shop_id' => $shop_id,
            'express_address_id' => $express_address_id_array
        );
        $retval = $shop_express_address->destroy($condition);
        return $retval;
    }
	/**
     * (non-PHPdoc)
     * @see \data\api\IExpress::selectShopExpressAddressInfo()
     */
	public function selectShopExpressAddressInfo($express_address_id){
		 $shop_express_address = new NsShopExpressAddressModel();
		 $retval = $shop_express_address->getInfo(['express_address_id' => $express_address_id], '*');
         return $retval;
	}
	/**
	 * (non-PHPdoc)
	 * @see \data\api\IExpress::getExpressShippingItemsLibrary()
	 */
	public function getExpressShippingItemsLibrary($shop_id){
	    $express_model=new NsExpressShippingItemsLibraryModel();
	    $item_list=$express_model->getQuery(["shop_id"=>$shop_id], "*", "");
	    return $item_list;
	}
	/**
	 * (non-PHPdoc)
	 * @see \data\api\IExpress::getExpressShipping()
	 */
	public function getExpressShipping($co_id){
	    $express_model=new NsExpressShippingModel();
	    $express_obj=$express_model->getInfo(["co_id"=>$co_id], "*");
	    return $express_obj;
	}
	/**
	 * (non-PHPdoc)
	 * @see \data\api\IExpress::getExpressShippingItems()
	 */
	public function getExpressShippingItems($sid){
	    $express_model=new NsExpressShippingItemsModel();
	    $item_list=$express_model->getQuery(["sid"=>$sid], "*", "");
	    return $item_list;
	}
	/**
	 * 修改物流模板的打印项的位置
	 * (non-PHPdoc)
	 * @see \data\api\IExpress::updateExpressShippingItem()
	 */
	public function updateExpressShippingItem($sid, $itemsArray){
        $items_str=explode(";", $itemsArray);
        foreach($items_str as $item_obj){
            $item_obj_str=explode(",", $item_obj);
            $data=array(
                "field_display_name"=>$item_obj_str[1],
                "is_print"=>$item_obj_str[2],
                "x"=>$item_obj_str[3],
                "y"=>$item_obj_str[4]
            );
            $field_name=$item_obj_str[0];
            $express_item_model=new NsExpressShippingItemsModel();
            $express_item_model->save($data, ["sid"=>$sid, "field_name"=>$field_name]);
        }
	}
	/**
	 * 更新物流模板的信息, 以及打印的信息
	 * @param unknown $template_id
	 * @param unknown $width
	 * @param unknown $height
	 * @param unknown $imgUrl
	 */
	public function updateExpressShipping($template_id, $width, $height, $imgUrl, $itemsArray){
	    $express_model=new NsExpressShippingModel();
	    $express_model->startTrans();
	    try {
	        $data=array(
	            "width"=>$width,
	            "height"=>$height,
	            "image"=>$imgUrl
	        );
	        $result=$express_model->save($data, ["sid"=>$template_id]);
	        $this->updateExpressShippingItem($template_id, $itemsArray);
	        $express_model->commit();
	        return 1;
	    } catch (\Exception $e) {
	        $express_model->rollback();
	        return $e->getCode();
	    }
	}
}