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

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

    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();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'];

        if (!$shop_code) {
            $return = ['code' => 100, 'msg' => '请选择部门（店）' . $shop_code];
            return json($return);
        }

        //通过页面获取的shop_code获取归属店的shop_code
       /* $shopCodes = sx_call('5a005e0038270', ['belong_shop_code' => $shop_code]);
        if ($shopCodes['code'] == 200) {
            $shopCodes = array_unique(array_column($shopCodes['data'], 'shop_code'));
        } else {
            $shopCodes = $shop_code;
        }*/
        $timeArea = explode(' - ', $data['timeArea']);
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        // 时间区域
        if ($data['timeArea']) {
            $start = date('Y-m-d', strtotime($timeArea[0]));
            $end = date('Y-m-d 23:59:59', strtotime('+1 day', strtotime($timeArea[1])));
        } else {
            $start = 0;
            $end = date('Y-m-d H:i:s', time());
        }
        // 省份
        if ($data['province_id']) {
            $where['province_id'] = $data['province_id'];
        }
        // 城市
        if ($data['city_id']) {
            $where['city_id'] = $data['city_id'];
        }
        // 渠道
        if ($data['channel_id']) {
            $where['customer_channel_id'] = $data['channel_id'];
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        //关键词
        $keywords = db('c_customerinfo')
            ->where($where)
            ->where('customer_key',  'not null')
            ->where('customer_key', '<>', '')
            ->where('add_shop_code', $shop_code)
            ->where('dj_day', 'between time', [$start, $end])
            ->field('count(*) AS num,customer_key')
            ->group('customer_key')
            ->order('num desc')
            ->limit($limit)
            ->page($page)
            ->select();
        $keyword = array_column($keywords,'customer_key');
            if (!$data['li'] || $data['li'] == 1) {//获取排行
                $cont = '获取排行';
                $tel = db('c_customerinfo')
                    ->where($where)
                    ->where('is_first_tel|is_first_wechat|is_first_qq', '1')
                    ->where('customer_key', 'in',$keyword)
                    ->where('add_shop_code',$shop_code)
                    ->where('create_time', 'between time', [$start, $end])
                    ->group('customer_key')
                    ->order('num desc')
                    ->column('count(*) AS num','customer_key');
            } elseif ($data['li'] == 2) {//邀约
                $cont = '邀约排行';
                $tel = db('c_customerinfo')
                    ->where($where)
                    ->where('customer_key', 'in',$keyword)
                    ->where('add_shop_code',$shop_code)
                    ->where('yjd_day', 'between time', [$start, $end])
                    ->group('customer_key')
                    ->order('num desc')
                    ->column('count(*) AS num','customer_key');

            } elseif ($data['li'] == 3) {//订单
                $cont = '订单排行';
                $tel = db('c_customerinfo')
                    ->where($where)
                    ->where('is_success', 1)
                    ->where('customer_key', 'in',$keyword)
                    ->where('add_shop_code',$shop_code)
                    ->where('order_day', 'between time', [$start, $end])
                    ->group('customer_key')
                    ->order('num desc')
                    ->column('count(*) AS num','customer_key');
            } elseif ($data['li'] == 4) {//订单总价
                $cont = '订单总价排行';
                $tel = db('c_customerinfo')
                    ->where($where)
                    ->where('customer_key', 'in',$keyword)
                    ->where('add_shop_code',$shop_code)
                    ->where('order_start_time', 'between time', [$start, $end])
                    ->group('customer_key')
                    ->order('num desc')
                    ->column('sum(totalpay_money) as num','customer_key');
            } elseif ($data['li'] == 5) {//单价
                $cont = '单价排行';
                $tel = db('c_customerinfo')
                    ->where($where)
                    ->where('customer_key', 'in',$keyword)
                    ->where('add_shop_code',$shop_code)
                    ->where('order_day', 'between time', [$start, $end])
                    ->group('customer_key')
                    ->order('num desc')
                    ->column('sum(fact_money) as num','customer_key');
            } elseif ($data['li'] == 6) {//总体
                $cont = '总体排行';
                $tel = db('c_customerinfo')
                    ->where($where)
                    ->where('customer_key', 'in',$keyword)
                    ->where('add_shop_code',$shop_code)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->group('customer_key')
                    ->order('num desc')
                    ->column('count(*) as num','customer_key');
            }
        $res = [];
        $i = 0;
        foreach ($tel as $k => $v) {
            $res[$i]['customer_key'] = $k;
            $res[$i]['tel'] = intval($v);
            $i++;
        }
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($res);
        $return['data'] = $res;
        // 导出
        if ($data['need'] == 1) {
            $title = array('关键字', '数量/金额');
            $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';
            controller("crm/Customer", "lib")->export($title, $keywords, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 200, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }

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

}