<?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_wx_tsign_data extends Report {

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

    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'];
        $shop_code = $data['shop_code']?$data['shop_code']:session('shop_code');
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'请选择门店');
        }
        // 人员 网销 行
        /*
        $mc = new \app\common\lib\mcInterface();
        $staffs = [];
        $allStaffs = $mc->getStaffsByWorkType(array('shop_code' => session('shop_code'),'work_type'=>RECEIVE_WORK_TYPE));
        foreach ($allStaffs as $key => $value) {
            $temp['id'] = $value['id'];
            $temp['staffname'] = $value['staffname'];
            array_push($staffs, $temp);
        }
        // var_dump($staffs);die;
        $staffNames = array_column($staffs,'staffname');
        */
        // 所有追踪人
        $allStaffs = db('c_customerinfo')
            ->where('dj_day','between',[$start,$end])
            ->where('shop_code',$shop_code)
            ->group('sales_staff')
            ->field('sales_staff,sales_staff_id')->select();
        $staffs = array_column($allStaffs,'sales_staff');

        // 追踪标记 列
        $marks = db('s_markset')->where('shop_code',$shop_code)->select();
        $marks= array_column($marks,'mark_name');

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

        $sql = 'dj_day between "'.$start.'" and "'.$end.'"';
        
        // 查询追踪标记条件
        $param['sql'] = $sql;
        $param['where'] = $where;
        $param['op_signinfo'] = $marks;
        if ($data['getProvince']) {
            return $this->getTsign($param);
        }
        // 查询追踪标记条件
        $column = $this->getTsign($param);
        // var_dump($column);die;
        // 渠道
        // $channel = db('c_customerinfo')
        //     ->where($where)
        //     ->where($sql)
        //     ->where('op_signinfo','in',$marks)->where('sales_staff','in',$staffs)
        //     ->group('sales_staff')->column('sales_staff');
        // echo db()->getLastSql();die;
        // 数据
        $info = db('c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('op_signinfo','in',$marks)->where('sales_staff','in',$staffs)
            ->group('sales_staff,op_signinfo')
            ->field('sales_staff,op_signinfo,COUNT(id) AS num')
            // ->fetchSql(true)
            ->select();
        // echo db()->getLastSql();die;
        // var_dump($info);die;
        $returnData = [];
        $arr = [];
        foreach ($staffs as $key => $value) {
        	// var_dump($value);
        	$returnData[$key]['staff_name'] = $value;
        	foreach ($info as $k => $v) {
        		if ($value == $v['sales_staff']) {
        			$returnData[$key]['总计'] += $v['num'] ? $v['num'] : 0;
                    $returnData[$key][$v['op_signinfo']] = $v['num'];
        		}
        	}
        	$all += $returnData[$key]['总计'];
        }
        // die;
        $arr = [];
        $arr['staff_name'] = '总计';
        $arr['总计'] = $all;
        // var_dump($column);die;
        foreach ($column as $key => $value) {
        	$arr[$value] = '';
        	foreach ($returnData as $k => $v) {
        		$arr[$value] += $v[$value];
        	}
        }
        array_unshift($returnData, $arr);
        foreach ($returnData as $key => $value) {
            // var_dump($value['总计']);
            foreach ($column as $k => $v) {
                $rate = $value[$v] ? sprintf('%.2f',$value[$v]/$value['总计']*100).'%' : '';
                $returnData[$key][$v] = $rate ? $value[$v].'('.$rate.')' : $value[$v];
            }
        }
        // var_dump($returnData);die;
        // die;
        $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();

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>session('brandclass_id')]);
        $this->assign("consumptionType", $consumptionType);
        
        $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()));

        // 追踪标记
        $marks = db('s_markset')->where('shop_code',$shop_code)->select();

        $marks= array_column($marks,'mark_name');

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

        $param['sql'] = 'dj_day between "2020-06-01 00:00:00" and "'.date('Y-m-d 23:59:59',time()).'"';
    	$param['where'] = $where;
    	$param['op_signinfo'] = $marks;
        $header = $this->getTsign($param);
        $this->assign('header',$header);
        $mc = new \app\common\lib\mcInterface();
        $shopList = $mc->cacheData('5a8fd8296f3d3',['staff_id'=>session('staff_id')]);
        $this->assign('shop_list',$shopList);
        return $this->fetch($display);
    }
    public function getTsign($param){
        $where = $param['where'];
        $sql = $param['sql'];
        $marks = $param['op_signinfo'];

        $column = db('c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('op_signinfo','in',$marks)
            // ->where('customer_channel','in',$channels)
            ->group('op_signinfo')
            ->order('num desc')
            ->field('COUNT(id) as num,op_signinfo')
            ->select();
        // echo db()->getLastSql();die;
        $allProvince = array_column($column,'op_signinfo');
        return $allProvince;
    }
}