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

class Jsj_rep_dep_data extends Report {

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

    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'] || !$data['end']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $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'=>'报表配置有误');
        }
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $where['is_status'] = 1;
        $data['shop_code'] = $data['shop_code'] ? $data['shop_code'] : $shop_code;

        if($data['consultation_type_id']){
            $consultation_type_id = intval($data['consultation_type_id']);
        }
        $dep = controller("crm/Customer")->getDepartmentList(array('shop_code' =>$shop_code));
        foreach($dep as $k=>$v){
            if($k > 2){
                unset($dep[$k]);
            }
        }
        $sql = '';
        if($data['method'] == 'dj'){
            $method = 'dj_department_id';
            $code = 'add_shop_code';
            $sql .= "sum(dj_day between '$start' and '$end') as mkz,";
            $cus = db('c_customerinfo')
                ->where('add_shop_code',$data['shop_code'])
                ->where($where)
                ->where('dj_day','between',[$start,$end])
                ->column('dj_department_id','id');
        }else{
            $method = 'sales_department_id';
            $code = 'shop_code';
            $sql .= "sum(yx_day between '$start' and '$end') as mkz,";
            $cus = db('c_customerinfo')
                ->where('shop_code',$data['shop_code'])
                ->where($where)
                ->where('dj_day','between',[$start,$end])
                ->column('sales_department_id','id');
        }


        $temp = [];
        $temp1 = [];
        foreach($cus as $k=>$v){
            $temp[] = $k;
            $temp1[$v][] = $k;
        }
        $channelCost = db('c_customer_from')
                        ->where('cid','in',$temp)
                        ->column('c_channel_cost','cid');
        $cost = [];
        foreach($temp1 as $k=>$v){
            foreach($v as $kk=>$vv){
                $cost[$k] += floatval($channelCost[$vv]);
            }
        }

        if($data['consultation_type_id']){
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_valid in('1','4','5') and yx_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_intostore in ('2','3','5') and syjd_day between '$start' and '$end') as jd,";
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_intostore=5  and syjd_day between '$start' and '$end') as loss,";//流失
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_success=1 and order_day between '$start' and '$end') as newOrder";//订单
        }else{
            $sql .= "sum(is_valid in('1','4','5') and yx_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(is_intostore in ('2','3','5') and syjd_day between '$start' and '$end') as jd,";
            $sql .= "sum(is_intostore=5  and syjd_day between '$start' and '$end') as loss,";//流失
            $sql .= "sum(is_success=1 and order_day between '$start' and '$end') as newOrder";
        }
        // 录入客资量
        $info= db('c_customerinfo')
            ->where($where)
            ->where($code, $data['shop_code'])
            ->group($method)
            ->column($sql,$method);

        //营收
        $detail = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($where)
            ->where('c.'.$code, $data['shop_code'])
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group('c.'.$method)
            ->column('sum(d.order_fact) as fact','c.'.$method);
        //套系
        $whereTx['c.is_status'] = 1;

        $total = db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
            ->where($whereTx)
            ->where('c.'.$code, $data['shop_code'])
//            ->where('c.'.$method, 'in',$staffIds)
            ->where('o.order_valid', 2)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.'.$method)
            ->column('sum(o.order_amount) as total','c.'.$method);
        $returnData = [];
        $arr = [];
        $i = 1;
        $arr['id'] = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        foreach ($dep as $key => $value) {
            $returnData[$key]['id'] = $i;
            $returnData[$key]['department'] = $value['department_name'];
            $returnData[$key]['invCustomer'] = $info[$value['id']]['valid'];
            $returnData[$key]['intoNum'] = $info[$value['id']]['jd'];
            $returnData[$key]['loss'] = $info[$value['id']]['loss'];
            $returnData[$key]['lossRate'] = (number_format($returnData[$key]['loss'] / $returnData[$key]['intoNum']*100, 2)) . '%';
            $returnData[$key]['orderNum'] = $info[$value['id']]['newOrder'];
            // 成交率（ 有效新单 / 实际进店 ）
            $returnData[$key]['orderRate'] = (number_format($returnData[$key]['orderNum'] / $returnData[$key]['intoNum']*100, 2)) . '%';
            $returnData[$key]['cost'] = sprintf('%.2f',$cost[$value['id']]);
            // 有效客资成本
            $returnData[$key]['validCost'] = (number_format($cost[$value['id']] / $returnData[$key]['invCustomer'], 2));

            $returnData[$key]['orderAmount'] = sprintf('%.2f',$total[$value['id']]);
            $returnData[$key]['factMoney'] = sprintf('%.2f',$detail[$value['id']]);
            $returnData[$key]['orderAmountAvg'] = sprintf('%.2f',$detail[$value['id']]/$info[$value['id']]['newOrder']);
            $returnData[$key]['roi'] = number_format($cost[$value['id']] / $detail[$value['id']], 2).':1';

            $arr['department'] = '总计';
            $arr['invCustomer'] += $info[$value['id']]['valid'];
            $arr['intoNum'] += $info[$value['id']]['jd'];
            $arr['loss'] += $info[$value['id']]['loss'];
            $arr['lossRate'] = '';
            $arr['orderNum'] += $info[$value['id']]['newOrder'];
            $arr['orderRate'] = '';
            $arr['cost'] += floatval($cost[$value['id']]);
            $arr['validCost'] = '';
            $arr['orderAmount'] += $total[$value['id']];
            $arr['factMoney'] += $detail[$value['id']];
            $arr['orderAmountAvg'] = '';
            $arr['roi'] = '';
            $i++;
        }
        $arr['lossRate'] = sprintf('%.2f',$arr['loss']/$arr['intoNum']*100).'%';
        $arr['orderRate'] = sprintf('%.2f',$arr['orderNum']/$arr['intoNum']*100).'%';
        $arr['validCost'] = sprintf('%.2f',$arr['cost']/$arr['invCustomer']);
        $arr['orderAmountAvg'] = sprintf('%.2f',$arr['factMoney']/$arr['orderNum']);
        $arr['roi'] = sprintf('%.2f',$arr['factMoney']/$arr['cost']).':1';
        array_push($returnData,$arr);

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

        //来源渠道
        $channel = db('s_channel')->where('shop_code','in',$info['shop_code'])->order('order_sort')->select();
        $this->assign("channel", $channel);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}
