<?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_staff_data extends Report {
    private $level=1;
    private $type=3;
    private $code='code1541640529';

    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'];
        }
        //获取店内所有有话务类型的员工
        // $staffs = getStaffsByWorkType(['shop_code'=>$data['shop_code'],'work_type'=>RECEIVE_WORK_TYPE]);
        // 所有追踪人
        $staffs = db('c_customerinfo')
            ->where('dj_day','between',[$start,$end])
            ->where('shop_code',$shop_code)
            ->where('is_status',1)->where('c_from',1)
            ->where('sales_staff_id','>',0)
            ->group('sales_staff')
            ->field('sales_staff,sales_staff_id')->select();
        // $staffs = array_column($allStaffs,'sales_staff');
        $staffIds = array_column($staffs,'sales_staff_id');
        foreach ($staffs as $key => $value) {
            $staffs[$key]['group'] = db('c_staff_group_relation')->alias('r')
                ->join('c_staff_group g','r.group_id=g.id','left')
                ->where('r.staff_id',$value['sales_staff_id'])
                ->value('g.group_name');
            // echo db()->getLastSql();
        }
        // die;
        // var_dump($staffs);
        // die;
        $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');
        $sql1 = db()->getLastSql();
        // 总订单量
        $allOrder = db('c_customerinfo')->alias('c')
            ->join('c_customer_order o','o.customer_id=c.id','left')
            ->where('c.is_success', '<>', 2)
            ->where('c.target_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');
        $sql2 = db()->getLastSql();
        // 续订转介绍订单量
        $xdOrder = db('c_customerinfo')->alias('c')
            ->join('c_customer_order o','o.customer_id=c.id','left')
            ->where('c.is_success', '<>', 2)
            ->where('c.target_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');
        $sql2_1 = db()->getLastSql();
        //实收
        $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('c.target_time', 'between time', [$start, $end])
            ->group('c.sales_staff_id')
            ->column('sum(d.order_fact) as fact','c.sales_staff_id');
        $sql3 = db()->getLastSql();
        //营收
        $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.target_time', 'between time', [$start, $end])
            ->group('c.sales_staff_id')
            ->column('sum(o.order_amount) as total','c.sales_staff_id');
        $sql4 = db()->getLastSql();
        $returnData = [];
        $arr = [];
        foreach ($staffs as $key => $value) {
            $returnData[$key]['sort']  = '';
            $returnData[$key]['staff'] = $value['sales_staff'];
            $returnData[$key]['group'] = $value['group'];
            $returnData[$key]['mkz'] = $info[$value['sales_staff_id']]['mkz'];
            $returnData[$key]['order'] = $allOrder[$value['sales_staff_id']] - $xdOrder[$value['sales_staff_id']];
            $returnData[$key]['orderxd'] = $xdOrder[$value['sales_staff_id']];
            $returnData[$key]['fact'] = sprintf('%.2f',$detail[$value['sales_staff_id']]);
            $returnData[$key]['total'] = sprintf('%.2f',$total[$value['sales_staff_id']]);
            // 毛客资订单率（ 订单 / 毛客资 ）
            $returnData[$key]['orderRate'] = sprintf('%.2f',$allOrder[$value['sales_staff_id']]/$info[$value['sales_staff_id']]['mkz']*100) . '%';
            $returnData[$key]['avg'] = sprintf('%.2f',$total[$value['sales_staff_id']]/$allOrder[$value['sales_staff_id']]);

            $returnData[$key]['sort']  = '';
            $arr['staff'] = '总计';
            $arr['mkz'] += $info[$value['sales_staff_id']]['mkz'];
            $arr['order'] += $returnData[$key]['order'];
            $arr['orderxd']+=$returnData[$key]['orderxd'];
            $arr['fact'] += $detail[$value['sales_staff_id']];
            $arr['total'] += $total[$value['sales_staff_id']];
            $arr['orderRate'] = '';
            $arr['avg'] = '';
        }

        $sort_order = 'SORT_DESC';
        $returnData = my_sort($returnData, 'fact', $sort_order);
        foreach ($returnData as $key => $value) {
            $returnData[$key]['sort'] = $key+1;
        }
        $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);
        // 导出
        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['sql1'] = $sql1;
            $return['sql2'] = $sql2;
            $return['sql3'] = $sql3;
            $return['sql4'] = $sql4;
            $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);
    }
}