<?php
/**
 * 报表实现类 小阿福 爱婴上门及订单汇总
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: wangyining 2020-06-08 $
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;
use PHPExcel_IOFactory;
use Excel5;
use PHPExcel;
class Xaf_sm_order_data extends Report {

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

    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();
        $sql = [];
        $start = date('Y-m-d 00:00:00', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $det = db('crm_s_report_form')->alias('f')->join('crm_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,report_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['customer_type'] = 1;
        $where['add_shop_code'] = $shop_code;
        // $where['dj_day'] = ['between time',[$start, $end]];

        $startDay = date('Y-m-d', strtotime($data['start']));
        $endDay = date('Y-m-d', strtotime($data['end']));
        $where['pc.pc_time'] = ['between',[$start, $end]];

        if($data['consultation_type_id']){
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }

        if($data['channel_id']){
            $where['customer_channel_id'] = $data['channel_id'];
        }

        // 地域id，拼接where条件
        /*
        if ($data['province']) {
            $where['province_id'] = $data['province'];
        }

        if ($data['city']) {
            $where['city_id'] = (int)$data['city'];
        }
        */

        //所有登记人
        
        $staff =  db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid','left')
            ->where($where)
            ->group('c.dj_staff')
            ->column('c.dj_staff');

        //邀约量
        $yy_num = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid','left')
            ->where($where)
            ->where('pc.is_delete',2)
            ->where('pc.pc_shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->group('dj_staff')
            ->column('count(c.id) as num', 'dj_staff');

        //上门量
        $sm_num = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid','left')
            ->where($where)
            ->where('pc.is_delete',2)
            ->where('pc.status','in',[2,3])
            ->where('pc.pc_shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->group('dj_staff')
            ->column('count(c.id) as num', 'dj_staff');
        $orderWhere = $where;
        unset($orderWhere['pc.pc_time']);
        $orderWhere['erp_order.targetdate']= ['between',[date('Ymd',strtotime($start)),date('Ymd',strtotime($end))]];
        //三宝 单量
        $sb_order_num = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid')
            ->join('c_customerorder erp_order','pc.id=erp_order.crm_visit_id')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where($orderWhere)
            ->where(['pc.is_delete'=>2,'c.consultation_type'=>['like','%三宝%']])
            ->group('dj_staff')
            ->column('count(c.id) as num', 'dj_staff');
        $sql['sb_order_num'] = db()->getLastSql();
        //三宝 成交总额
        $sb_order_total_money = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid')
            ->join('c_customerorder erp_order','pc.id=erp_order.crm_visit_id')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where($orderWhere)
            ->where(['pc.is_delete'=>2,'c.consultation_type'=>['like','%三宝%']])
            ->group('dj_staff')
            ->column('sum(erp_order.total_money) as num', 'dj_staff');
        $sql['sb_order_total_money'] = db()->getLastSql();
        //三宝 订单实收总额
        $sb_order_payment_money = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid')
            ->join('c_customerorder erp_order','pc.id=erp_order.crm_visit_id')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where($orderWhere)
            ->where(['pc.is_delete'=>2,'c.consultation_type'=>['like','%三宝%']])
            ->group('dj_staff')
            ->column('sum(erp_order.payment_money) as num', 'dj_staff');
        $sql['sb_order_payment_money'] = db()->getLastSql();
        //三宝 订单现金实收总额
        $sb_order_payment_money_xj = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid')
            ->join('c_customerorder erp_order','pc.id=erp_order.crm_visit_id')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->join('c_paymentcontent pay','pay.orderId = photo.orderId and pay.currentfc = 1')
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where($orderWhere)
            ->where(['pc.is_delete'=>2,'c.consultation_type'=>['like','%三宝%']])
            ->where('pay.payclass',0)//VIP卡充值
            ->where('pay.isshishou','实收')//只取实收
            ->group('dj_staff')
            ->column('sum(erp_order.payment_money) as num', 'dj_staff');
        $sql['sb_order_payment_money_xj'] = db()->getLastSql();

        //摄影 单量
        $sy_order_num = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid')
            ->join('c_customerorder erp_order','pc.id=erp_order.crm_visit_id')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where($orderWhere)
            ->where(['pc.is_delete'=>2,'c.consultation_type'=>['not like','%三宝%']])
            ->group('dj_staff')
            ->column('count(c.id) as num', 'dj_staff');
        $sql['sy_order_num'] = db()->getLastSql();

        //摄影 成交总额
        $sy_order_total_money = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid')
            ->join('c_customerorder erp_order','pc.id=erp_order.crm_visit_id')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where($orderWhere)
            ->where(['pc.is_delete'=>2,'c.consultation_type'=>['not like','%三宝%']])
            ->group('dj_staff')
            ->column('sum(erp_order.total_money) as num', 'dj_staff');
        $sql['sy_order_total_money'] = db()->getLastSql();

        //摄影 订单实收总额
        $sy_order_payment_money = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid')
            ->join('c_customerorder erp_order','pc.id=erp_order.crm_visit_id')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where($orderWhere)
            ->where(['pc.is_delete'=>2,'c.consultation_type'=>['not like','%三宝%']])
            ->group('dj_staff')
            ->column('sum(erp_order.payment_money) as num', 'dj_staff');
        $sql['sy_order_payment_money'] = db()->getLastSql();
        //摄影 订单现金实收总额
        $sy_order_payment_money_xj = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_l_pc_log pc','c.id=pc.cid')
            ->join('c_customerorder erp_order','pc.id=erp_order.crm_visit_id')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->join('c_paymentcontent pay','pay.orderId = photo.orderId and pay.currentfc = 1')
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where($orderWhere)
            ->where(['pc.is_delete'=>2,'c.consultation_type'=>['not like','%三宝%']])
            ->where('pay.payclass',0)//VIP卡充值
            ->where('pay.isshishou','实收')//只取实收
            ->group('dj_staff')
            ->column('sum(erp_order.payment_money) as num', 'dj_staff');
        $sql['sy_order_payment_money_xj'] = db()->getLastSql();

        //储值单量
        $cz_order_num = db('crm_c_customerinfo')
            ->alias('c')
            ->join('c_customerorder erp_order','c.customer_number = erp_order.crm_customer_number')
            //->join('c_paymentcontent pay','erp_order.orderId = pay.orderId','left')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->join('c_paymentcontent pay','pay.orderId = photo.orderId and pay.currentfc = 1')
            ->where($orderWhere)
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where('pay.payclass',3)//VIP卡充值
            ->group('dj_staff')
            ->column('count(distinct erp_order.orderId) as num', 'dj_staff');
        $sql['cz_order_num'] = db()->getLastSql();


        //储值总额
        $cz_order_money = db('crm_c_customerinfo')
            ->alias('c')
            ->join('c_customerorder erp_order','c.customer_number = erp_order.crm_customer_number')
            ->join('c_customerphoto photo','photo.orderId = erp_order.orderId and photo.currentfc = 1')
            ->join('c_paymentcontent pay','pay.orderId = photo.orderId and pay.currentfc = 1')
            ->where($orderWhere)
            ->where('photo.shop_code','in',['xaf002','xaf021','xaf022','xaf023'])//爱婴
            ->where('pay.payclass',3)//VIP卡充值
            ->group('dj_staff')
            ->column('sum(pay.payment_money) as num', 'dj_staff');
        $sql['cz_order_money'] = db()->getLastSql();



        $returnData = [];
        $sum = [];
        $sum_yy_num = 0;
        $sum_sm_num = 0;
        $sum_sb_order_num = 0;
        $sum_sb_order_total_money = 0;
        $sum_sb_order_payment_money = 0;
        $sum_sb_order_payment_money_xj = 0;
        $sum_sy_order_num = 0;
        $sum_sy_order_total_money = 0;
        $sum_sy_order_payment_money = 0;
        $sum_sy_order_payment_money_xj = 0;
        $sum_cz_order_num = 0;
        $sum_cz_order_money = 0;
        foreach($staff as $k => $v){

            $returnData[$k]['dj_staff'] = $v;
            $returnData[$k]['yy_num'] = $yy_num[$v] ? $yy_num[$v] : 0;
            $returnData[$k]['sm_num'] = $sm_num[$v] ? $sm_num[$v] : 0;
            $returnData[$k]['sm_lv']  = (sprintf('%.2f', $returnData[$k]['sm_num'] / $returnData[$k]['yy_num']) * 100).'%';
            //三宝
            $returnData[$k]['sb_order_num'] = $sb_order_num[$v] ? $sb_order_num[$v] : 0;
            $returnData[$k]['sb_order_total_money'] = $sb_order_total_money[$v] ? $sb_order_total_money[$v] : 0;
            $returnData[$k]['sb_order_payment_money'] = $sb_order_payment_money[$v] ? $sb_order_payment_money[$v] : 0;
            $returnData[$k]['sb_order_payment_money_xj'] = $sb_order_payment_money_xj[$v] ? $sb_order_payment_money_xj[$v] : 0;
            $returnData[$k]['sb_order_avg'] = sprintf('%.2f',$returnData[$k]['sb_order_total_money'] / $returnData[$k]['sb_order_num']);

            //摄影
            $returnData[$k]['sy_order_num'] = $sy_order_num[$v] ? $sy_order_num[$v] : 0;
            $returnData[$k]['sy_order_total_money'] = $sy_order_total_money[$v] ? $sy_order_total_money[$v] : 0;
            $returnData[$k]['sy_order_payment_money'] = $sy_order_payment_money[$v] ? $sy_order_payment_money[$v] : 0;
            $returnData[$k]['sy_order_payment_money_xj'] = $sy_order_payment_money_xj[$v] ? $sy_order_payment_money_xj[$v] : 0;
            $returnData[$k]['sy_order_avg'] = sprintf('%.2f',$returnData[$k]['sy_order_total_money'] / $returnData[$k]['sy_order_num']);

            //储值单量
            $returnData[$k]['cz_order_num'] = $cz_order_num[$v] ? $cz_order_num[$v] : 0;
            //储值总额
            $returnData[$k]['cz_order_money'] = $cz_order_money[$v] ? $cz_order_money[$v] : 0;


            $sum_yy_num += $returnData[$k]['yy_num'];
            $sum_sm_num += $returnData[$k]['sm_num'];

            $sum_sb_order_num += $returnData[$k]['sb_order_num'];
            $sum_sb_order_total_money += $returnData[$k]['sb_order_total_money'];
            $sum_sb_order_payment_money += $returnData[$k]['sb_order_payment_money'];
            $sum_sb_order_payment_money_xj += $returnData[$k]['sb_order_payment_money_xj'];

            $sum_sy_order_num += $returnData[$k]['sy_order_num'];
            $sum_sy_order_total_money += $returnData[$k]['sy_order_total_money'];
            $sum_sy_order_payment_money += $returnData[$k]['sy_order_payment_money'];
            $sum_sy_order_payment_money_xj += $returnData[$k]['sy_order_payment_money_xj'];

            $sum_cz_order_num += $returnData[$k]['cz_order_num'];
            $sum_cz_order_money += $returnData[$k]['cz_order_money'];
        }

        $sum['dj_staff'] = '合计：';
        $sum['yy_num'] = $sum_yy_num;
        $sum['sm_num'] = $sum_sm_num;
        $sum['sm_lv'] = (sprintf('%.2f', $sum_sm_num / $sum_yy_num) * 100).'%';

        $sum['sb_order_num'] = $sum_sb_order_num;
        $sum['sb_order_total_money'] = $sum_sb_order_total_money;
        $sum['sb_order_payment_money'] = $sum_sb_order_payment_money;
        $sum['sb_order_payment_money_xj'] = $sum_sb_order_payment_money_xj;
        $sum['sb_order_avg'] = sprintf('%.2f',$sum_sb_order_total_money / $sum_sb_order_num);

        $sum['sy_order_num'] = $sum_sy_order_num;
        $sum['sy_order_total_money'] = $sum_sy_order_total_money;
        $sum['sy_order_payment_money'] = $sum_sy_order_payment_money;
        $sum['sy_order_payment_money_xj'] = $sum_sy_order_payment_money_xj;
        $sum['sy_order_avg'] = sprintf('%.2f',$sum_sy_order_total_money / $sum_sy_order_num);

        $sum['cz_order_num'] = $sum_cz_order_num;
        $sum['cz_order_money'] = $sum_cz_order_money;

        array_push($returnData,$sum);
        //print_r($returnData);die;

        //导出
        if($data['need'] == 1){
            $this->export($returnData,$det['report_name']);
        }

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        $return['sql'] = $sql;

        return json($return);

    }

    //导出
    public function export($data,$title){
        set_time_limit(0);
        $PHPExcel = new PHPExcel();
        $PHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Document")
            ->setSubject("Office 2007 XLSX Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
        if (!\PHPExcel_Settings::setCacheStorageMethod($cacheMethod)) {
            die($cacheMethod . " 缓存方法不可用" . EOL);
        }


        //合并单元格  标题
        $PHPExcel->getActiveSheet()->mergeCells('A1:N1');      //合并
        $PHPExcel->getActiveSheet()->setCellValue('A1',$title);
        $PHPExcel->setActiveSheetIndex(0)->getstyle('A1')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);

        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle('ksEveryMonth'); //给当前活动sheet设置名称

        $PHPExcel->getActiveSheet()->mergeCells('A2:A3');
        $PHPExcel->getActiveSheet()->setCellValue('A2','客资获取人');
        $PHPExcel->setActiveSheetIndex(0)->getstyle('A2')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);

        //合并邀约及上门
        $PHPExcel->getActiveSheet()->mergeCells('B2:D2');
        $PHPExcel->getActiveSheet()->setCellValue('B2','邀约及上门');
        $PHPExcel->setActiveSheetIndex(0)->getstyle('B2')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);

        //合并三宝成交
        $PHPExcel->getActiveSheet()->mergeCells('E2:H2');
        $PHPExcel->getActiveSheet()->setCellValue('E2','三宝成交');
        $PHPExcel->setActiveSheetIndex(0)->getstyle('E2')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);

        //合并摄影成交
        $PHPExcel->getActiveSheet()->mergeCells('I2:L2');
        $PHPExcel->getActiveSheet()->setCellValue('I2','摄影成交');
        $PHPExcel->setActiveSheetIndex(0)->getstyle('I2')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);

        //合并储值
        $PHPExcel->getActiveSheet()->mergeCells('M2:N2');
        $PHPExcel->getActiveSheet()->setCellValue('M2','储值');
        $PHPExcel->setActiveSheetIndex(0)->getstyle('M2')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);

        $secondTitle = ['邀约量','上门量','上门率','单量','成交总额','订单实收总额','成交均值','单量','成交总额','订单实收总额','成交均值','储值单量','储值总额'];

        $title2 = 3;
        for($i=0;$i<count($secondTitle);$i++){
            $range[$i+1] = controller('Customer','lib')->stringFromColumnIndex($i+1);
            //设置单元格宽度
            $PHPExcel->setActiveSheetIndex(0)->getColumnDimension($range[$i+1])->setWidth(18);
            $PHPSheet->setCellValue($range[$i+1].$title2, $secondTitle[$i]);
        }
        //print_r($data);die;
        if(count($data)>0){
            foreach($data as $k=>$v){
                $title2++;
                foreach(array_values($v) as $kk=>$vv){
                    $ranges[$kk] = controller('Customer','lib')->stringFromColumnIndex($kk);
                    $PHPSheet->setCellValue($ranges[$kk].$title2, $vv);
                    //$PHPSheet->setCellValue("{$range[$kk]}{$title2}",$vv);
                }
            }
        }


        //边框
        $PHPExcel->getActiveSheet()->getStyle('A1:N'.$title2)->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

        //设置行高
        //$PHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(30);

        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');
        //header("Content-type:text/html;charset=utf-8");
        header('Content-type: application/vnd.ms-excel');//告诉浏览器输出07Excel文件
        header('Content-Disposition: attachment;filename='.$title. '.xlsx');//告诉浏览器输出浏览器名称
        header("Content-Description: File Transfer");
        header('Cache-Control: max-age=0');//禁止缓存
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        $PHPWriter->save("php://output");
        exit;
    }

    public function show(){
        /*
        $did = strtolower(input('param.did'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_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();*/
        $menu_code = strtolower(input('param.menu_code'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_s_report_detail d','d.form_id=f.id','left')->where('f.code',$menu_code)->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();
        $city = db('crm_s_shop_address')->where('shop_code',$info['shop_code'])->where('type',2)->select();

        //消费类型
        $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);

        //来源渠道
        $channel = controller("Customer", "lib")->getChannel($info['shop_code']);
        $this->assign("channel", $channel);

        $code = $this->getCode();
        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $title = db('crm_s_report_form')->where('code', $code)->value('report_name');
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('title', $shopInfo[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}