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

    private $level=1;
    private $type=3;
    private $code='code1528805903';

    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['province_id']) {
            $return = ['code' => 300, 'msg' => '请选择省份', 'count' => 0, 'data' => '',];
            return json($return);
        }
        // 时间区域
        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);
        }
        $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'];
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['shop_code'] = $shop_code;
        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        if ($det['brandclass_id'] != 2) {
            $where['customer_type'] = HS_TYPE;
        }
        $consultation_type_id = $data['consultation_type_id'] ? intval($data['consultation_type_id']) : HS_TYPE;
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
            $whereC['province_id'] = (int)$data['province_id'];
        }
        //获取城市
        $citys = controller('crm/Customer', 'lib')->address(['type' => 2, 'pid' => $data['province_id'], 'shop_code' => $shop_code]);
        $cityIds = array_column($citys,'id');
        $sql = '';
        $sql .= "sum(dj_day between '$start' and '$end') as dj,";//毛客资
        $sql .= "sum(jr_day between '$start' and '$end') as mkz,";//轮位客资
        $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_valid=1 and yx_day between '$start' and '$end') as valid,";//有效

        $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_intostore in (2,3) and syjd_day between '$start' and '$end') as jd,";//进店
        $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_success=1 and order_day between '$start' and '$end') as xd";
        //新单
        $info = db('c_customerinfo')
            ->where($where)
            ->where('city_id', 'in',$cityIds)
            ->group('city_id')
            ->column($sql,'city_id');
        $whereTx['c.is_status'] = 1;
        $whereTx['c.c_from'] = 1;
        $whereTx['c.shop_code'] = $shop_code;
        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        if ($det['brandclass_id'] != 2) {
            $whereTx['c.customer_type'] = HS_TYPE;
        }
        //套系总额
        $amount = db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
            ->where($whereTx)
            ->where('c.consultation_type_id',$consultation_type_id)
            ->where('o.order_valid', 2)
            ->where('o.create_time', 'between time', [$start, $end])
            ->group('c.city_id')
            ->column('sum(o.order_fact) as total','c.city_id');
        //营收
        $detail = db('c_customerinfo')->alias('c')->join('c_order_detail d','c.order_number=d.order_sn')
            ->where($whereTx)
            ->where('c.city_id', 'in',$cityIds)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group('c.city_id')
            ->column('sum(d.order_fact) as fact','c.city_id');

        $returnData = [];
        $total = [];
        $total['name'] = '总计';
        foreach ($citys as $k => $v) {
            $arr = [];
            $arr['name'] = $v['name'];
            //毛客资
            $arr['dj'] = $info[$v['id']]['dj'];
            //轮位客资
            $arr['jr_num'] = $info[$v['id']]['mkz'];
            //有效客资
            $arr['valid'] = $info[$v['id']]['valid'];
            //邀约客资
            $arr['jd'] = $info[$v['id']]['jd'];
            //新单
            $arr['order'] = $info[$v['id']]['xd'];
            //套系 总额
            $arr['orderAmount'] = $amount[$v['id']];
            //营收
            $arr['factMoney'] = sprintf('%.2f',$detail[$v['id']]);
            //邀约转化率
            $arr['intoRate'] = number_format($arr['jd'] / $arr['valid'] * 100, 2) . '%';
            //成交率
            $arr['succRate'] = number_format($arr['order'] / $arr['jd'] * 100, 2) . '%';
            //新单/有效
            $arr['orderRate'] = number_format($arr['order'] / $arr['valid'] * 100, 2) . '%';
            //有效率
            $arr['validRate'] = number_format($arr['valid'] / $arr['jr_num'] * 100, 2) . '%';
            array_push($returnData, $arr);
            $total['dj'] += $arr['dj'];
            $total['jr_num'] += $arr['jr_num'];
            $total['valid'] += $arr['valid'];
            $total['jd'] += $arr['jd'];
            $total['order'] += $arr['order'];
            $total['orderAmount'] += $arr['orderAmount'];
            $total['factMoney'] += floatval($arr['factMoney']);
        }
        //有省无市
        $noCity = db('c_customerinfo')
            ->where($where)
            ->where('city_id is null or city_id = 0')
            ->column($sql);
        foreach($noCity as $k=>$v){
            $noCity['dj'] = $v['dj'];
            $noCity['mkz'] = $v['mkz'];
            $noCity['jr_num'] = $v['jr_num'];
            $noCity['valid'] = $v['valid'];
            $noCity['jd'] = $v['jd'];
            $noCity['xd'] = $v['xd'];
        }

        $whereTx['c.is_status'] = 1;
        $whereTx['c.c_from'] = 1;
        $whereTx['c.shop_code'] = $shop_code;
        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        if ($det['brandclass_id'] != 2) {
            $whereTx['c.customer_type'] = HS_TYPE;
        }
        //套系总额
        $noAmount = db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
            ->where($whereTx)
            ->where('c.consultation_type_id',$consultation_type_id)
            ->where('o.order_valid', 2)
            ->where('o.create_time', 'between time', [$start, $end])
            ->where('c.city_id is null or c.city_id = 0')
            ->value('sum(o.order_fact) as total');
        //营收
        $noFact = db('c_customerinfo')->alias('c')->join('c_order_detail d','c.order_number=d.order_sn')
            ->where($whereTx)
            ->where('c.city_id is null or c.city_id = 0')
            ->where('d.pay_time', 'between time', [$start, $end])
            ->value('sum(d.order_fact) as fact');
        $null = [];
        $null['name'] = '其它';
        //毛客资
        $null['dj'] = $noCity['dj'];
        //轮位客资
        $null['jr_num'] = $noCity['mkz'];
        //有效客资
        $null['valid'] = $noCity['valid'];
        //邀约客资
        $null['jd'] = $noCity['jd'];
        //新单
        $null['order'] = $noCity['xd'];
        //营收
        $null['orderAmount'] = sprintf('%.2f',$noAmount);
        //营收
        $null['factMoney'] = sprintf('%.2f',$noFact);
        //邀约转化率
        $null['intoRate'] = number_format($null['jd'] / $null['valid'] * 100, 2) . '%';
        //成交率
        $null['succRate'] = number_format($null['order'] / $null['jd'] * 100, 2) . '%';
        //新单/有效
        $null['orderRate'] = number_format($null['order'] / $null['valid'] * 100, 2) . '%';
        //有效率
        $null['validRate'] = number_format($null['valid'] / $null['jr_num'] * 100, 2) . '%';
        array_push($returnData,$null);

        $total['dj'] = $total['dj']+$noCity['dj'];
        $total['jr_num'] = $total['jr_num']+$null['jr_num'];
        $total['valid'] = $total['valid']+$null['valid'];
        $total['jd'] = $total['jd']+$null['jd'];
        $total['order'] = $total['order']+$null['order'];
        $total['orderAmount'] = floatval($total['orderAmount']+$null['orderAmount']);
        $total['factMoney'] = floatval($total['factMoney']+$null['factMoney']);
        $total['intoRate'] = number_format($total['jd'] / $total['valid'] * 100, 2) . '%';
        $total['succRate'] = number_format($total['order'] / $total['jd'] * 100, 2) . '%';
        $total['orderRate'] = number_format($total['order'] / $total['valid'] * 100, 2) . '%';
        $total['validRate'] = number_format($total['valid'] / $total['jr_num'] * 100, 2) . '%';
        array_push($returnData,$total);
        // 导出
        if ($data['need'] == 1) {
            $title = ['地域', '毛客资','轮位客资', '有效', '邀约', '新单','套系总额', '营收', '邀约转化率', '成交率', '新单/有效', '有效率'];
            $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['code'] = 0;
            $return['msg'] = '';
            $return['count'] = count($returnData);
            $return['data'] = $returnData;
            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);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['shop_code'];
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        $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);
        //查询事业部下的电商店
//        $shop = controller('crm/Customer','lib')->shop(['belong_shop_code'=>session('shop_code'),'is_marketing'=>1]);
//        $this->assign('shop', $shop);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}