<?php
/**
 *网销员工数据统计
 * User: sx01
 * Date: 2018/11/8
 * Time: 10:58
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;
class Tk_wx_group_data extends Report {
    private $level=1;
    private $type=3;
    private $code='code1541640530';

    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'] = $shop_code;
        $where['c_from'] = 1;
        if($data['consultation_type_id']){
            $where['consultation_type_id'] = intval($data['consultation_type_id']);
            $whereTx['c.consultation_type_id'] = intval($data['consultation_type_id']);
        }
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
            $whereTx['c.province_id'] = (int)$data['province_id'];
        }
        if ($data['city_id']) {
            $where['city_id'] = (int)$data['city_id'];
            $whereTx['c.city_id'] = (int)$data['city_id'];
        }
        // 获取店下的小组
        $groupList = db('c_staff_group')->where('shop_code', $shop_code)->select();
        $returnTemp = [];
        foreach ($groupList as $k => $v) {
            // 组内所有人
            $staffs = db('c_staff_group')->alias('g')->join('c_staff_group_relation r','g.id=r.group_id')
                ->where('g.id',$v['id'])
                ->field('g.id,g.group_name,r.staff_id as sales_staff_id,r.staff_name as sales_staff')
                ->select();
            $staffIds = array_column($staffs,'sales_staff_id');
            $sql = '';
            $sql .= "sum(dj_day between '$start' and '$end') as mkz";
            // 录入客资量（分配）
            $info= db('c_customerinfo')
                ->where($where)
                ->where('shop_code', $data['shop_code'])
                ->where('sales_staff_id', 'in',$staffIds)
                ->group('sales_staff_id')
                ->column($sql,'sales_staff_id');
            // 总订单量
            $allOrder = db('c_customerinfo')->alias('c')
                ->join('c_customer_order o','o.customer_id=c.id','left')
                ->where('c.is_success', '<>', 2)
                ->where('c.order_start_time', 'between time', [$start, $end])
                ->where($whereTx)
                ->where('c.shop_code', $data['shop_code'])
                ->where('c.sales_staff_id', 'in',$staffIds)
                ->group('c.sales_staff_id')
                ->column('count(o.id) as oNum','c.sales_staff_id');
            // 续订转介绍订单量
            $xdOrder = db('c_customerinfo')->alias('c')
                ->join('c_customer_order o','o.customer_id=c.id','left')
                ->where('c.is_success', '<>', 2)
                ->where('c.order_start_time', 'between time', [$start, $end])
                ->where($whereTx)->where('c.customer_channel','in', '员工转介绍,老顾客转介绍,老顾客续订')
                ->where('c.shop_code', $data['shop_code'])
                ->where('c.sales_staff_id', 'in',$staffIds)
                ->group('c.sales_staff_id')
                ->column('count(o.id) as oNum','c.sales_staff_id');
            //实收
            $detail = db('c_customerinfo')->alias('c')
                ->join('c_customer_order o','o.customer_id=c.id','left')
                ->join('c_order_detail d','d.order_sn=o.order_sn','left')
                ->where($whereTx)
                ->where('c.shop_code', $data['shop_code'])
                ->where('c.sales_staff_id', 'in',$staffIds)
                ->where('d.pay_type',1)
                ->where('d.pay_time', 'between time', [$start, $end])
                ->group('c.sales_staff_id')
                ->column('sum(d.order_fact) as fact','c.sales_staff_id');
            //营收
            $total = db('c_customerinfo')->alias('c')
                ->join('c_customer_order o','o.customer_id=c.id','left')
                ->where($whereTx)
                ->where('c.shop_code', $data['shop_code'])
                ->where('c.sales_staff_id', 'in',$staffIds)
                ->where('c.order_start_time', 'between time', [$start, $end])
                ->group('c.sales_staff_id')
                ->column('sum(o.order_amount) as total','c.sales_staff_id');
            $grouData = [];
            foreach ($staffs as $key => $value) {
                $grouData[$key]['sort']  = '';
                $grouData[$key]['staff'] = $value['sales_staff'];
                $grouData[$key]['group'] = $value['group_name'];
                $grouData[$key]['mkz'] = $info[$value['sales_staff_id']]['mkz'];
                $grouData[$key]['order'] = $allOrder[$value['sales_staff_id']] - $xdOrder[$value['sales_staff_id']];
                $grouData[$key]['orderxd'] = $xdOrder[$value['sales_staff_id']];
                $grouData[$key]['fact'] = sprintf('%.2f',$detail[$value['sales_staff_id']]);
                $grouData[$key]['total'] = sprintf('%.2f',$total[$value['sales_staff_id']]);
                // 毛客资订单率（ 订单 / 毛客资 ）
                $grouData[$key]['orderRate'] = sprintf('%.2f',$allOrder[$value['sales_staff_id']]/$info[$value['sales_staff_id']]['mkz']*100) . '%';
                $grouData[$key]['avg'] = sprintf('%.2f',$total[$value['sales_staff_id']]/$allOrder[$value['sales_staff_id']]);
            }
            $sort_order = 'SORT_DESC';
            $grouData = my_sort($grouData, 'fact', $sort_order);
            foreach ($grouData as $key => $value) {
                $grouData[$key]['sort'] = $key+1;
            }
            $returnTemp[] = $grouData;
        }
        $returnData = [];
        foreach ($returnTemp as $key => $value) {
            foreach ($value as $k => $v) {
                $returnData[]=$v;
            }
        }
        foreach ($returnData as $key => $value) {
            $arr['sort']  = '';
            $arr['staff'] = '总计';
            $arr['mkz'] += $returnData[$key]['mkz'];
            $arr['order'] += $returnData[$key]['order'];
            $arr['orderxd']+=$returnData[$key]['orderxd'];
            $arr['fact'] += $returnData[$key]['fact'];
            $arr['total'] += $returnData[$key]['total'];
            $arr['orderRate'] = '';
            $arr['avg'] = '';
        }
        $arr['fact'] = sprintf('%.2f',$arr['fact']);
        $arr['total'] = sprintf('%.2f',$arr['total']);
        $arr['orderRate'] = sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%';
        $arr['avg'] = sprintf('%.2f',$arr['total']/($arr['order']+$arr['orderxd']));
        array_push($returnData,$arr);
        // var_dump($returnData);

        // 导出
        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, $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']]);

        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['shop_code'];
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $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);

        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }
}