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

class Ds_region_ts extends Report {

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

    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();

        // 时间区域
        if (!$data['start']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        if (!$data['end']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        // 省份
        if (!$data['province_id']) {
            $return = ['code' => 200, 'msg' => '请选择省份', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $start = date('Y-m-d', strtotime(trim($data['start'])));
        $end = date('Y-m-d 23:59:59', strtotime(trim($data['end'])));

        $id = db('s_report_form')->where('code', $this->getCode())->value('id');
        $det = db('s_report_detail')->where('form_id',$id)->field('shop_code,brandclass_id')->find();
        if(empty($det['brandclass_id'])){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        if($det['brandclass_id'] != 8){
            $where['consultation_type_id'] = HS_TYPE;
        }
        $where['add_shop_code'] = $data['shop_code'];
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
        }
        //获取省份下的城市
        $param = array(
            'pid' => $data['province_id'],
            'type' => 2,
            'shop_code' => $data['shop_code'],
        );
        $citys = controller('crm/Customer', 'lib')->address($param);
        $cityIds = array_column($citys,'id');
        // 来源渠道
        $channels = db('s_channel')->where('shop_code', $data['shop_code'])->order('order_sort')->select();
        $channelIds = array_column($channels,'channel_name');
        //表头 开始
        $returnData[0][0] = $data['province'];
        foreach ($citys as $k => $v) {
            $returnData[0][$k + 1] = $v['name'];
        }
        $returnData[0][count($citys) + 1] = '总计';
        //表头 结束
        $valid = db('c_customerinfo')
            ->where($where)
            ->where('is_valid', 1)
            ->where('city_id', 'in',$cityIds)
            ->where('customer_channel', 'in',$channelIds)
            ->where('yx_day', 'between time', [$start, $end])
            ->group('city_id,customer_channel_id')
            ->field('count(*) num,city_id,customer_channel_id')
            ->select();
        $va = [];
        foreach($valid as $k=>$v){
            $va[$v['city_id'].'_'.$v['customer_channel_id']] = $v['num'];
        }
        $channelTotal = [];
        $total  = 0;
        foreach ($channels as $key => $value) {
            $arr= [];
            $arr[] = $value['channel_name'];
            $cityTotal= 0;
            foreach($citys as $k=>$v){
                $num = $va[$v['id'].'_'.$value['id']] ? $va[$v['id'].'_'.$value['id']] : '';
                array_push($arr,$num);
                $cityTotal += intval($num);
                $channelTotal[$v['id']] += intval($num);
            }
            $total += intval($cityTotal);
            array_push($arr,$cityTotal);
            array_push($last,$channelTotal);
            array_push($returnData,$arr);
        }
        $channelTotal = array_values($channelTotal);
        array_push($channelTotal,$total);
        array_unshift($channelTotal,'总计');
        array_push($returnData,$channelTotal);

        // 导出
        if ($data['need'] == 1) {
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$data['shop_code']]);
            $file = $shop[0]['shop_name'].'-'.$ff.'.xlsx';
            $title = $returnData[0];
            unset($returnData[0]);
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json(array('code' => 1, 'data' => $returnData, 'count' => count($returnData[0])));
        }
    }

    public function show(){
        $code = $this->getCode();
        $did = strtolower(input('param.did'));
        $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();
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('shop', $shop);

        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $title = db('s_report_form')->where('code', $code)->value('report_name');
        $this->assign('title', $shop[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}