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

class Cd_unvalid_cause extends Report {

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

    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('crm_s_report_form')->alias('f')->join('crm_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();

        //可操作店
        if($data['shop_code']){
            $shop_code = $data['shop_code'];
        }elseif($det['shop_code']){
            $shop_code = $det['shop_code'];
        }else{
            $shop_code = session('shop_code');
        }
        
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'请选择店面');
        }

        if($data['channel_id']){
            $channels = explode(',',$data['channel_id']);
            $channel_data = db('crm_s_channel')->where("channel_name","in",$data['channel_id'])->order("order_sort")->select();
            $channel_datas = array_column($channel_data, 'channel_info_name');
            // asort($channel_datas);
            $channelData = [];
            foreach($channel_datas as $key=>$value){
                $channelData[] = $channel_data[$key];
            }
        }elseif($data['erji_channel_id']){
            // 来源渠道
            $channels = explode(',',$data['erji_channel_id']);
            $channel_data = db('crm_s_channel')->where("channel_info_name","in",$data['erji_channel_id'])->order("order_sort")->select();
            $channel_datas = array_column($channel_data, 'channel_info_name');
            // asort($channel_datas);
            $channel_datas = array_unique($channel_datas);
            $channelData = [];
            foreach($channel_datas as $key=>$value){
                $channelData[] = $channel_data[$key];
            }
        }else{
            // 来源渠道
            $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
            $channel_datas = array_column($channels, 'channel_info_name');
            // asort($channel_datas);
            $channel_datas = array_unique($channel_datas);
            $channelData = [];
            foreach($channel_datas as $key=>$value){
                $channelData[] = $channels[$key];
            }
            $channels = array_column($channels,'channel_info_name');
        }

        if((int)$data['consultation_type_id']){
            $where['consultation_type_id'] = (int)$data['consultation_type_id'];
        }

        //客资无效原因
        $allReason = controller('crm/Customer','lib')->getUnValidReason();
        $unvalidReasons = array_column($allReason,'reason');

        $where['dj_day'] = ['between',[$start,$end]];
        
        if($data['channel_id']){
            // 数据
            $info = db('crm_c_customerinfo')
            ->where($where)
            ->where('customer_channel','in',$channels)
            ->where('unvalid_reason','in',$unvalidReasons)
            ->group('unvalid_reason,customer_channel')
            ->field('unvalid_reason,customer_channel,COUNT(id) AS num')
            ->select();    
        }else{
            // 数据
            $info = db('crm_c_customerinfo')->alias('i')
            ->join('crm_s_channel s','i.customer_channel=s.channel_name','left')
            ->where($where)
            ->where('s.channel_info_name','in',$channels)
            ->where('unvalid_reason','in',$unvalidReasons)
            ->group('unvalid_reason,s.channel_info_name')
            ->field('unvalid_reason,s.channel_info_name,COUNT(i.id) AS num')
            ->select();
        }
        
        $sql1 = db()->getLastSql();

        $returnData = [];
        $arr = [];
        foreach ($channelData as $key => $value) {
            // var_dump($value);
            $channel = 'channel_info_name';
            $info_channel = 'channel_info_name';
            if($data['channel_id']){
                $channel = 'channel_name';
                $info_channel = 'customer_channel';
                $returnData[$key]['channel_name'] = $value['channel_name'];
            }
            $returnData[$key]['channel_info_name'] = $value['channel_info_name'];
            foreach ($info as $k => $v) {
                if ($value[$channel] == $v[$info_channel]) {
                    $returnData[$key][$v['unvalid_reason']] = $v['num'] ? $v['num'] : 0;
                    $returnData[$key]['总计'] += $v['num'] ? $v['num'] : 0;
                }
            }
            $all += $returnData[$key]['总计'];
        }
        $arr = [];
        $arr['channel_name'] = '总计';
        $arr['总计'] = $all;
        foreach ($unvalidReasons as $key => $value) {
            $arr[$value] = '';
            foreach ($returnData as $k => $v) {
                $arr[$value] += $v[$value];
            }
        }

        array_unshift($returnData, $arr);
        $return['sql1'] = $sql1;
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channel)+1;
        $return['data']  = $returnData;
        $return['unvalidReasons'] = $unvalidReasons;
        
        return json($return);
        
    }
    public function show(){
        $code = $this->getCode();
        /*
        $did = strtolower(input('param.did'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_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();*/
        $menu_code = strtolower(input('param.menu_code'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_s_report_detail d','d.form_id=f.id','left')->where('f.code',$menu_code)->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();

        //来源渠道
        $channel = getChannelJson(session('shop_code'));
        $this->assign("channel", json_encode($channel));

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>session('brandclass_id')]);
        $this->assign("consumptionType", $consumptionType);
        //渠道一二级
        $channel2 = getChannelJson12($shop_code);
        $this->assign("channel2",json_encode($channel2));

        //事业部下店面
        $mc = new \app\common\lib\mcInterface;
        $shopList = $mc->getWorkShop(['staff_id'=>session('staff_id'),'brandclass_id'=>session('brandclass_id')]);
        $this->assign('shopList',$shopList);
        $this->assign("shop_code", $info['shop_code']?$info['shop_code']:session('shop_code'));

        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';

        $this->assign('title', session('shop_name').'-'.$info['report_name']);

        //客资无效原因
        $allReason = controller('crm/Customer','lib')->getUnValidReason();

        $unvalidReasons = array_column($allReason,'reason');

        /*$where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $info['shop_code'];

        $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['unvalid_reason'] = $unvalidReasons;
        $header = $this->getUnvalidReason($param);*/

        //表格隐藏列
        $this->assign('hiddenColumns',explode('|',cookie('report_cd_unvalid_cause_hidden')));

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

        return $this->fetch($display);
    }
    public function getUnvalidReason($param){
        $where = $param['where'];
        $sql = $param['sql'];
        $unvalid_reason = $param['unvalid_reason'];

        $column = db('crm_c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('unvalid_reason','in',$unvalid_reason)
            ->group('unvalid_reason')
            ->order('num desc')
            ->field('COUNT(id) as num,unvalid_reason')
            ->select();
            
        $allProvince = array_column($column,'unvalid_reason');
        return $allProvince;
    }
}