<?php
namespace app\common\lib;
class erpInterface {
    protected $options = [
        'address'     => '',//ERP请求地址
        'token' => '^******^',//ERP请求密钥
        // 'token' => '0',//ERP请求密钥
        'shop_type'=>1,//类型，按MC的门店类型：婚纱1，儿童2，注意，ERP内标识是婚纱0儿童1
    ];
    protected $erpConfig = [];
    protected  $handler = null ;
    var $error = '';
    var $errno = '';
    function __construct($options=array()) {
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        $this->erpConfig = config('ext.app_config');
        if($this->options['shop_type'] == 2){
            $this->options['address'] = $this->erpConfig['sx_erp']['addr_child'];
        }else{
            $this->options['shop_type'] = 1;
            $this->options['address'] = $this->erpConfig['sx_erp']['addr'];
        }
    }

    /**
     * 获取ERP的支付类型
     * 
     * @return [array] [收款类型字典]
     */
    public function getPayTypeDict(){
        $pathArray = [
            2=>'/SX_ChildCrmApi/Sel_ZhiFuTypeSet',
            1=>'/SX_CrmApi/Sel_ZhiFuTypeSet'
        ];
        $cacheKey = 'erp_paytype_dict_'.$this->options['shop_type'];
        $result = [];
        if(!cache('?'.$cacheKey)){
            $path = $pathArray[$this->options['shop_type']];
            $url = trim($this->options['address'],'/').$path.'?Token='.$this->options['token'].'&Code=';
            $res = requestERP($url,[]);
            if($res['Code'] == 200){
                $result = $res['Data'];
                cache($cacheKey,$result);
                return $result;
            }else{
                $this->error = $res['Message']?$res['Message']:json_encode($res);
                $this->errno = $res['Code'];
                return false;
            }
        }else{
            return cache($cacheKey);
        }
    }

    /**
     * 获取ERP系统的收款款项
     * @return [array] [款项列表]
     */
    public function getFeeCategoryDict(){
        $pathArray = [
            2=>'/SX_ChildCrmApi/Sel_KuanXiangSet',
            1=>'/SX_CrmApi/Sel_KuanXiangSet'
        ];
        //转输给ERP的款项类型。儿童1婚纱0
        $KXType=$this->getErpShopType();
        $cacheKey = 'erp_feecategory_dict_'.$this->options['shop_type'];;
        $result = [];
        if(!cache('?'.$cacheKey)){
            $path = $pathArray[$this->options['shop_type']];
            $url = trim($this->options['address'],'/').$path.'?Token='.$this->options['token'].'&KXType='.$KXType.'&Code=';
            $res = requestERP($url,[]);
            if($res['Code'] == 200){
                $result = $res['Data'];
                cache($cacheKey,$result);
                return $result;
            }else{
                $this->error = $res['Message']?$res['Message']:json_encode($res);
                $this->errno = $res['Code'];
                return false;
            }
        }else{
            return cache($cacheKey);
        }
    }

    /**
     * 创建订单，即转订单接口
     * 
     * [addNewOrder description]
     */
    public function addNewOrder($data){
        $pathArray = [
            2=>'/SX_ChildCrmApi/Add_CustomerOrderinfo',
            1=>'/SX_CrmApi/Add_CustomerOrderinfo'
        ];
        //转输给ERP的款项类型。儿童1婚纱0
        $path = $pathArray[$this->options['shop_type']];
        $erpShopType=$this->getErpShopType();
        $url = trim($this->options['address'],'/').$path.'?Token='.$this->options['token'].'&CustomerType='.$erpShopType;
        $response = requestERP($url, $data);
        // var_dump($response);die;
        if ($response['Code'] != '200') {
            $this->error = $response['Message']?$response['Message']:json_encode($response);
            $this->errno = $response['Code'];
            return false;
        }
        return $response['Data'];
    }

