<?php
/**
 * CRM项目默认类，此类在素玄系统内每个模块都有，供全局管理系统间握手使用
 * 
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 * 
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
    function _initialize() {
        if(!defined('IS_POST')){
            define('IS_POST', \think\Request::instance()->isPost());
        }
        /*
        if(!file_exists(APP_PATH.'../runtime'.DS.'Suxuan.php'))
        {
            $this->redirect('install/index/index');
            exit();
        }*/
    }
    public function index()
    {
        $this->redirect('crm/Index/index');
        
        // if($this->is_weixin()){
        //     $APPID='wxe1d66f5605ddc128';
        //     $REDIRECT_URI=urlencode('http://crm.sx.com/crm/Index/index/');
        //     $scope='snsapi_base';
        //     $scope='snsapi_userinfo';//需要授权
        //     $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.$REDIRECT_URI.'&response_type=code&scope='.$scope.'&state=STATE#wechat_redirect';
        //     $this->redirect($url);
        //     $this->redirect('crm/Index/index');
        // }else{
        //     $this->redirect('crm/Index/index');
        // }
    }
    ///判断是PC还是微信登录
    function is_weixin(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') !== false ) {
            return true;
        }else{
            return false;
        }
    }
    public function login() {
        /*
        if(IS_POST){
            //处理登录请求
            $param['password'] = input('post.password');
            $param['staffname'] = input('post.staffname');
            $param['five'] = input('post.five');
            $res = controller('crm/Customer','lib')->login($param);
            return $res;
        }else{
            //return $this->fetch();
        }
        */
        $this->redirect('/crm/index/login');

    }
    function getClientIp(){
        $ret = [
            'code'=>200,
            'msg'=>'',
            'data'=>'',
        ];
        $ret['data']['ip'] = get_client_ip();

        return json($ret);
    }
    function loginQrShow() {

        if(\think\Request::instance()->isAjax()){
            
            
        }else{
            
        }
        $qrcodeInfo = session('qrlogincodeinfo');
        
        if(!$qrcodeInfo  || $qrcodeInfo['expire'] > time()){
            $response = sx_call('5a1027da4e9c1');
            if($response && $response['code'] == 200){
                $qrcodeInfo = $response['data'];
                session('qrlogincodeinfo',$qrcodeInfo);
            }
        }
        
        $qrcode = new \Endroid\QrCode\QrCode();
        $qrcode->setText($qrcodeInfo['qr_code']);
        echo $qrcode->writeString();
    }

    // 追踪记录  erp用
    public function trackInfo(){
        $is_erp = is_install('sx_erp');
        if ($is_erp === false) {
            return $this->error('没有安装erp系统');
        }

        $data = input();

        $phone = $data['phone'];
        $bid   = (int)$data['bid'];
        $cInfo = db('c_customerinfo')
            ->where('brandclass_id', $bid)
            ->where('customer_tel|customer_wechat|customer_qq|mate_tel|mate_wechat|mate_qq', $phone)
            ->field('id,customer_name,customer_sex,customer_tel,customer_wechat,mate_name,mate_sex,mate_tel,mate_wechat,consultation_type,is_valid,dj_staff,add_shop_name,sales_staff,shop_name')
            ->order('c_end_day, id desc')
            ->find();
        $this->assign('cInfo',$cInfo);
        // 查询追踪记录表
        $trackInfo = db('c_salestrackinginfo')
            ->where('customer_id', $cInfo['id'])
            ->field('gtType, customer_name, customer_tel, customer_intention, consultation_type, tel_alltime, tel_static, sales_day, sales_staff, sales_remark')
            ->order('sales_day desc')
            ->select();
        $this->assign('track',$trackInfo);
        return $this->fetch();
    }

    // 订单详情  erp用
    public function orderInfo(){
        $is_erp = is_install('sx_erp');
        if ($is_erp === false) {
            return $this->error('没有安装erp系统');
        }
        $data = input();

        $order_sn  = $data['order_sn'];
        $customer_type = $data['customer_type'];
        $sign      = $data['sign'];
        $secret    = 'oUWKYeqCEojOvbmsynvWTctJSAVeoMZv';
        
        $auth = md5($order_sn.$customer_type.$secret);
        // var_dump($auth);
        // exit;
        if ($auth === $sign) {
            $erp = config('ext.app_config')['sx_erp'];
            $shop_type = session('shop_type');
            $tel = 1;
            if ($shop_type == 2) {
                $shop_type = 1;
                $addr= $erp['addr_child'];
                $url = $addr.'SX_ChildCrmApi/All_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Tel='.$tel.'&orderId='.$order_sn;
            }else{
                $shop_type = 0;
                $addr= $erp['addr'];
                $url = $addr.'SX_CrmApi/All_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Tel='.$tel.'&orderId='.$order_sn;
            }
            $dataErp = '[]';

            $response = requestERP($url, $dataErp);

            if ($response['Code'] == 200) {
                // 基础信息  订单表
                $baseInfo = $response['Data']['C_order'];
//                 print_r($baseInfo);die;
                $this->assign('baseInfo', $baseInfo);
                // 产品信息  消费项目
                $cpInfo = $response['Data']['C_page'];
                $this->assign('cpInfo', $cpInfo);
                // 摄影信息  
                $syInfo = $response['Data']['C_photo'];
                $this->assign('syInfo', $syInfo);
                // print_r($syInfo);
                // 选片信息 
                $xpInfo = $response['Data']['C_sp'];
                $this->assign('xpInfo', $xpInfo);
                // 收款信息
                $skInfo = $response['Data']['C_payment'];
                $this->assign('skInfo', $skInfo);
                // 化妆信息
                $hzInfo = $response['Data']['C_makeup'];
                $this->assign('hzInfo', $hzInfo);
                // 礼服信息
                $lfInfo = $response['Data']['C_dress'];
                $this->assign('lfInfo', $lfInfo);
                // var_dump($lfInfo);
            }
            
            $this->assign('order_sn', $order_sn);
            return $this->fetch();
        }else{
            return $this->error('签名错误'); 
        }
    }
    // 根据客资编号 （ customer_number ） 查看追踪记录
    public function getTrackInfo(){
        $app = config('ext.app_config');
        if (empty($all['sx_erp'])) {
            // return $this->error('没有安装erp系统');
        }
        $data = input();

        $customer_number = trim($data['customer_number']);
        $cid = db('c_customerinfo')->where('customer_number', $customer_number)->value('id');
        // $customer_number = (int)$data['customer_number'];
        // 查询追踪记录表
        $trackInfo = db('c_salestrackinginfo')
            ->where('customer_id', $cid)
            ->field('gtType, customer_name, customer_tel, customer_intention, consultation_type, tel_alltime, tel_static, sales_day, sales_staff, sales_remark')
            ->order('sales_day',desc)
            ->select();
        // echo db()->getLastSql();
        // var_dump($trackInfo);exit;
        $this->assign('track',$trackInfo);


        // 修改日志
        $changeLogs = controller("crm/Customer","lib")->getCustomerChangeLogs($cid);
        $info = [];
        foreach($changeLogs as $k=>$v){
            if(is_json($v['old_data']) || is_json($v['data'])){
                $oldDate = json_decode($v['old_data'], true);
                $oldDateStr = '';
                foreach ($oldDate as $kk => $vv) {
                    $key = translate('c_customerinfo',$kk);
                    if($kk == 'is_valid'){
                        $vv = getIsValid($vv);
                    }
                    if($kk == 'is_intostore'){
                        $vv = getIsIntostore($vv);
                    }
                    if($kk == 'is_loss'){
                        $vv = getIsLoss($vv);
                    }
                    if($kk == 'is_status'){
                        $vv = getIsStatusAttr($vv);
                    }
                    if($key){
                        $oldDateStr .= $key.'：'.$vv.'；<br>';
                    }
                }
                $newDate = json_decode($v['data'], true);

                $newDateStr = '';
                foreach ($newDate as $kkk => $vvv) {
                    if($kkk == 'is_valid'){
                        $vvv = getIsValid($vvv);
                    }
                    if($kkk == 'is_intostore'){
                        $vvv = getIsIntostore($vvv);
                    }
                    if($kkk == 'is_loss'){
                        $vvv = getIsLoss($vvv);
                    }
                    $key1 = translate('c_customerinfo',$kkk);
                    if($key1){
                        $newDateStr .= $key1.'：'.$vvv.'；<br>';
                    }
                }
                $info[$k]['oldDateStr'] = $oldDateStr;
                $info[$k]['newDateStr'] = $newDateStr;
                $info[$k]['create_time'] = $v['create_time'];
                $info[$k]['staff_name'] = $v['staff_name'];
            }else{
                $oldDate = json_decode($v['old_data'], true);
                $oldDateStr = $v['old_data'];
                foreach ($oldDate as $kk => $vv) {
                    $oldDateStr .= $kk.'：'.$vv.'；';
                }
                $newDate = json_decode($v['data'], true);
                $newDateStr = '';
                foreach ($newDate as $kk => $vv) {
                    $newDateStr .= $kk.'：'.$vv.'；';
                }
                $oldDateStr = $v['old_data'];
                $newDateStr = $v['data'];
                $info[$k]['oldDateStr'] = $oldDateStr;
                $info[$k]['newDateStr'] = $newDateStr;
                $info[$k]['create_time'] = $v['create_time'];
                $info[$k]['staff_name'] = $v['staff_name'];
            }
        }
        $this->assign('changeLogs', $info);    
        return $this->fetch();
    }

}
