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

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

    public function getLevel(){
        return $this->level;

    }
    public function getType(){
        return $this->type;
    }
    public function getCode(){
        return $this->code;
    }
      //is_status = 1,c_from=1,shop_code,时间 dj_day
    public function data(){
        set_time_limit(0);

        $data = input();

        $info = db('crm_s_report_form')->where('code', $data['code'])->field('code,report_name,report_class_name')->find();
        if (!$info || empty($data['code'])) {
            $this->error('没有此报表。');
        }
        $shop_code = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        
        $date = explode(" - ", $data['start']);
        $start = $date[0] ? $date[0]." 00:00:00" : date("Y-m-d 00:00:00",strtotime("-7 day"));
        $end = $date[1] ? $date[1]." 23:59:59" : date('Y-m-d 23:59:59');

        $d1 = strtotime($start);
        $d2 = strtotime($end);
        $Days = round(($d2-$d1)/3600/24);
        if ($Days > 31) {
            $return['code'] = 100;
            $return['msg'] = '日期范围请选择一个月31天内。';
            return json($return);
        }
        // 登记人
        if ($data['dj_staff']) {
            $where['c.dj_staff_id'] = ['in', $data['dj_staff']];
        }
        // 追踪人
        if ($data['sales_staff']) {
            $where['c.sales_staff_id'] = ['in', $data['sales_staff']];
        }
        // 品牌，crm系统设定的品牌和mc的brandclass不一样
        if ($data['b_id']) {
            $where['c.b_id'] = ['in', $data['b_id']];
        }
        //  城市
        if ($data['city']) {
            $where['c.city_id'] = ['in', $data['city']];
        }
        //  客资标记
        if ($data['sign']) {
            $where['c.sign_id'] = ['in', $data['sign']];
        }
        // 是否成交
        if ($data['is_success']==1) {// 已订单
            $where['c.is_success'] = ['in', '1,3'];
        }else if ($data['is_success']==2) {// 未定单
            $where['c.is_success'] = ['in', '2'];
        }
        // 消费类型
        if ($data['xflx']) {
            $where['c.consultation_type_id'] = ['in', $data['xflx']];
        }
        // 渠道
        if($data['channel']){
            $where['c.customer_channel'] = ["in",$data['channel']];
        }
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.shop_code'] = $shop_code;

        $returnData = db('crm_c_customerinfo')->alias("c")
            ->join("crm_s_channel cl","cl.id = c.customer_channel_id","left")
            ->join("crm_c_customer_from cf","cf.cid = c.id")
            ->where($where)
            ->where('c.dj_day','between',[$start,$end])
            ->field("c.dj_day,c.customer_channel,c.op_signinfo,c.customer_name,c.customer_tel,c.customer_wechat,c.city,c.consulation_shop,c.is_success,c.consultation_type,c.dj_staff,c.consultation_type,c.customer_cource,c.customer_intention,c.access_model,c.brandclass,c.order_number,c.last_trackday,c.shop_name,c.shop_code,cl.channel_info_name,cf.dj_group_name,cf.sales_group_name,c.add_shop_name,c.sales_staff,c.tel_visit_num")
            ->select();
        $sql1 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        $order = [];
        foreach ($returnData as $key => $value) {
            $returnData[$key]['dj_day'] = date('m-d',strtotime($value['dj_day']));
            $returnData[$key]['is_success'] = getIsSuccess($value['is_success']);
            if ($value['order_number']) {
                $order[] = $value['order_number'];
            }
        }
        $recTime .= microtime(true).'<br />';

        if (count($order)>0) {
            $customerorder = db('c_customerorder')->alias('o')
                ->join('c_paymentcontent p', 'p.orderId=o.orderId','left')
                ->where('o.orderId','in',$order)
                ->field('o.bargain_money,o.yixiaoshishou,p.paytype,p.payment_money as pay,o.orderId')->select();
                // ->column('o.bargain_money,o.yixiaoshishou,p.paytype,p.isshishou,p.payment_money as pay','o.orderId');
            $sql2 = db()->getLastSql();

            $recTime .= microtime(true).'<br />';
            foreach ($returnData as $key => $value) {
                $returnData[$key]['key'] = $key+1;
                foreach ($customerorder as $k => $v) {
                    if ($v['orderId']==$value['order_number']) {
                        $returnData[$key]['yx_tx'] = $v['bargain_money'];
                        $returnData[$key]['yx_qk'] = $v['bargain_money']-$v['yixiaoshishou'];
                        // 实收 金额 包含充值
                        if ($v['paytype']!='4') {
                            $returnData[$value['customer_channel']]['ssje'] += $v['pay'];
                        }
                        if ($v['paytype'] == '刷卡') {
                            $returnData[$key]['shuaka'] = $v['pay'];
                        }
                        if ($v['paytype'] == '现金') {
                            $returnData[$key]['xianjin'] = $v['pay'];
                        }
                        if ($v['paytype'] == '网络付款') {
                            $returnData[$key]['wl'] = $v['pay'];
                        }
                        if ($v['paytype'] == '免单') {
                            $returnData[$key]['md'] = $v['pay'];
                        }
                        if ($v['paytype'] == 'VIP卡') {
                            $returnData[$key]['vip'] = $v['pay'];
                        }
                        if ($v['paytype'] == '优惠券') {
                            $returnData[$key]['yhj'] = $v['pay'];
                        }
                    }
                }
            }
            $recTime .= microtime(true).'<br />';
        }

        $return['order'] = $order;
        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['recTime'] = $recTime;
        $return['code'] = 0;
        $return['msg'] = '';
        $return['data'] = $returnData;
        $return['count'] = count($returnData);
        return json($return);
    }

    public function show(){
        $menu_code = strtolower(input('param.menu_code'));
        $info = db('crm_s_report_form')->where('code', $menu_code)->field('code,report_name,report_class_name')->find();
        if (!$info) {
            $this->error('没有此报表。');
        }


        $shop_code = session('shop_code');
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);

        // $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$info['shop_code']]);
        // $this->assign('staff', $staff);

        //来源渠道
        $channel = getChannelJson($info['shop_code']);
        $this->assign("channel", json_encode($channel));
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);

        // crm省    列表
        $data['type']=1;
        $data['shop_code']= $info['shop_code'] ? $info['shop_code'] : session('shop_code');
        $province=controller("crm/Customer","lib")->address($data);
        $this->assign("province",$province);
        // 只有一个省 查这个省下的城市
        if (count($province)==1) {
            $data['type'] = 2;
            $data['pid']  = $province[0]['id'];
            $staCity = controller("crm/Customer", "lib")->address($data);
            $this->assign("staCity",$staCity);
        }
        //品牌
        $brandArr = db('crm_s_brandset')->select();
        $this->assign('brandArr',$brandArr);
        // 客资标记
        $sign = db('CrmSTracksign')->where('shop_code',$data['shop_code'])->where('is_delete',1)->select();
        $this->assign("sign",$sign);
        // var_dump($sign);die;
        $mc = new \app\common\lib\mcInterface();
        // 部门
        $departmentList = $mc->getDepartmentByShopcode($data['shop_code']);
        foreach ($departmentList as $key => $value) {
            if ($value['department_name']==session('department_name')) {
                $departmentList[$key]['selected']=1;
                $departmentId = $value['id'];
            }
        }
        $this->assign("departmentList",$departmentList);
        $staffParam['department_id'] = $departmentId;
        $staffParam['get_main'] = 1;
        // 登记人
        $djStaffList = $mc->getStaffByDepartment($staffParam);
        $this->assign("djStaffList",$djStaffList);
        // 追踪人
        $salesStaffList = $mc->getStaffByDepartment($staffParam);
        $this->assign("salesStaffList",$salesStaffList);

        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';

        $this->assign('title', $shop[0]['shop_name'].'-'.$info['report_name']);
        $this->assign('did', $info['id']);
        $this->assign('start', date('Y-m-01'));
        $this->assign('end', date('Y-m-d'));
        return $this->fetch($display);
    }

}