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

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

    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'=>'请选择门店');
        }
        // if($data['channel_id']){
        //     $channels = explode(',',$data['channel_id']);
        // }else{
        //     // 来源渠道
        //     $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        //     $channels = array_column($channels,'channel_name');
        // }

        // 人员 网销
        $staffs = [];
        // $mc = new \app\common\lib\mcInterface();
        // $allStaffs = $mc->getStaffsByWorkType(array('shop_code' => session('shop_code'),'work_type'=>RECEIVE_WORK_TYPE));
        // 所有追踪人
        $allStaffs = db('c_customerinfo')
            ->where('dj_day','between',[$start,$end])
            ->where('shop_code',$shop_code)
            ->where('sales_staff_id','>',0)
            ->group('sales_staff')
            ->field('sales_staff,sales_staff_id')->select();
        foreach ($allStaffs as $key => $value) {
            $temp['id'] = $value['sales_staff_id'];
            $temp['staffname'] = $value['sales_staff'];
            array_push($staffs, $temp);
        }
        $staffNames = array_column($staffs,'staffname');

        //客资无效原因
        $allReason = controller('crm/Customer','lib')->getUnValidReason();
        $unvalidReasons = array_column($allReason,'reason');
        if((int)$data['consultation_type_id']){
            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
        }

        switch ($data['data_type']) {
        	case 'mkz':
        		$sql = 'dj_day between "'.$start.'" and "'.$end.'"';
        		break;
            default:
                $sql = 'dj_day between "'.$start.'" and "'.$end.'"';
                break;
        }
        
        // 查询省条件
        $param['sql'] = $sql;
        $param['where'] = $where;
        $param['unvalid_reason'] = $unvalidReasons;
        if ($data['getProvince']) {
            return $this->getUnvalidReason($param);
        }
        // 省
        $column = $this->getUnvalidReason($param);
        // var_dump($column);die;
        // 渠道
        $channel = db('c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('unvalid_reason','in',$column)->where('sales_staff','in',$staffNames)
            ->group('sales_staff')->column('sales_staff');
        // 数据
        $info = db('c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('is_valid',3)
            ->where('unvalid_reason','in',$column)->where('sales_staff','in',$staffNames)
            ->group('unvalid_reason,sales_staff')
            ->field('unvalid_reason,sales_staff,COUNT(id) AS num')
            // ->fetchSql(true)
            ->select();
        $sql1 = db()->getLastSql();
        // var_dump($info);die;
        $returnData = [];
        $arr = [];
        foreach ($staffs as $key => $value) {
        	// var_dump($value);
        	$returnData[$key]['staff_name'] = $value['staffname'];
        	foreach ($info as $k => $v) {
        		if ($value['staffname'] == $v['sales_staff']) {
        			$returnData[$key][$v['unvalid_reason']] = $v['num'] ? $v['num'] : 0;
        			$returnData[$key]['总计'] += $v['num'] ? $v['num'] : 0;
        		}
        	}
        	$all += $returnData[$key]['总计'];
        }
        $arr = [];
        $arr['staff_name'] = '总计';
        $arr['总计'] = $all;
        foreach ($column as $key => $value) {
        	$arr[$value] = '';
        	foreach ($returnData as $k => $v) {
        		$arr[$value] += $v[$value];
        	}
        }
        // die;
        array_unshift($returnData, $arr);
        $return['sql1'] = $sql1;
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channel)+1;
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = array('渠道名称', '毛客资', '有效客资', '无效客资', '待定客资', '预约数量', '入店量', '成交量', '有效率', '无效率', '待定率', '毛客资入店率', '有效客资入店率','入店成交率','毛客资成交率','有效客资成交率','花费', '毛客资成本', '有效客资成本','入店成本', '成交成本','成交均价','营业额','已收金额', 'ROI(已收:花费)');
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);
            $file = $shop[0]['shop_name'].'-'.$ff.'.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            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');
        //客资无效原因
        $allReason = controller('crm/Customer','lib')->getUnValidReason();
        $unvalidReasons = array_column($allReason,'reason');

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $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('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 getUnvalidReason($param){
    	$where = $param['where'];
        $sql = $param['sql'];
        $unvalid_reason = $param['unvalid_reason'];

        $column = db('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();
        // echo db()->getLastSql();die;
        $allProvince = array_column($column,'unvalid_reason');
        return $allProvince;
    }
}