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

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

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

    }
    public function getType(){
        return $this->type;
    }
    public function getCode(){
        return $this->code;
    }
    public function data()
    {
        $title = ['组名', '姓名', '(进店)实际达成', '(进店)目标', '(进店)差额', '(进店)达成比', '(新单)实际达成', '(新单)目标', '(新单)差额', '(新单)达成比'];

        $data = input();
        $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'=>'报表配置有误');
        }

        //获取店下的小组,人员 关联查询
        $groupList = db('c_staff_group')->alias('g')->join('c_staff_group_relation r','g.id = r.group_id')
            ->where('g.shop_code', $shop_code)
            ->order('g.id')
            ->column('g.id,g.group_name,r.staff_id,r.staff_name','r.staff_id');
        $staffIds = array_column($groupList,'staff_id');
        $noGroup = getStaffsByWorkType(['shop_code'=>$shop_code,'work_type'=>RECEIVE_WORK_TYPE]);
        $noGroupStaff = array_column($noGroup,'id');
        $staff_diff_id = array_diff($noGroupStaff,$staffIds);
        $staff_diff_id = implode(',',$staff_diff_id);
        $url = '5a18e3fa516a1';
        $res = sx_call($url,['staff_id'=>$staff_diff_id]);
        if($res['code'] == 200){
            $another = $res['data'];
        }
        $returnData = [];
        $data = input();
        $timeArea = explode('-', $data['timeArea']);
        $time = getdateArea($data['timeArea']);
        // 时间区域
        if ($data['timeArea']) {
            $year = $timeArea[0];
            $month = $timeArea[1];
            $start = $time[0];
            $end = $time[1];
        } else {
            $year = date('Y');
            $month = date('Y-m');
            $start = date('Y-m', time());
            $end = date('Y-m-d H:i:s', time());
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        // $where['customer_type'] = 1;
        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        if ($det['brandclass_id'] != 2) {
            $where['customer_type'] = HS_TYPE;
        }
        if($data['consultation_type_id']){
            $where['consultation_type_id'] = intval($data['consultation_type_id']);
        }
        $where['shop_code'] = $shop_code;

        $sql = '';
        $sql .= "sum(syjd_day between '$start' and '$end' and is_intostore in (2,3)) as jd,";
        $sql .= "sum(is_success=1 and order_day between '$start' and '$end') as neworder";
        $info = db('c_customerinfo')
            ->where($where)
            ->where('sales_staff_id', 'in',$noGroupStaff)
            ->group('sales_staff_id')
            ->column($sql,'sales_staff_id');

        $total = [];
        foreach ($groupList as $k => $v) {
            $arr['group_name'] =  $v['group_name'];
            $arr['staff_name'] = $v['staff_name'];
            $arr['sj_num'] = $info[$k]['jd'] ? $info[$k]['jd'] : '';
            //目标
            //通过人查目标
            $goal = db('s_kpi_staffgoal')
                ->where('staff_id', $k)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where('month', intval($month))
                ->where('shop_code', $shop_code)
                ->value('kpi_value');
            //通过岗位查
            if (empty($goal)) {
                $staffInfo = getStaffInfoById($k);
                $goal = db('s_kpi_staffgoal')
                    ->where('position_code', $staffInfo['main_position_code'])
                    ->where('staff_id', 0)
                    ->where('month', intval($month))
                    ->where('shop_code', $shop_code)
                    ->where('kpi_id', 'actualIntoCustomerNumber')
                    ->value('kpi_value');
            }
            $arr['goal'] = $goal ? $goal : '';
            $arr['diff'] = $arr['goal'] - $arr['sj_num'] != 0 ? $arr['goal'] - $arr['sj_num'] : '';
            $arr['rate'] = number_format(intval($arr['sj_num']) / intval($arr['goal']) * 100, 2) . '%';
            $arr['order_num'] = $info[$k]['neworder'] ? $info[$k]['neworder'] : '';
            //目标
            //通过人查目标
            $goal1 = db('s_kpi_staffgoal')
                ->where('staff_id', $k)
                ->where('kpi_id', 'orderNumber')
                ->where('month', intval($month))
                ->where('shop_code', $shop_code)
                ->value('kpi_value');
            //通过岗位查
            if (empty($goal1)) {
                $staffInfo = getStaffInfoById($k);
                $goal1 = db('s_kpi_staffgoal')
                    ->where('position_code', $staffInfo['main_position_code'])
                    ->where('staff_id',0)
                    ->where('month', intval($month))
                    ->where('shop_code', $shop_code)
                    ->where('kpi_id', 'orderNumber')
                    ->value('kpi_value');
            }
            $arr['order_goal'] = $goal1 ? $goal1 : '';
            $arr['order_diff'] = $arr['order_goal'] - $arr['order_num'] != 0 ? $arr['order_goal'] - $arr['order_num'] : '';
            $arr['order_rate'] = number_format(intval($arr['order_num']) / intval($arr['order_goal']) * 100, 2) . '%';
            array_push($returnData, $arr);
            $total['group_name'] = '';
            $total['staff_name'] = '总计';
            $total['sj_num'] += intval($arr['sj_num']);
            $total['goal'] += intval($arr['goal']);
            $total['diff'] += intval($arr['diff']);
            $total['rate'] = 0;
            $total['order_num'] += intval($arr['order_num']);
            $total['order_goal'] += intval($arr['order_goal']);
            $total['order_diff'] += intval($arr['order_diff']);
            $total['order_rate'] = 0;
        }
        foreach ($another as $k => $v) {
            $arr['group_name'] = '无小组';
            $arr['staff_name'] = $v['staffname'];
            $arr['sj_num'] = $info[$v['id']]['jd'] ? $info[$v['id']]['jd'] : '';
            //目标
            //通过人查目标
            $goal = db('s_kpi_staffgoal')
                ->where('staff_id', $v['id'])
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where('month', intval($month))
                ->where('shop_code', $shop_code)
                ->value('kpi_value');
            //通过岗位查
            if (empty($goal)) {
                $staffInfo = getStaffInfoById($v['id']);
                $goal = db('s_kpi_staffgoal')
                    ->where('position_code', $staffInfo['main_position_code'])
                    ->where('staff_id', 0)
                    ->where('month', intval($month))
                    ->where('shop_code', $shop_code)
                    ->where('kpi_id', 'actualIntoCustomerNumber')
                    ->value('kpi_value');
            }
            $arr['goal'] = $goal ? $goal : '';
            $arr['diff'] = $arr['goal'] - $arr['sj_num'] != 0 ? $arr['goal'] - $arr['sj_num'] : '';
            $arr['rate'] = number_format(intval($arr['sj_num']) / intval($arr['goal']) * 100, 2) . '%';
            $arr['order_num'] = $info[$v['id']]['neworder'] ? $info[$v['id']]['neworder'] : '';
            //目标
            //通过人查目标
            $goal1 = db('s_kpi_staffgoal')
                ->where('staff_id', $v['id'])
                ->where('kpi_id', 'orderNumber')
                ->where('month', intval($month))
                ->where('shop_code', $shop_code)
                ->value('kpi_value');
            //通过岗位查
            if (empty($goal1)) {
                $staffInfo = getStaffInfoById($v['id']);
                $goal1 = db('s_kpi_staffgoal')
                    ->where('position_code', $staffInfo['main_position_code'])
                    ->where('staff_id',0)
                    ->where('month', intval($month))
                    ->where('shop_code', $shop_code)
                    ->where('kpi_id', 'orderNumber')
                    ->value('kpi_value');
            }
            $arr['order_goal'] = $goal1 ? $goal1 : '';
            $arr['order_diff'] = $arr['order_goal'] - $arr['order_num'] != 0 ? $arr['order_goal'] - $arr['order_num'] : '';
            $arr['order_rate'] = number_format(intval($arr['order_num']) / intval($arr['order_goal']) * 100, 2) . '%';
            array_push($returnData, $arr);
            $total['group_name'] = '';
            $total['staff_name'] = '总计';
            $total['sj_num'] += intval($arr['sj_num']);
            $total['goal'] += intval($arr['goal']);
            $total['diff'] += intval($arr['diff']);
            $total['rate'] = 0;
            $total['order_num'] += intval($arr['order_num']);
            $total['order_goal'] += intval($arr['order_goal']);
            $total['order_diff'] += intval($arr['order_diff']);
            $total['order_rate'] = 0;
        }
        $total['rate'] = number_format(intval($total['sj_num']) / intval($total['goal']) * 100, 2) . '%';
        $total['order_rate'] = number_format(intval($total['order_num']) / intval($total['order_goal']) * 100, 2) . '%';
        array_push($returnData, $total);
        // 导出
        if ($data['need'] == 1) {
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$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();
        //获取方式
//        $accessModel = controller("Customer", "lib")->accessModel(array('shop_code' => session('shop_code')));
//        $this->assign("accessModel", $accessModel);
        //来源渠道
//        $channel = controller("Customer", "lib")->getChannel();
//        $this->assign("channel", $channel);
        //客资地域
        // crm省    列表
//        $data['type'] = 1;
//        $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');
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('title', $shop[0]['shop_name'].'-'.$title);
        //查询事业部下的电商店
//        $shop = controller('crm/Customer','lib')->shop(['belong_shop_code'=>session('shop_code'),'is_marketing'=>1]);
        $this->assign('did', $info['id']);
        $this->assign('shop', $shop);
        return $this->fetch($display);
    }

}