<?php
/**
 * 订单相关数据处理
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * Author: Wangyining <Wangyining@suxuantech.cn>  2019年04月26日
 */
namespace app\mobile\lib;
use think\Controller;
use think\Model;
use think\Session;
use think\cache;

class Order extends Controller{

    //店面列表
    function get_shop($data){

        $url="5a005e0038270";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $info=$res['data'];
        }
        return $info;
    }

    /*
     * 获取事业部下 根据省分类的店面
     */
    public function brandProvinceShop(){
        $p_shop = cache('p_shop_list'.session('brand_id'));
        if(!$p_shop){
            $brand_shop = cache('shop_list_'.session('brand_id'));
            if(!$brand_shop){
                $all_shop = controller('Order','lib')->get_shop(['brandclass_id'=>session('brand_id')]);
                //将会员系统中未设置详情的店 去掉
                $vipShopCode = db('s_shop_info')->where('brand_id',session('brand_id'))->where('is_show',1)->order('sort')->select();
                foreach($vipShopCode as $key => $val){
                    foreach ($all_shop as $k => $v) {
                        if($v['shop_code'] == $val['shop_code']){
                            $brand_shop[] = $v;
                            break;
                        }
                    }
                }
                $brand_shop = array_values($brand_shop);
                cache('shop_list_'.session('brandid'),$brand_shop,3600);
            }

            //省 (去重，去空)
            $province_list = array_filter(array_unique(array_column($brand_shop,'province')));

            $p_shop = [];

            foreach($province_list as $k => $v){
                $p_shop[$k]['province'] = $v;
                foreach($brand_shop as $key => $val){
                    if(strstr($v,$val['province'])){
                        $p_shop[$k]['shop'][] = $val;
                    }
                }
            }

            $p_shop = array_values($p_shop);

            cache('p_shop_list'.session('brand_id'),$p_shop,3600);
        }

        return $p_shop;
    }

    /*
     * 获取某个省下店列表，指定店详情（未指定店则默认取第一个店）
     * $province  省名称
     * $shop_code 店面code
     */
    public function getPShop($province,$shop_code){

        //本事业部下 根据省分类店面
        $p_shop = $this->brandProvinceShop();
        //print_r($p_shop);die;

//        if(!$p_shop){
//            return json(['code'=>201,'data'=>[],'msg'=>'未获取到店面信息']);
//        }

        //当前省的店面
        foreach($p_shop as $k => $v){
            if(strstr($v['province'],$province)){
                $shopList = $v['shop'];
                break;
            }
        }

        //若当前省没有店面，默认展示第一个城市
        if(!$shopList){
            $shopList = $p_shop[0]['shop'];
            $province = $p_shop[0]['province'];
        }


        //若指定店 获取此店信息
        if($shop_code){
            //vip设置的详情
            $shopInfo = db('s_shop_info')->where('shop_code',$shop_code)->find();

            //mc中店信息
            foreach($shopList as $key => $val){
                if($val['shop_code'] == $shop_code){
                    $shopData = $val;
                }
            }

            $shopInfo['city']   = $shopData['city'];
            $shopInfo['county'] = $shopData['county'];
            $shopInfo['shopaddress'] = $shopData['shopaddress'];
            $shopInfo['shop_photo']  = json_decode($shopInfo['shop_img'],true);
        }else{

            //未指定店，则默认取mc中本省第一个店
            $shopData = $shopList[0];

            //vip设置的详情
            $shopInfo = db('s_shop_info')->where('shop_code',$shopData['shop_code'])->find();

            $shopInfo['city'] = $shopData['city'];
            $shopInfo['county'] = $shopData['county'];
            $shopInfo['shopaddress'] = $shopData['shopaddress'];
            $shopInfo['shop_photo']  = json_decode($shopInfo['shop_img'],true);
        }

        if($shopList){
            return ['code'=>200,'data'=>['p_shop'=>$p_shop,'shop_list'=>$shopList,'province'=>$province,'shop_info'=>$shopInfo]];
        }else{
            return ['code'=>202,'data'=>[],'msg'=>'未获取到数据'];
        }
    }


    /*
     *  获取某个店面详情
     */
    public function getShopInfo($shop_code){

        if(!$shop_code){
            return ['code'=>201,'data'=>[],'msg'=>'未获取到店面识别码'];
        }

        $brand_shop = cache('shop_list_'.session('brand_id'));
        if(!$brand_shop){
            $brand_shop = controller('Order','lib')->get_shop(['brandclass_id'=>session('brand_id')]);
            cache('shop_list_'.session('brandid'),$brand_shop);
        }

        foreach($brand_shop as $k => $v){
            if($v['shop_code'] == $shop_code){
                $shop = $v;
                break;
            }
        }

        $shopInfo = db('s_shop_info')->where('shop_code',$shop_code)->find();
        $shopInfo['province'] = $shop['province'];
        $shopInfo['city'] = $shop['city'];
        $shopInfo['county'] = $shop['county'];
        $shopInfo['shopaddress'] = $shop['shopaddress'];
        $shopInfo['shop_type'] = $shop['shop_type'];
        $shopInfo['shop_photo']  = json_decode($shopInfo['shop_img'],true);
        $shopInfo['shop_tel'] = $shopInfo['shop_tel'] ?  $shopInfo['shop_tel'] :'';


        if($shopInfo){
            return ['code'=>200,'data'=>$shopInfo];
        }else{
            return ['code'=>202,'data'=>[],'msg'=>'未获取到数据'];
        }

    }


    /*
     *  某个店面下 一个分类 的套系(标识是否加入购物清单，若已加入付款类型是什么)
     * shop_code
     * cat_id
     */
    public function getShopTypePackage($shop_code,$cat_id){
        if(!get_magic_quotes_gpc()){
            $shop_code = addslashes($shop_code);
        }
        //店面是否展示所有套系（1是，2否 只展示本店套系）
        $all_package = db('c_sysconfig')->where('ckey','all_package')->value('cvalue');
        if($all_package != 1){
            $where['shop_code'] = function($query) use ($shop_code){
                $query->where('shop_code',$shop_code)->where('FIND_IN_SET(\''.$shop_code.'\',erp_package_shop_code)');
            };
        }
        $where['is_del'] = 1;
        if($cat_id)  $where['cat_id'] = $cat_id;

        $package = db('s_package_info')->where($where)->order('p_sort desc, id desc')->select();

        //本店选购清单
        $cartList = $this->getShopCart($shop_code);

        //选购清单里 加入套系的付款类型 1全款 2定金
        $cart_p_type = [];
        foreach($cartList['data']['list'] as $k => $v){
            $cart_p_type[$v['package_id']] = $v['price_type'];
        }

        $cart_p_array = array_column($cartList['data']['list'],'package_id');
        if($cart_p_array)  $cart_p_id = implode(',',$cart_p_array);

        //标识加入选购清单的套系 付款类型
        foreach($package as $key => $val){
            if(in_array($val['id'],$cart_p_array)){
                $package[$key]['is_cart'] = 1;
                $package[$key]['price_type'] = $cart_p_type[$val['id']];
            }
        }

        return ['code'=>200,'data'=>['package'=>$package,'cart_p_id'=>$cart_p_id,'cart_list'=>$cartList['data']['list'],'cart_total_price'=>$cartList['data']['total_price']]];
    }

    /*
     * 获取某店面下的购物清单
     * shop_code
     */
    public function getShopCart($shop_code){
        $cartList = db('s_package_cart')
            ->alias('cart')
            ->join('s_package_info info','cart.package_id = info.id','left')
            ->join('s_cat type','info.cat_id = type.id','left')
            ->where(['cart.user_id'=>session('userid'),'cart.shop_code'=>$shop_code])
            ->where('cart.pay_time is null')
            ->field('cart.id,cart.package_id,info.package_name,info.package_title_img,info.package_price,info.package_price_down,type.name as cat_name,cart.price_type,cart.price')
            ->order('add_time desc')
            ->select();

        $total =  array_sum(array_map(create_function('$val', 'return $val["price"];'), $cartList));

        return ['code'=>200,'data'=>['list'=>$cartList,'total_price'=>$total]];
    }

    /*
     *  加入购物车
     */
    public function addCart($p_id,$price_type,$shop_code){

        $detail = db('s_package_info')->where('id',$p_id)->find();

        //1全款 2定金
        $price = $price_type == 1 ? $detail['package_price'] : $detail['package_price_down'];
        //一次只能下一个店的套系，--songdemei
        db('s_package_cart')->where('user_id',session('userid'))->where('shop_code','<>',$shop_code)->delete();
        $is_exist = db('s_package_cart')->where(['package_id'=>$p_id,'user_id'=>session('userid')])->find();

        if($is_exist){
            $editData = [
                'package_name' => $detail['package_name'],
                'cat_id'     => $detail['cat_id'],
                'price_type' => $price_type,
                'price'      => $price,
                'add_time'   => date('Y-m-d H:i:s')
            ];
            $res = db('s_package_cart')->where(['id'=>$is_exist['id']])->update($editData);

        }else{
            $addData = [
                'package_id' => $p_id,
                'package_name' => $detail['package_name'],
                'cat_id'     => $detail['cat_id'],
                'price_type' => $price_type,
                'price'      => $price,
                'user_id'    => session('userid'),
                'shop_code'  => $shop_code,
                'shop_name'  => $detail['shop_name'],
                'add_time'   => date('Y-m-d H:i:s')
            ];
            $res = db('s_package_cart')->insert($addData);
        }

        if($res === false){
            return ['code'=>201,'msg'=>'加入购物清单失败，请稍后重试'];
        }else{
            return ['code'=>200,'msg'=>'success'];
        }

    }


    /*
    * 获取可用优惠券列表及数量
    */
    public function getCoupon($user_id,$price,$package_id){


        //读取未使用的优惠券(需符合满减条件)
        $couponlist = db("c_coupon_list")->where([
            'userid'=>$user_id,
            'status'=> ['in','(0,4)'] , //未使用
            'expire_time' => ['>=',date('Y-m-d',time())], //未过期
            //'condition_value' => ['<=',$price] //满足使用条件
        ])
            ->where(' FIND_IN_SET("'.$package_id.'",package_ids)  ')
            ->where('brandid',session('brand_id'))
            ->select();

        return array('data'=>$couponlist,'count'=>count($couponlist));

    }

    /**
     * 根据订单单号，返回订单产品列表
     */
    public function getErpOrderPackageInfo($params){
        $orderId = $params['order_id'];  //接取订单id
        $zltype  = $params['zltype'];   //婚纱 儿童判断
        $fc = $params['fc'];//服次
        if(!$orderId){
            return ['code'=>201,'msg'=>'没有获取到订单号！'];
        }

        //防止单号中有空格
        $orderId = get_escape_str($orderId);

        //读取配置文件erp接口地址
        $erp = config('ext.app_config');
        $apiUrl = $erp['sx_erp']['addr'];

        //订单产品信息接口
        if (empty($orderInfo)){
            if($zltype == 'ET'){
                $apiway = 'SX_ChildVipApi';
            }else{
                $apiway = 'SXWebErpAppStaff';
            }
            $url = $apiUrl . '/'.$apiway.'/Vip_SelOrderPackageInfo?Token=^******^&orderid='.$orderId;
            $dataN = json_encode('');
            $response = requestERP($url, $dataN);  //调用erp接口

            //print_r($response);die;
            if ($response['Code'] != 200) {
                //调取不成功待处理
                self::errorLog($url, $response['Msg']);
            }else{
                $orderPackageInfo = $response['Data'];
                unset($response);
                //cache("orderInfo_" . $orderId, $orderInfo, 3600);
            }
        }

        if($orderPackageInfo){
            return ['code'=>200,'msg'=>'success','data'=>$orderPackageInfo];
        }else{
            return ['code'=>204,'msg'=>'未获取到erp订单信息'];
        }
    }

    /*
     * 获取订单详情
     */
    public function getErpOrderInfo($params){
        $orderId = $params['order_id'];  //接取订单id
        $zltype  = $params['zltype'];   //婚纱 儿童判断
        $fc = $params['fc'];//服次

        if(!$orderId){
            return ['code'=>201,'msg'=>'没有获取到订单号！'];
        }

        //防止单号中有空格
        $orderId = get_escape_str($orderId);

        //读取配置文件erp接口地址
        $erp = config('ext.app_config');
        $apiUrl = $erp['sx_erp']['addr'];

        //若不是刷新请求，则取缓存
        if($params['load_type'] != 'refresh'){
            //$orderInfo = cache("orderInfo_" . $orderId); //订单信息
        }

        //订单详情接口
        if (empty($orderInfo)){
             if($zltype == 'ET'){
                $apiway = 'SX_ChildErpAppNew';
            }else{
                $apiway = 'SXWebErpAppStaff';
            }
            $url = $apiUrl . '/'.$apiway.'/SX_InquireCustomerInfoJQ?Token=^******^&orderid='.$orderId;
            $dataN = '';
            $response = requestERP($url, $dataN);  //调用erp接口

            //print_r($response);die;
            if ($response['Code'] != 200) {
                //调取不成功待处理
                self::errorLog($url, $response['Msg']);
            }else{
                $orderInfo = $response['Data'][0];
                $orderInfo['targetdate'] = date('Y-m-d',strtotime($orderInfo['targetdate']));
                //宝宝出生日期
                if($orderInfo['bbithdate']) $orderInfo['bbithdate'] = date('Y-m-d',strtotime($orderInfo['bbithdate']));
                unset($response);
                //cache("orderInfo_" . $orderId, $orderInfo, 3600);
            }
        }

        if($orderInfo){
            return ['code'=>200,'msg'=>'success','data'=>$orderInfo];
        }else{
            return ['code'=>204,'msg'=>'未获取到erp订单信息'];
        }

    }

    /*
     * 获取套系产品详情
     */
    public function getErpPackageInfo($params){
        $orderId = $params['order_id'];  //接取订单id
        $zltype = $params['zltype'];  //婚纱儿童判断
        $fc = $params['fc'];//服次

        if(!$orderId){
            return ['code'=>201,'msg'=>'没有获取到订单号！'];
        }

        //防止单号中有空格等
        $orderId = get_escape_str($orderId);

        //读取配置文件erp接口地址
        $erp = config('ext.app_config');
        $apiUrl = $erp['sx_erp']['addr'];

        //若不是刷新请求，则取缓存
        if($params['load_type'] != 'refresh'){
            //$packArr = cache("packageInfo_" . $orderId); //产品信息
        }

        //产品详情接口
        if (empty($packArr)) {

            if($zltype == 'ET'){
                $apiway = 'SX_ChildErpAppNew';
            }else{
                $apiway = 'SXWebErpAppStaff';
            }
            $packurl = $apiUrl . '/'.$apiway.'/SX_CustomerConsumptionContent?Token=^******^&orderid='.$orderId.'&Code='.$params['shop_code'];
            
            $packdataN = '';
            $pack_response = requestERP($packurl, $packdataN);

            //print_r($pack_response);die;
            if ($pack_response['Code'] != 200) {
                //调取不成功待处理
                self::errorLog($packurl, $pack_response['Msg']);
            }else{
                $packArr = $pack_response['Data'];
                unset($pack_response);
                cache("packageInfo_" . $orderId, $packArr, 3600);
            }

        }

        if($packArr){
            return ['code'=>200,'msg'=>'success','data'=>$packArr];
        }else{
            return ['code'=>204,'msg'=>'未获取到erp产品信息'];
        }

    }

    /*
     * 获取单个套系的设定信息
     */
    public function getPackageSetInfo($params){

        $package_name = $params['package_name'];

        if(!$package_name){
            return ['code'=>201,'msg'=>'没有获取到套系名称！'];
        }

        //读取配置文件erp接口地址
        $erp = config('ext.app_config');
        $apiUrl = $erp['sx_erp']['addr'];

        //套系设定信息接口
        $packurl = $apiUrl . '/SX_ChildErpAppNew/SX_PackageNameSet?Token=^******^&TXName='.$package_name;

        $pack_response = requestERP($packurl, '');

        //print_r($pack_response);die;
        if ($pack_response['Code'] != 200) {
            //调取不成功待处理
            self::errorLog($packurl, $pack_response['Msg']);
        }else{
            $packArr = $pack_response['Data'];
            unset($pack_response);
        }


        if($packArr){
            return ['code'=>200,'msg'=>'success','data'=>$packArr];
        }else{
            return ['code'=>204,'msg'=>'未获取到erp产品信息'];
        }
    }

    /*
     * 获取本服次拍照排程信息
     */
    public function getErpPhoto($params){
        $orderId = $params['order_id'];  //接取订单id
        $fc = $params['fc'];//服次
        $shop_code = $params['shop_code'];
        $zltype = $params['zltype'];

        if(!$orderId){
            return ['code'=>201,'msg'=>'没有获取到订单号！'];
        }

        //防止单号中有空格等
        $orderId = get_escape_str($orderId);

        //读取配置文件erp接口地址
        $erp = config('ext.app_config');
        $apiUrl = $erp['sx_erp']['addr'];

        //若不是刷新请求，则取缓存---------拍照排程信息实时查询
        //if($params['load_type'] != 'refresh'){
        //    $data = cache("PhotoList_".$orderId);
        //}

        //拍照订单列表接口
        if(!$data) {
            if($zltype == 'ET'){
                $apiway = 'SX_ChildErpAppNew';
            }else{
                $apiway = 'SXWebErpAppStaff';
            }
            $url = $apiUrl.'/'.$apiway.'/SX_CustomerPhotoInfo?Token=^******^&orderid='.$orderId.'&Code='.$shop_code;
            
            $response = requestERP($url, '');  //调用erp接口
            //print_r($response);die;
            if ($response['Code'] != 200) {
                //调取不成功待处理
                self::errorLog($url, $response['Msg']);
            }

            $data = $response['Data'];

            cache("PhotoList_".$orderId,$data,3600);
        }

        $photoData = [];

        foreach($data as $k => $v){
            //$v['photodate'] = '';
            if ($v['photodate']){

                $data[$k]['photodate'] = date('Y-m-d', strtotime(substr($v['photodate'], 0, 10)));
                $data[$k]['year'] = date('Y', strtotime(substr($v['photodate'], 0, 10)));
                $data[$k]['month'] = date('m', strtotime(substr($v['photodate'], 0, 10)));
                $data[$k]['day'] = date('d', strtotime(substr($v['photodate'], 0, 10)));
            }else{
                //$data[$k]['photodate'] = '';
                $data[$k]['year'] = date('Y');
                $data[$k]['month'] = date('m');
                $data[$k]['day'] = '00';
            }
            if ($v['phototime']){
                $data[$k]['photoTime'] = substr($v['phototime'], 0, 2) . ':' . substr($v['phototime'], 2, 4);
            }
            if($v['currentfc'] == $fc){
                $photoData[] = $data[$k];
            }
        }
        //print_r($photoData);die;

        if($photoData){
            return ['code'=>200,'msg'=>'success','data'=>$photoData];
        }else{
            return ['code'=>204,'msg'=>'未获取到erp排程信息'];
        }

    }


    /*
     * 获取本服次所有选片详情
     */
    public function getErpSelectInfo($params){
        $orderId = $params['order_id'];  //接取订单id
        $fc = $params['fc'];//服次
        $shop_code = $params['shop_code'];
        $zltype = $params['zltype'];

        if(!$orderId){
            return ['code'=>201,'msg'=>'没有获取到订单号！'];
        }

        //防止单号中有空格等
        $orderId = get_escape_str($orderId);

        //读取配置文件erp接口地址
        $erp = config('ext.app_config');
        $apiUrl = $erp['sx_erp']['addr'];

        //若不是刷新请求，则取缓存
        if($params['load_type'] != 'refresh'){
            //$data = cache("SPInfo_".$orderId);
        }
        //选片列表接口
        if(!$data) {
            if($zltype == 'ET'){
                $apiway = 'SX_ChildErpAppNew';
            }else{
                $apiway = 'SXWebErpAppStaff';
            }
            $url = $apiUrl.'/'.$apiway.'/SX_CustomerXuanPian?Token=^******^&orderid='.$orderId.'&Code='.$shop_code;

            $response = requestERP($url, '');  //调用erp接口
            //print_r($response);die;
            if ($response['Code'] != 200) {
                //调取不成功待处理
                self::errorLog($url, $response['Msg']);
            }

            $data = $response['Data'];
            cache("SPInfo_".$orderId,$data,3600);
        }

        $selectData = [];
        foreach ($data as $k => $v) {

            if ($v['selectday']){

                $data[$k]['selectday'] = date('Y-m-d',strtotime($v['selectday']));
                $data[$k]['year'] = date('Y', strtotime(substr($v['selectday'], 0, 10)));
                $data[$k]['month'] = date('m', strtotime(substr($v['selectday'], 0, 10)));
                $data[$k]['day'] = date('d', strtotime(substr($v['selectday'], 0, 10)));
            }

            //$data[$k]['selectday']  = $data[$k]['selectday']?date('Y-m-d',strtotime($v['selectday'])):'';//选片日期
            $data[$k]['kanbanriqi'] = $data[$k]['kanbanriqi']?date('Y-m-d',strtotime($v['kanbanriqi'])):'';//看版日期
            $data[$k]['kanbanendday'] = $data[$k]['kanbanendday']?date('Y-m-d',strtotime($v['kanbanendday'])):'';//看版完成日期
            $data[$k]['sptend_day'] = $data[$k]['sptend_day']?date('Y-m-d',strtotime($v['sptend_day'])):'';//选片完成日期
            //看版时间
            $data[$k]['kanbanshijian'] = $data[$k]['kanbanshijian']?substr($data[$k]['kanbanshijian'],0,2).':'.substr($data[$k]['kanbanshijian'],2,4):'';

            //选片时间
            $data[$k]['selectTime'] = $data[$k]['selectTime']?substr($data[$k]['selectTime'],0,2).':'.substr($data[$k]['selectTime'],2,4):'';

            //本服次
            if($v['currentfc'] == $fc){
                $selectData[] = $data[$k];
            }
        }

        if($data){
            return ['code'=>200,'msg'=>'success','data'=>$selectData];
        }else{
            return ['code'=>204,'msg'=>'未获取到erp选片详情'];
        }

    }

    /*
     * 获取本服次取件详情
     */
    public function getErpQjInfo($params){
        $orderId = $params['order_id'];  //接取订单id
        $fc = $params['fc'];//服次
        $shop_code = $params['shop_code'];
        $zltype = $params['zltype'];

        if(!$orderId){
            return ['code'=>201,'msg'=>'没有获取到订单号！'];
        }

        //防止单号中有空格等
        $orderId = get_escape_str($orderId);

        //读取配置文件erp接口地址
        $erp = config('ext.app_config');
        $apiUrl = $erp['sx_erp']['addr'];

        //若不是刷新请求，则取缓存
        if($params['load_type'] != 'refresh'){

            $data = cache("QJInfo_".$orderId);
        }

        if(!$data) {
            if($zltype == 'ET'){
                $apiway = 'SX_ChildErpAppNew';
            }else{
                $apiway = 'SXWebErpAppStaff';
            }
            $url = $apiUrl.'/'.$apiway.'/SX_CustomerGetTakeawayItem?Token=^******^&orderid='.$orderId.'&Code='.$shop_code;
            if($fc){
                $url .= '&fc='.$fc;
            }
            $response = requestERP($url, '');  //调用erp接口
            //print_r($response);die;
            if ($response['Code'] != 200) {
                //调取不成功待处理
                self::errorLog($url, $response['Msg']);
            }

            $data = $response['Data'];
            cache("QJInfo_".$orderId,$data,3600);
        }

        $qjData = [];
        foreach ($data as $k => $v) {
            //本服次
            if($v['servicenumber'] == $fc){
                $qjData[] = $data[$k];
            }
        }

        if($qjData){
            return ['code'=>200,'msg'=>'success','data'=>$qjData];
        }else{
            return ['code'=>204,'msg'=>'未获取到erp取件详情'];
        }
    }

    /*
     * 获取某月排程信息
     * shop_code  拍照店面简码
     * area       分区
     * date       当月任意一天日期 （2019-05-10）
     * zltype     区分婚纱/儿童
     */
    public function getMonthPc($shop_code,$area,$date,$zltype){

        $erp = config('ext.app_config');  //读取erp配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用url
        
        //本月排程情况
        // if($zltype == 'ET'){
            $url = $apiUrl.'/SX_ChildErpAppNew/VIP_ET_PhotoPaiChengMonthinfo?Token=^******^&vPcday='.$date.'&Code='.$shop_code.'&photofenqu='.$area;    
        // }else{
        //     $url = $apiUrl.'/SX_VipApi/VIP_PhotoPaiChengMonthinfo?Token=^******^&vPcday='.$date.'&Code='.$shop_code.'&photofenqu=';    
        // }

        //print_r($url);die;
        $response = requestERP($url, '');  //调用erp接口
        //print_r($response);die;
        if ($response['Code'] != 200) {
            //调取不成功待处理
            self::errorLog($url, $response['Msg']);

            return ['code'=>204,'msg'=>'调用erp排程信息失败'];
        }else{
            $monthPC = $response['Data'];

            //去除日期中间的零（例：2018-07-02 => 2018-7-2）
            foreach ($monthPC as $k => $v) {
                $monthPC[$k]['riqi'] = date('Y-n-j', strtotime($v['riqi']));
            }

            return ['code'=>200,'msg'=>'success','data'=>$monthPC];

        }

    }

    /*
     * 获取某天排程时间点
     */
    public function getTimePc($shop_code,$area,$riqi){
        $erp = config('ext.app_config');  //读取erp配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用url

        $date = date('Y-m-d',strtotime($riqi));
        $url = $apiUrl.'/SX_ChildErpAppNew/VIP_ET_PhotoPaiChengDayTimeInfo?Token=^******^&vPcday='.$date.'&Code='.$shop_code.'&photofenqu='.$area;
        //print_r($url);die;
        $response = requestERP($url, '');  //调用erp接口
        //print_r($response);die;
        if ($response['Code'] != 200 && $response['Code'] != '200') {

            //print_r($response['Code']);
            //调取不成功待处理
            self::errorLog($url, $response['Msg']);

            return ['code'=>204,'msg'=>'调用erp某天排程时间点失败'.$response['Msg']];
        }else{
            $timeArr = $response['Data'];

            //规范时间 （例如：0900 => 09:00）
            foreach ($timeArr as $k => $v) {
                $timeArr[$k]['time'] = date('H:i', strtotime($v['pctime']));

                if($v['isok'] == 0 ){//1可选，0不可选
                    unset($timeArr[$k]);
                }
            }

            //print_r($timeArr);die;
            return ['code'=>200,'msg'=>'success','data'=>$timeArr];

        }
    }

    /*
     * erp拍照排程
     */
    public function setErpPhotoPC($params){
        $shop_code = $params['shop_code'];
        $shop_name = $params['shop_name'];
        $area = trim($params['area']);
        $p_id = trim($params['p_id']);
        $fc = trim($params['fc']);
        $orderId = $params['orderId'];
        $customerid = $params['customerid'];
        $chooseDate = $params['chooseDate'];
        $chooseTime = $params['chooseTime'];
$zltype = $params['zltype'];

        $erp = config('ext.app_config');  //读取erp配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用url

        // if($zltype == 'ET'){
            $url = $apiUrl . '/SX_ChildErpAppNew/VIP_ET_OnlinePhotoPaiCheng?Token=^******^&pcday='.$chooseDate.'&photofenqu='.$area.'&Code='.$shop_code;
        // }else{
        //     $url = $apiUrl.'/SX_VipApi/VIP_OnlinePhotoPaiCheng?Token=^******^&pcday='.$chooseDate.'&photofenqu='.$area.'&Code='.$shop_code;    
        // }
        
        $data = [
            'Orderid'   => $orderId,
            'Customerid'=> $customerid,
            'Phototype' => '拍照',
            'Photodate' => date('Ymd',strtotime($chooseDate)),
            'Phototime' => date('Hi',strtotime($chooseTime)),
            'Shop_code' => $shop_code,
            'Shop_name' => $shop_name,
            'Ordernote' => '',
            'Photoid'   => (int)$p_id,
            'Pcid'      => "0",
            'Currentfc' => $fc,
            'Islast'    => "1",
            'Username'  => "线上会员"
        ];

        $response = requestERP($url, json_encode($data));  //调用erp接口

        if ($response['Code'] != 200) {
            return ['code'=>204,'msg'=>'erp线上排程失败！'.$response['Msg']];
        }else{
            return ['code'=>200,'msg'=>'success'];
        }
    }

    /*
    * 获取某月选片排程信息
    * shop_code  拍照店面简码
    * area       分区
    * date       当月任意一天日期 （2019-05-10）
    */
    public function getMonthXpPc($shop_code,$area,$date){

        $erp = config('ext.app_config');  //读取erp配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用url

        //本月排程情况
        $url = $apiUrl.'/SX_ChildErpAppNew/VIP_ET_XPPaiChengMonthinfo?Token=^******^&vPcday='.$date.'&Code='.$shop_code.'&photofenqu='.$area;
        //print_r($url); echo "|";
        $response = requestERP($url, '');  //调用erp接口
        //print_r($response);die;
        if ($response['Code'] != 200) {
            //调取不成功待处理
            self::errorLog($url, $response['Msg']);

            return ['code'=>204,'msg'=>'调用erp排程信息失败'];
        }else{
            $monthPC = $response['Data'];

            //去除日期中间的零（例：2018-07-02 => 2018-7-2）
            foreach ($monthPC as $k => $v) {
                $monthPC[$k]['riqi'] = date('Y-n-j', strtotime($v['riqi']));
            }
            //print_r($monthPC);die;
            return ['code'=>200,'msg'=>'success','data'=>$monthPC];

        }

    }


    /*
     * erp拍照排程
     */
    public function setErpXpPC($params){
        $shop_code = $params['shop_code'];
        $shop_name = $params['shop_name'];
        $area = trim($params['area']);
        $x_id = trim($params['x_id']);
        $fc = trim($params['fc']);
        $orderId = $params['orderId'];
        $customerid = $params['customerid'];
        $chooseDate = $params['chooseDate'];

        $erp = config('ext.app_config');  //读取erp配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用url

        $url = $apiUrl . '/SX_ChildErpAppNew/VIP_ET_OnlineXPPaiCheng?Token=^******^&pcday='.$chooseDate.'&photofenqu='.$area.'&Code='.$shop_code;
        $data = [
            'Orderid'   => $orderId,
            'Customerid'=> $customerid,
            'Spid'      => (int)$x_id,
            'Select_order_name' => '',
            'Selectday' => date('Ymd',strtotime($chooseDate)),
            'SelectTime'=> '',
            'Shop_code' => $shop_code,
            'Shop_name' => $shop_name,
            'Spremarks' => '',
            'Username'  => '线上会员',
            'Currentfc' => $fc,
        ];

        $response = requestERP($url, json_encode($data));  //调用erp接口

        if ($response['Code'] != 200) {
            return ['code'=>204,'msg'=>'erp线上排程失败！'.$response['Msg']];
        }else{
            return ['code'=>200,'msg'=>'success'];
        }
    }



    /**
     * 方法描述: 调取erp错误处理流程
     * @return payCode
     * @author Zhaojiepeng<zhaojiepeng@suxuantech.cn>
     */
    private static function errorLog($url, $data)
    {
        $errorLogData = [
            'url' => $url,
            'data' => $data,
            'create_time' => date('Y-m-d H:i:s'),
            'error_count' => 1,
        ];
        $logRes = db("c_vip_save")->insert($errorLogData);   //写入错误记录日志表
        if (!$logRes) {
            return array('code' => 201, 'msg' => '数据写入失败');
        }
        return 1;
    }

    /*
     * 获取erp的vip卡信息
     */
    public function getErpVipInfo($params){

        $phone = $params['phone'];

        //若不是刷新请求，则取缓存
        if($params['load_type'] != 'refresh'){
            //$data = cache("VipInfo_".$phone);
        }

        if(!$data){
            $erp = config('ext.app_config');   //读取配置文件
            $apiUrl = $erp['sx_erp']['addr'];  //调用erp的url
            $url = $apiUrl.'/SX_ChildErpAppNew/Sel_VipInfo?Token=^******^&wphone='.$phone;
            $response = requestERP($url, json_encode(''));  //调用erp接口
            //print_r($response);die;
            if ($response['Code'] != 200) {
                //调取不成功待处理
                self::errorLog($url, $response['Msg']);
            }

            $data = $response['Data'];

            foreach($data['ds1'] as $k => $v){
                $data['ds1'][$k]['date'] = date('Y-m-d',strtotime($v['paymentdate']));
                $data['ds1'][$k]['time'] = substr($v['paymenttime'], 0, 2) . ':' . substr($v['paymenttime'], 2, 4);
            }

            foreach($data['ds2'] as $k => $v){
                $data['ds2'][$k]['date'] = date('Y-m-d',strtotime($v['paymentdate']));
                $data['ds2'][$k]['time'] = substr($v['paymenttime'], 0, 2) . ':' . substr($v['paymenttime'], 2, 4);
            }

            $data['total_cz'] = array_sum(array_map(create_function('$val', 'return $val["payment_money"];'), $data['ds1']));//总充值
            $data['total_xf'] = array_sum(array_map(create_function('$val', 'return $val["payment_money"];'), $data['ds2']));//总消费

            cache("VipInfo_".$phone,$data);
        }

        if($data){
            return ['code'=>200,'msg'=>'success','data'=>$data];
        }else{
            return ['code'=>204,'msg'=>'未获取到VIP卡信息'];
        }

    }

    /*
     * 增加erp的vip卡积分
     */
    public function addErpVipIntro($params){
        $phone = $params['phone'];
        $erp = config('ext.app_config');   //读取配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用erp的url
        $url = $apiUrl.'/SX_ChildErpAppNew/SX_AddVIPJiFen?Token=^******^';
        $response = requestERP($url, json_encode([
            'cardid'    =>  $phone,
            'resource'  =>  $params['resource'],//积分值
            'sname'     =>  '增加积分',//积分项目
            'remark'    =>  '增加积分',//备注信息
        ]));  //调用erp接口
//        dump($response);die;
        if ($response['Code'] != 200) {
            //调取不成功待处理
            self::errorLog($url, $response['Msg']);
        }
        $data = $response['Data'];
        if($data){
            return ['code'=>200,'msg'=>'success','data'=>$data];
        }else{
            return ['code'=>204,'msg'=>'增加积分失败'];
        }
    }

    /*
     * 减少erp的vip卡积分
     */
    public function reduceErpVipIntro($params){
        $phone = $params['phone'];
        $erp = config('ext.app_config');   //读取配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用erp的url
        $url = $apiUrl.'/SX_ChildErpAppNew/SX_ReduceVIPJiFen?Token=^******^';
        $response = requestERP($url, json_encode([
            'cardid'    =>  $phone,
            'resource'  =>  $params['resource'],//积分值
            'sname'     =>  '增加积分',//积分项目
            'remark'    =>  '增加积分',//备注信息
        ]));  //调用erp接口
//        dump($response);die;
        if ($response['Code'] != 200) {
            //调取不成功待处理
            self::errorLog($url, $response['Msg']);
        }
        $data = $response['Data'];
        if($data){
            return ['code'=>200,'msg'=>'success','data'=>$data];
        }else{
            return ['code'=>204,'msg'=>'增加积分失败'];
        }
    }

    /*
     * 获取先睹为快照片
     */
    public function getSneakPeek($params){

        $orderId = $params['order_id'];
        $fc = $params['fc'];

        //防止单号中有空格等
        $orderId = get_escape_str($orderId);

        $erp = config('ext.app_config');   //读取配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用erp的url
        $mcUrl = $erp['sx_mc']['addr'];    //mc的url

        //$mcUrl = 'http://110.85.187.94:82';

        $url = $apiUrl.'/SX_ChildErpAppNew/Sel_CustomerXianDuWeiKuai?Token=^******^&OrderId='.$orderId;
        $response = requestERP($url, '');  //调用erp接口

        if ($response['Code'] != 200) {
            //调取不成功待处理
            self::errorLog($url, $response['Msg']);
        }

        $data = $response['Data'];

        $xdwkData = [];
        foreach ($data as $k => $v) {
            //本服次
            if((int)$v['currentfc'] == (int)$fc){
                $xdwkData = $data[$k];
            }
        }

        if(!empty($xdwkData)){
            $photoStatus = $xdwkData['xianduweikuai'];

            if($photoStatus == '0000'){
                return [];
            }

            /*
            //新的
            $xdwkMcRes = sx_call('5f2e7db5d9212',['order_id'=>$orderId,'fc_id'=>$fc]);
            if($xdwkMcRes['code'] == 200){
                $photoArr = $xdwkMcRes['data'];
            }else{
                $photoArr = [];
            }
            */



            $statusArr = str_split($photoStatus);

            $photoArr = [];
            foreach($statusArr as $k => $v){
                $num = $k + 1;
                if((int)$v == 1){
                    $photoArr[$num] = trim($mcUrl,'/').'/public/uploads/'.$orderId.'/'.$fc.'/'.$num.'.jpg?v='.date('YmdH');
                }else{
                    $photoArr[$num] = '';
                }
            }



            return ['photo'=>$photoArr,'cameraman'=>$xdwkData['cameraman'],'photo_shop_code'=>$xdwkData['shop_code']];
        }else{
            return [];
        }


    }
    /*
     * 获取订单评价到哪个环节
     * @param [type] $orderId [description]
     */
    public function GetUserLink($orderId){

        if(!$orderId){
            return false;
        }

        //评价到最大的环节
        $res = db('mc_evaluation_questionnaire_user')
               ->where('order_id',$orderId)
               ->where('is_del',1)
               ->field('max(type_id) as type_id')->find();
        
        if($res['type_id']){ 
            return $res['type_id']+1;
        }else{ //没有评价过
            return 1;
        }

    }


    /**
     * 获取用户评价答案
     * [GetUserAnswer description]
     */
    public function GetUserAnswer($orderId,$id,$typeid,$userid){

        if(!$orderId || !$id){
            return  false;
        }
        
        $where['order_id'] = $orderId;
        $where['type_id'] = $typeid;
        $where['userid']  = $userid;
        $userdata = db("mc_evaluation_questionnaire_user")->where($where)->find();
        if(!$userdata){
            return false;
        }
        $user_answerdata = db('mc_evaluation_questionnaire_user_answer')->where('equ_id',$userdata['id'])->where('eq_id',$id)->find();
        if($user_answerdata){
            return $user_answerdata;
        }else{
            return false;
        }
    }

    /**
     * 获取订单 可/已 评价列表
     * [GetUserAnswer description]
     */
    public function reloadEvaluateList($orderId){
        if(!$orderId){
            return false;
        }

        $erp = config('ext.app_config');   //读取配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用erp的url

        $url = $apiUrl.'/SX_VipApi/VIP_GetServiceEvaluationInfo?Token=^******^&OrderId='.$orderId;
        $response = requestERP($url, '');  //调用erp接口

        if ($response['Code'] != 200) {
            //调取不成功待处理
            // self::errorLog($url, $response['Msg']);
            return ['code'=>202,'msg'=>$response['Msg']];
        }else{
            $list = $response['Data'];
            return ['code'=>200,'msg'=>'获取成功','data'=>$list];
        }
        
    }

    /**
     * 获取订单 评价题目列表
     * [GetUserAnswer description]
     */
    public function getEvaluationSet($pftype,$mainid,$order_id){

        if(!$pftype){
            return false;
        }

        $erp = config('ext.app_config');   //读取配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用erp的url

        $url = $apiUrl.'/SX_VipApi/VIP_GetEvaluationSet?Token=^******^&pftype='.$pftype;
        $response = requestERP($url, '');  //调用erp接口
        if ($response['Code'] != 200) {
            //调取不成功待处理
            // self::errorLog($url, $response['Msg']);
            return ['code'=>202,'msg'=>$response['Msg']];
        }else{
            $list = $response['Data'];
            return ['code'=>200,'msg'=>'获取成功','data'=>$list,'mainid'=>$mainid,'order_id'=>$order_id];
        }
        
    }

    //评价提交
    public function addEvaluationInfo($data){
        if(!$data){
            return false;
        }

        $erp = config('ext.app_config');   //读取配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用erp的url

        $url = $apiUrl.'/SX_VipApi/SX_ADDEvaluationInfo?Token=^******^';

        $response = requestERP($url,json_encode($data));  //调用erp接口

        if ($response['Code'] != 200) {
            //调取不成功待处理
            // self::errorLog($url, $response['Msg']);
            return ['code'=>202,'msg'=>$response['Msg']];
        }else{
            return ['code'=>200,'msg'=>'评价成功'];
        }
        
    }

    /**
     *  已评价过，获取评价内容
     */
    public function getYiEvaluationInfo($data)
    {
        if(!$data){
            return false;
        }
        $erp = config('ext.app_config');   //读取配置文件
        $apiUrl = $erp['sx_erp']['addr'];  //调用erp的url

        $url = $apiUrl.'/SX_VipApi/VIP_GetYiEvaluationInfo?Token=^******^';
        $response = requestERP($url,json_encode($data));  //调用erp接口

        if ($response['Code'] != 200) {
            //调取不成功待处理
            // self::errorLog($url, $response['Msg']);
            return ['code'=>202,'msg'=>$response['Msg']];
        }else{
            $list = $response['Data'];
            return ['code'=>200,'msg'=>'评价成功','data'=>$list,'type'=>'已评','scoreremarks'=>$response['scoreremarks']];
        }
    }

}