    /**
     * 获取订单号，参数为：店面简码+人员简码
     *
     *
     */
    public function getOrderSn($data){
        if(customize('bjggt') && time() > strtotime('2020-10-15 00:00:00')){
            switch ($data['Consumption_type']) {
                case "宝宝照":
                case "新生儿":
                    $str = "K5";
                    break;
                case "孕妈照":
                    $str = "M3";
                    break;
                case "亲子照":
                    $str = "P2";
                    break;
                case "全家福":
                    $str = "F0";
                    break;
                default:
                    $str = '';
                    break;
            }
            if(!$str) return '';
            $str  .= date('y');
            $res = db()->query("SELECT max(substring(orderId,5) +0 ) maxid from c_customerorder where left(orderId,4) = '{$str}'");
            if($res){
                $maxNum = $res[0]['maxid'];
            }
            $maxNum = $maxNum?$maxNum:1;
            
            $orderIds = db('c_customerorder')->field('id,orderId')->where('targetdate',date('Ymd'))->where('orderId','like',$str.'%')->order(' id desc ')->column('orderId');
            $formatStr = '%04d';
        }elseif(customize('shynk')){
            $str = $data['ShopSn'].$data['channelCode'].date('ymd');
            if(!$str) return '';
            $orderIds = db('c_customerorder')->field('id,orderId')->where('targetdate',date('Ymd'))->where('orderId','like',$str.'%')->order(' id desc ')->column('orderId');
            $maxNum = 1;
            if (!empty($orderIds)) {
                $maxNum = substr($orderIds[0], -3)+1;
            }
            $formatStr = '%05d';
        }else{
            $str = $data['ShopSn'].$data['StaffSN'].date('ymd');
            $orderIds = db('c_customerorder')->field('id,orderId')->where('targetdate',date('Ymd'))->where('orderId','like',$str.'%')->order(' id desc ')->column('orderId');
            $maxNum = 1;
            if (!empty($orderIds)) {
                $maxNum = substr($orderIds[0], -3)+1;
            }
            $formatStr = '%03d';
        }
        
        $i = 0;
        do{
            $orderId = $str.sprintf($formatStr, $maxNum);
            $find = db('c_customerorder')->where('orderId',$orderId)->find();
            if(!$find){
                break;
            }
            $maxNum++;
            $i++;
            if($i > 200){
                break;
            }
        }while (1);
        if(strlen($orderId) > 50){
            return false;
        }
        return $orderId?$orderId:false;
    }
    /**
     * 开单
     *
     *
     */
    public function createOrder($data){
        $pathArray = [
            2=>'/SX_ChildCrmApi/createOrder',
            1=>'/SX_CrmApi/createOrder'
        ];
        //转输给ERP的款项类型。儿童1婚纱0
        $path = $pathArray[$this->options['shop_type']];
        $url = trim($this->options['address'],'/').$path.'?Token='.$this->options['token'];
        $response = requestERP($url, $data);
        // print_r($response);die;
        return $response;
    }
    /**
     * 获取订单相关信息(分区，来源等)，参数为：店面简码
     *
     * [addNewOrder description]
     */
    public function getCreateOrderInfo($data){
        $response = [];
        $response['Code'] = 200;

        if(empty($data['shop_code'])){
            $response['Code'] = 100;
            $response['Message'] = 'shop_code不能为空';
            $response['Data'] = [];
            return $response;
        }
        $response['Data']['dt_s_consumptiontype'] = db('s_consumptiontype')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('id,consumption_name,mustfill')->select();
        $response['Data']['dt_s_customerareaset'] = db('s_customerareaset')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('area_name')->select();
        $response['Data']['dt_s_cussource'] = db('s_cussource')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('cus_name')->select();
        $response['Data']['dt_s_acceptoraddress'] = db('s_acceptoraddress')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('acceptoraddress_name')->select();

        $tx = db('s_packageset')->where("find_in_set('".$data['shop_code']."',shop_code)")->where('iscanuse',1)->field('package_name,package_price,"tx" as type')->select();
        
        $cz = db('s_czpackageset')->where("find_in_set('".$data['shop_code']."',shop_code)")->where('iscanuse',1)->field('czpackage_name as package_name,czpackage_price as package_price,"cz" as type')->select();

        $response['Data']['dt_s_packageset'] = array_merge($tx,$cz);
        $response['Data']['dt_s_hospitalset'] = db('s_hospitalset')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('hospital')->select();
        $response['Data']['dt_c_paymenttype'] = db('c_paymenttype')->where("find_in_set('".$data['shop_code']."',shop_code)")->where('iscanuse','0')->select();

        $response['Data']['dt_s_topic'] = db('s_topic')->where("find_in_set('".$data['shop_code']."',shop_code)")->select();

        return $response['Data'];
    }
    /*
    public function getCreateOrderInfo($data){
        $pathArray = [
            2=>'/SX_ChildCrmApi/Sel_CreateOrderInfo',
            1=>'/SX_CrmApi/Sel_CreateOrderInfo'
        ];
        //转输给ERP的款项类型。儿童1婚纱0
        $path = $pathArray[$this->options['shop_type']];
        $url = trim($this->options['address'],'/').$path.'?Token='.$this->options['token'].'&Code='.$data['shop_code'];
        $response = requestERP($url, '');
        // var_dump($url);
        // var_dump($response);
        // exit;
        if ($response['Code'] != '200') {
            $this->error = $response['Message']?$response['Message']:json_encode($response);
            $this->errno = $response['Code'];
            return false;
        }
        return $response['Data'];
    }*/
    /**
     * 根据CRM店类型，返回ERP对应店类型。
     * 
     * @return [type] [description]
     */
    public function getErpShopType(){
        return $this->options['shop_type']==1?0:1;
    }
    /**
     * 变更类的门店类型，
     * 
     * @param integer $shopType [description]
     */
    public function setShopType($shopType = 0){
        if($shopType == 2){
            $this->options['shop_type'] = 2;
            $this->options['address'] = $this->erpConfig['sx_erp']['addr_child'];
        }else{
            $this->options['shop_type'] = 1;
            $this->options['address'] = $this->erpConfig['sx_erp']['addr'];
        }
    }
    /**
     * 变更类型的访问地址
     * 
     * @param string $address [description]
     */
    public function setAddress($address = ''){
        if($address){
            $this->options['address'] = $address;
        }
    }
    /**
     * 清除缓存方法，清除除所有本类设置的缓存
     * 
     * @param  string $cacheName [description]
     * @return [type]            [description]
     */
    static function cleanCache($cacheName=''){
        if($cacheName){
            cache($cacheName.'*',null);
        }
        cache('erp_paytype_dict_*',null);
        cache('erp_feecategory_dict_*',null);
    }

}