<?php
/**
 * 报表实现类 西安绝对人气 定制 市域客资分析
 * *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong 2020-05 $
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;

class Xa_city_data extends Report {

    private $level= 1;
    private $type = 1;
    private $code = 'code1592991493';

    public function getLevel(){
        return $this->level;
    }
    public function getType(){
        return $this->type;
    }
    public function getCode(){
        return $this->code;
    }
    public function data(){
        set_time_limit(0);
        $data = input();
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        // $det = db('s_report_form')->alias('f')->join('s_report_detail d','d.form_id=f.id')->where('d.id',$data['did'])->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();
        // $shop_code = $det['shop_code'];
        $add_shop_code = session('shop_code');
        $shop_code = $data['shop_code']?$data['shop_code']:session('shop_code');
        // $shop_code = session('shop_code');
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'请选择门店');
        }
        if($data['channel_id']){
            $channels = explode(',',$data['channel_id']);
            $whereT['customer_channel'] = ['in', $channels];
        }
        // 根据省 取 省下的城市
        $province = $data['province'];
        $citys = db('s_shop_address')->where('type',2)->where('pid',$province)->where('shop_code',session('shop_code'))->select();
        $allCitys= array_column($citys,'name');

        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        // $where['c.add_shop_code'] = $add_shop_code;
        $where['c.shop_code'] = $shop_code;
        $where['c.province_id'] = $province;
        if((int)$data['consultation_type_id']){
            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
        }

        $yxconfig = db_config('yx_config') ? db_config('yx_config') : "'1','5'";
		$wxconfig = db_config('wx_config') ? db_config('wx_config') : "'3','4'";
		$ddconfig = db_config('dd_config') ? db_config('dd_config') : "'2'";

        $sql = '';
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'") as mkz,';
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$yxconfig.')) as valid,';
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$wxconfig.')) as unValid,';
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$ddconfig.')) as dd,';
        $sql .= 'sum(c.syjd_day between "'.$start.'" and "'.$end.'" and c.is_intostore in (\'2\',\'3\',\'5\')) as jd,';
        $sql .= 'sum(c.order_start_time between "'.$start.'" and "'.$end.'" and c.is_success!=2) as ddl, ';
        $sql .= 'sum(c.order_day between "'.$start.'" and "'.$end.'" and c.is_success=1) as `order`';
        
        // 数据
        $info = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where($whereT)
            ->where('c.city','in',$allCitys)
            ->group('c.city')
            ->column($sql, 'c.city');
        // echo db()->getLastSql();die;
        // var_dump($info);die;
        //实收
        $allMoney = db('c_customerinfo')->alias('c')
            ->where($where)->where($whereT)
            ->where('c.city','in',$allCitys)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.city')
            ->column('sum(c.fact_money) as fact,sum(c.totalpay_money) as total', 'c.city');
        // echo db()->getLastSql();die;
        $returnData = [];
        $arr = [];
        foreach ($allCitys as $k => $v) {
        	// var_dump($value);
        	$returnData[$k]['city'] = $v;
            $returnData[$k]['mkz'] = $info[$v]['mkz'];
            $returnData[$k]['valid'] = $info[$v]['valid'];
            $returnData[$k]['validRate'] = $info[$v]['valid'] ? sprintf('%.2f',$info[$v]['valid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['unValid'] = $info[$v]['unValid'];
            $returnData[$k]['unValidRate'] = $info[$v]['unValid'] ? sprintf('%.2f',$info[$v]['unValid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['dd'] = $info[$v]['dd'];
            $returnData[$k]['ddRate'] = $info[$v]['dd'] ? sprintf('%.2f',$info[$v]['dd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['jd'] = $info[$v]['jd'];
            $returnData[$k]['ddl'] = $info[$v]['ddl'];
            $returnData[$k]['order'] = $info[$v]['order'];
            $returnData[$k]['mkzJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['validJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['valid']*100).'%' : '0%';
            $returnData[$k]['jdOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['jd']*100).'%' : '0%';
            $returnData[$k]['mkzOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['validOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['valid']*100).'%' : '0%';
            $returnData[$k]['totalMoney'] = sprintf('%.2f',$allMoney[$v]['total']);
            $returnData[$k]['factMoney'] = sprintf('%.2f',$allMoney[$v]['fact']);
            $returnData[$k]['orderAVG'] = $info[$v]['order'] ? sprintf('%.2f',$allMoney[$v]['total']/$info[$v]['order']) : '';

        	$arr['city'] = '总计';
            $arr['mkz'] += $info[$v]['mkz'];
            $arr['valid'] += $info[$v]['valid'];
            $arr['unValid'] += $info[$v]['dd'];
            $arr['dd'] += $info[$v]['unValid'];
            $arr['jd'] += $info[$v]['jd'];
            $arr['ddl'] += $info[$v]['ddl'];
            $arr['order'] += $info[$v]['order'];
            $arr['totalMoney'] += sprintf('%.2f',$allMoney[$v]['total']);
            $arr['factMoney'] += sprintf('%.2f',$allMoney[$v]['fact']);
        }
        $arr['validRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '0%';
        $arr['unValidRate'] = $arr['unValid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
        $arr['ddRate'] = $arr['dd'] ? sprintf('%.2f',$arr['dd']/$arr['mkz']*100).'%' : '0%';
        $arr['mkzJdRate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['mkz']*100).'%' : '0%';
        $arr['validJdRate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['valid']*100).'%' : '0%';
        $arr['jdOrderRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['jd']*100).'%' : '0%';
        $arr['mkzOrderRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%' : '0%';
        $arr['validOrderRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%' : '0%';
        $arr['orderAVG'] = $arr ? sprintf('%.2f',$arr['total']/$arr['order']) : '';
        // die;
        // array_unshift($returnData, $arr);
        $returnData[] = $arr;
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channel)+1;
        $return['data'] = $returnData;
        
        return json($return);
    }
    public function show(){
        $code = $this->getCode();
        $did = strtolower(input('param.did'));
        $shop_code = session('shop_code');
        // $info = db('s_report_form')->alias('f')->join('s_report_detail d','d.form_id=f.id')->where('d.id',$did)->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();
        //来源渠道
        $channel = getChannelJson($shop_code);
        $this->assign("channel", json_encode($channel));
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>session('brandclass_id')]);
        $this->assign("consumptionType", $consumptionType);
        // 省
        $province = db('s_shop_address')->where('type',1)->where('shop_code',$shop_code)->select();
        $this->assign('province', $province);
        $info = db('s_report_form')->where('code', $code)->field('report_class_name,report_name')->find();
        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $this->assign('title', session('shop_name').'-'.$info['report_name']);

        // $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);

        $this->assign('did', $info['id']);
        $this->assign('today',date('Y-m-d'));
        $this->assign('yestoday',date('Y-m-d',time()));


        $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        $channels = array_column($channels,'channel_name');
        // 省
        $province = db('s_shop_address')->where('type',1)->where('shop_code',session('shop_code'))->select();
        $provinces= array_column($province,'name');

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        $mc = new \app\common\lib\mcInterface();
        $shopList = $mc->cacheData('5a8fd8296f3d3',['staff_id'=>session('staff_id')]);
        $this->assign('shop_list',$shopList);

        $sql = 'dj_day between "'.date('Y-m-d 00:00:00',time()).'" and "'.date('Y-m-d 23:59:59').'"';
        $param['sql'] = $sql;
    	$param['where'] = $where;
    	$param['provinces'] = $provinces;
    	$param['channels'] = $channels;

        return $this->fetch($display);
    }
}