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

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

        $staffIds = array_column($staffs,'id');
        $sql = '';
        $sql .= "sum(dj_day between '$start' and '$end') as mkz,";
        $sql .= "sum(is_intostore in (2,3) and syjd_day between '$start' and '$end') as jd,";
        $sql .= "sum((is_intostore=2 or is_intostore=3) and is_success<>1 and syjd_day between '$start' and '$end') as zd,";
        $sql .= "sum(is_success=1 and order_type=1 and order_day between '$start' and '$end') as online,";
        $sql .= "sum(is_success=1 and order_type=2 and order_day between '$start' and '$end') as intoOrder,";
        $sql .= "sum(is_success=1 and order_day between '$start' and '$end') as `order`";


        // 录入客资量（分配）
        $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');
        $whereTx['c.c_from'] = 1;
        $whereTx['c.is_status'] = 1;
        $whereTx['c.is_success'] = 1;
        //营收
        $detail = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->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','c.order_number=o.order_sn')
            ->where($whereTx)
            ->where('c.shop_code', $data['shop_code'])
            ->where('c.sales_staff_id', 'in',$staffIds)
            ->where('o.order_valid', 2)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.sales_staff_id')
            ->column('sum(o.order_amount) as total','c.sales_staff_id');

        $returnData = [];
        $arr = [];
        foreach ($staffs as $key => $value) {
            $returnData[$key]['staff'] = $value['staffname'];
            $returnData[$key]['mkz'] = $info[$value['id']]['mkz'];
            $returnData[$key]['jd'] = $info[$value['id']]['jd'];
            $returnData[$key]['zd'] = $info[$value['id']]['zd'];
            $returnData[$key]['online'] = $info[$value['id']]['online'];
            $returnData[$key]['intoOrder'] = $info[$value['id']]['intoOrder'];
            $returnData[$key]['order'] = $info[$value['id']]['order'];
            $returnData[$key]['fact'] = sprintf('%.2f',$detail[$value['id']]);
            $returnData[$key]['total'] = sprintf('%.2f',$total[$value['id']]);
            // 毛客资进店率（ 进店 / 毛客资 ）
            $returnData[$key]['mkzRate'] = sprintf('%.2f',$info[$value['id']]['jd']/$info[$value['id']]['mkz']*100) . '%';
            // 毛客资订单率（ 订单 / 毛客资 ）
            $returnData[$key]['orderRate'] = sprintf('%.2f',$info[$value['id']]['order']/$info[$value['id']]['mkz']*100) . '%';
            // 成交率（ 订单 / 进店 ）
            $returnData[$key]['succRate'] = sprintf('%.2f',$info[$value['id']]['order']/$info[$value['id']]['jd']*100) . '%';
            $returnData[$key]['avg'] = sprintf('%.2f',$total[$value['id']]/$info[$value['id']]['order']);


            $arr['staff'] = '总计';
            $arr['mkz'] += $info[$value['id']]['mkz'];
            $arr['jd'] += $info[$value['id']]['jd'];
            $arr['zd'] += $info[$value['id']]['zd'];
            $arr['online'] += $info[$value['id']]['online'];
            $arr['intoOrder'] += $info[$value['id']]['intoOrder'];
            $arr['order'] += $info[$value['id']]['order'];
            $arr['fact'] += $detail[$value['id']];
            $arr['total'] += $total[$value['id']];
            $arr['mkzRate'] = '';
            $arr['orderRate'] = '';
            $arr['succRate'] = '';
            $arr['avg'] = '';
        }
        $arr['fact'] = sprintf('%.2f',$arr['fact']);
        $arr['total'] = sprintf('%.2f',$arr['total']);
        $arr['mkzRate'] = sprintf('%.2f',$arr['jd']/$arr['mkz']*100).'%';
        $arr['orderRate'] = sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%';
        $arr['succRate'] = sprintf('%.2f',$arr['order']/$arr['jd']*100).'%';
        $arr['avg'] = sprintf('%.2f',$arr['total']/$arr['order']);
        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['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);
    }
}