<?php
/**
 * 客户管理模块
 * Created by PhpStorm.
 * User: tpl
 * Date: 2019/10/30
 * Time: 13:54
 */
namespace JinDouYun\Controller\Customer;


use JinDouYun\Dao\Department\DDepartment;
use JinDouYun\Dao\Department\DStaff;
use JinDouYun\Dao\Shop\DShop;
use JinDouYun\Dao\SysAreaChina\DSysAreaChina;
use JinDouYun\Dao\System\DCustomerSource;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Controller\BaseController;
use Jindouyun\Cache\CustomerCache;

use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\Order\MOrder;
use JinDouYun\Model\Customer\MReflectDetail;
use JinDouYun\Model\Customer\MMemberBalanceDetail;



class Customer extends BaseController
{
    /**
     * @var MCustomer
     */
    private $objMReflectDetail;
    private $objMMemberBalanceDetail;
    private $objMCustomer;
    //private $objTempSaveCache;

    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objMReflectDetail = new MReflectDetail($this->onlineEnterpriseId,$this->onlineUserId);
        $this->objMMemberBalanceDetail = new MMemberBalanceDetail($this->onlineEnterpriseId,$this->onlineUserId);
        //$this->objTempSaveCache = new TempSaveCache();
    }

    /**
     * 添加和编辑客户管理公共字段处理方法
     *
     * @return array
     */
    public function commonFieldFilter(){
        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $customerData = [
            'mobile' => isset($params['mobile']) ? $params['mobile'] : '',//账号
            'name' => isset($params['name']) ? $params['name'] : '',
            'type' => isset($params['type']) ? $params['type'] : '',//客户类型
        ];

        //非暂存则验空
        if (!isset($params['tempSave']) || $params['tempSave'] == false) {
            foreach($customerData as $key => $value){
                if(empty($value) && $value !== 0){
                    $this->sendOutput($key.'参数错误', ErrorCode::$paramError);
                }
            }
        }
        $customerData['enableStatus'] = isset($params['enableStatus']) ? $params['enableStatus'] : StatusCode::$standard;//启用状态
        $customerData['contact'] = isset($params['contact']) ? $params['contact'] : '';
        $customerData['provinceCode'] = isset($params['provinceCode']) ? $params['provinceCode'] : '';
        $customerData['cityCode'] = isset($params['cityCode']) ? $params['cityCode'] : '';
        $customerData['districtCode'] = isset($params['districtCode']) ? $params['districtCode'] : '';
        $customerData['shopId'] = isset($params['shopId']) ? $params['shopId'] : '';

        $customerData['longitude'] = isset($params['longitude']) ? $params['longitude'] : '';
        $customerData['latitude']  = isset($params['latitude']) ? $params['latitude'] : '';

        $customerData['tempSave']= isset($params['tempSave']) ? $params['tempSave'] : false;
        $customerData['password'] = isset($params['password']) ? $params['password'] : '';//密码
        $customerData['address'] = isset($params['address']) ? $params['address'] : '';
        $customerData['managerMobile'] = isset($params['managerMobile']) ? $params['managerMobile'] : '';
        $customerData['avatar'] = isset($params['avatar']) ? $params['avatar'] : '';//客户头像
        // $customerData['sortingId'] = isset($params['sortingId']) ? $params['sortingId'] : '';
        $customerData['departmentId'] = isset($params['departmentId']) ? $params['departmentId'] : '';
        $customerData['salesManId'] = isset($params['salesManId']) ? $params['salesManId'] : '';
        $customerData['salesManCode'] = isset($params['salesManCode']) ? $params['salesManCode'] : '';
        $customerData['salesManName'] = isset($params['salesManName']) ? $params['salesManName'] : '';
        $customerData['birthday'] = isset($params['birthday']) ? $params['birthday'] : '';
        $customerData['remark'] = isset($params['remark']) ? $params['remark'] : '';
        $customerData['deleteStatus']= StatusCode::$standard;
        $customerData['status']= isset($params['status']) ? $params['status'] : '';
        $customerData['area'] = isset($params['area']) ? $params['area'] : [];
        $customerData['shopName'] = isset($params['shopName']) ? $params['shopName'] : '';
        $customerData['reservoirId'] = isset($params['reservoirId']) ? $params['reservoirId'] : '';
        (isset($params['extend']) && !empty($params['extend'])) && $customerData['extend'] = json_encode($params['extend']);
        $customerData['memberBalance'] = getArrayItem($params, 'memberBalance','');
        $customerData['recommenderType'] = getArrayItem($params,'recommenderType','');
        $customerData['recommenderId'] =getArrayItem($params,'recommenderId','');
        
        $customerData['createTime'] = time();
        $customerData['updateTime'] = time();
        //联系人信息
        $customerData['contact'] = getArrayItem($params,'contact', []);
        return $customerData;
    }

    /**
     * 添加客户
     * @throws \Exception
     */
    public function addCustomer()
    {
        $customerData = $this->commonFieldFilter();
        if ($customerData['tempSave']) {
            //$this->objTempSaveCache->saveCustomer($this->onlineEnterpriseId, $this->onlineUserId, $customerData);
            parent::sendOutput('暂存成功');
        }

        unset($customerData['tempSave']);
        unset($customerData['area']);
        unset($customerData['shopName']);
        $result = $this->objMCustomer ->addCustomer($customerData);
        if($result->isSuccess()){
            //删除暂存数据
            //$this->objTempSaveCache->delCustomer($this->onlineEnterpriseId, $this->onlineUserId);
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 获取暂存信息
     */
    public function getTempData()
    {
        //$result = $this->objTempSaveCache->getCustomer($this->onlineEnterpriseId, $this->onlineUserId);
        $this->sendOutput('');
    }

    /**
     * 获取指定客户信息
     * @throws \Exception
     */
    public function getCustomerInfo()
    {
        $customerId  = $this->request->param('request_id');
        if ( !$customerId ) {
            $this->sendOutput('参数错误', ErrorCode::$paramError );
        }

        // 直接从缓存层返回
        $objCustomerCache = new CustomerCache();
        $customerData = $objCustomerCache->getCustomerData($this->onlineEnterpriseId, $customerId);
        if( !empty($customerData) ){
            $this->sendOutput($customerData);
        }

        $result = $this->objMCustomer->getCustomerInfo($customerId);
        if($result->isSuccess()){
            $objCustomerCache->cacheCustomerData($this->onlineEnterpriseId, $customerId, $result->getData());
            $this->sendOutput($result->getData());
        }else{
            $this->sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 编辑客户
     * @throws \Exception
     */
    public function editCustomer()
    {
        $customerId  = $this->request->param('request_id');
        if(empty($customerId)){
            $this->sendOutput('参数错误', ErrorCode::$paramError);
        }
        $customerData = $this->commonFieldFilter();
        $customerData['id'] = $customerId;
        unset($customerData['createTime']);
        unset($customerData['status']);
        unset($customerData['tempSave']);
        unset($customerData['area']);
        unset($customerData['shopName']);
        $result = $this->objMCustomer->editCustomer($customerData);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 后台批量分配部门及业务员
     */
    public function batchEditCustomer()
    {

        $params = $this->request->getRawJson();
        $data = [
            'ids' => isset($params['ids']) ? $params['ids'] : [],
            'departmentId' => isset($params['departmentId']) ? $params['departmentId'] : 0,//部门id
            'salesManId' => isset($params['salesManId']) ? $params['salesManId'] : 0,//业务员id
        ];

        foreach ($data as $key => $val){
            if (empty($val)){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }
        $result = $this->objMCustomer->batchEditCustomer($data);
        if(!$result->isSuccess()){
            $objCustomerCache = new CustomerCache();
            foreach ($data['ids'] as $key => $value){
                $objCustomerCache->delCustomerData($this->onlineEnterpriseId, $value);
            }
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }

    /**
     * 删除客户
     * @throws \Exception
     */
    public function delCustomer()
    {
       $userCenterIds = $this->request->getRawJson();
        if(!$userCenterIds){
            $this->sendOutput('参数错误', ErrorCode::$paramError);
        }
        $result = $this->objMCustomer->delCustomer($userCenterIds);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 客户启用和禁用
     * @throws \Exception
     */
    public function updateCustomerStatus()
    {
        $params = $this->request->getRawJson();
        if( empty($params['id']) &&  empty($params['enableStatus'])){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $result = $this->objMCustomer->updateCustomerStatus($params);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 客户审核通过和审核拒绝
     * @throws \Exception
     */
    public function updateCustomerCheckStatus()
    {
        $params = $this->request->getRawJson();
        if( empty($params['id']) &&  empty($params['status'])){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        if($params['status'] == StatusCode::$auditStatus['auditNotPass'] && !isset($params['reason'])) {
            $this->sendOutput('请输入审核拒绝的原因', ErrorCode::$paramError );
        }

        $params['reason'] = isset($params['reason']) ? $params['reason'] : '';
        $result = $this->objMCustomer->updateCustomerCheckStatus($params);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }


    /**
     * 后台所有客户列表
     * @throws \Exception
     */
    public function getAllCustomer()
    {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $pageParams = pageToOffset($params['page']?:1, $params['pageSize']?:10);

        $condition = [
            'status' => isset($params['status']) ? $params['status'] : 2,
            'enableStatus' => getArrayItem($params, 'enableStatus', 0),
            'keyword' => getArrayItem($params, 'keyword', ''),
            'salesManId' => getArrayItem($params, 'salesManId', 0),
            'shopId' => getArrayItem($params, 'shopId', 0),
            'cityCode' => getArrayItem($params, 'cityCode', 0),
            'districtCode' => getArrayItem($params, 'districtCode', 0),
            'provinceCode' => getArrayItem($params, 'provinceCode', 0),
            'offset'  => $pageParams['offset'],
            'limit'   => $pageParams['limit'],
        ];

        $result = $this->objMCustomer->getAllCustomer($condition);
        if($result->isSuccess()){
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 添加客户标签
     * @throws \Exception
     */
    public function addCustomerTag() {
        $params = $this->request->getRawJson();
        if( empty($params['id']) && empty($params['tag']) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $result = $this->objMCustomer->addCustomerTag($params);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 删除客户标签
     * @throws \Exception
     */
    public function delCustomerTag() {
        $params = $this->request->getRawJson();
        if( empty($params['id']) && empty($params['tag']) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $result = $this->objMCustomer->delCustomerTag($params);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 搜索
     */
    public function search() {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $selectParams = [
            'keyword' => isset($params['keyword']) ? $params['keyword'] : '',
            'type' => isset($params['type']) ? $params['type'] : '',
            'provinceCode' => isset($params['provinceCode']) ? $params['provinceCode'] : '',
            'cityCode' => isset($params['cityCode']) ? $params['cityCode'] : '',
            'districtCode' => isset($params['districtCode']) ? $params['districtCode'] : '',
            'status' => isset($params['status']) ? $params['status'] : '',
            'enableStatus' => isset($params['enableStatus']) ? $params['enableStatus'] : '',
            'shopId' => isset($params['shopId']) ? $params['shopId'] : '',
            'departmentId' => isset($params['departmentId']) ? $params['departmentId'] : '',
            'salesManId' => isset($params['salesManId']) ? $params['salesManId'] : '',
            'start' => isset($params['start']) ? $params['start'] : '',
            'end' => isset($params['end']) ? $params['end'] : ''
        ];

        $pageParams = pageToOffset($params['page']?:1, $params['pageSize']?:10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        $result = $this->objMCustomer->search($selectParams);
        if($result->isSuccess()){
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 客户查询
     * @throws \Exception
     */
    public function query() {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $selectParams = [
            'keyword' => isset($params['keyword']) ? $params['keyword'] : '',//关键字：客户姓名/手机号/负责人电话
            'tag' => isset($params['tag']) ? $params['tag'] : '',//标签
            'provinceCode' => isset($params['provinceCode']) ? $params['provinceCode'] : '',//区域
            'cityCode' => isset($params['cityCode']) ? $params['cityCode'] : '',
            'districtCode' => isset($params['districtCode']) ? $params['districtCode'] : '',
            'enableStatus' => isset($params['enableStatus']) ? $params['enableStatus'] : '',//客户启用状态
            'shopId' => isset($params['shopId']) ? $params['shopId'] : '',//所属商铺
            'source' => isset($params['source']) ? $params['source'] : '',//来源
            'salesManId' => isset($params['salesManId']) ? $params['salesManId'] : '',//业务员
            'birthday_start' => isset($params['birthday_start']) ? $params['birthday_start'] : '',//客户生日 开始
            'birthday_end' => isset($params['birthday_end']) ? $params['birthday_end'] : ''//客户生日 结束
        ];

        $pageParams = pageToOffset($params['page']?:1, $params['pageSize']?:10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        $result = $this->objMCustomer->query($selectParams);
        if($result->isSuccess()){
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
                'customerTotalNum' => $this->objMCustomer->getCustomerTotalNum(),
                'newCustomerNum'   => $this->objMCustomer->getNewCustomerNum(),
                'interestCustomerNum' =>$this->objMCustomer->getInterestCustomerNum(),
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 根据code获取客户的经纬度信息
     */
    public function getCustomerLocation() {
        $params = $this->request->getRawJson();
        $code = isset($params['code']) ? $params['code'] : '';
        $result = $this->objMCustomer->getCustomerLocation($code);
        if($result->isSuccess()){
            $returnData = $result->getData();
            parent::sendOutput($returnData);
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 导出方法
     * @throws \Exception
     */
    public function export()
    {
        $params = $this->request->getRawJson();
        $selectParams = [
            'keyword' => isset($params['keyword']) ? $params['keyword'] : '',
            'type' => isset($params['type']) ? $params['type'] : '',
            'provinceCode' => isset($params['provinceCode']) ? $params['provinceCode'] : '',
            'cityCode' => isset($params['cityCode']) ? $params['cityCode'] : '',
            'districtCode' => isset($params['districtCode']) ? $params['districtCode'] : '',
            'status' => isset($params['status']) ? $params['status'] : '',
            'enableStatus' => isset($params['enableStatus']) ? $params['enableStatus'] : '',
            'shopId' => isset($params['shopId']) ? $params['shopId'] : '',
            'departmentId' => isset($params['departmentId']) ? $params['departmentId'] : '',
            'salesManId' => isset($params['salesManId']) ? $params['salesManId'] : '',
            'start' => isset($params['start']) ? $params['start'] : '',
            'end' => isset($params['end']) ? $params['end'] : ''
        ];

        $selectParams['limit'] = null;
        $selectParams['offset'] = null;

        $result = $this->objMCustomer->getAllCustomer($selectParams);
        if($result->isSuccess() == false){
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        $returnData = $result->getData();
        $data = $returnData['data'];
        //导出到本地
        header ( "Content-type:application/vnd.ms-excel" );
        header ( "Content-Disposition:filename=客户列表.csv" );
        header ('Cache-Control: max-age=0');

        $fp = fopen('php://output', 'a');

        $head = ['客户名称','联系人','登录账号','客户类型','商铺','销售部门','业务员','账号状态','备注'];       //定义标题

        foreach ($head as $i => $v) {
            $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8');     //将中文标题转换编码，否则乱码
        }

        fputcsv($fp, $head);

        $limit = 10000;
        $num = 0;                                         //计数器
        foreach ( $data as $v ) {                           //循环数据
            $num++;
            if($num == $limit){
                ob_flush();         //释放内存
                flush();
            }
            $rows=[
                'name'=>$v['name'],
                'contactName'=>empty($v['contact']) ? '' : $v['contact'][0]['name'],
                'mobile' => $v['mobile'],
                'customerType' => $v['customerType'],
                'shopName' => $v['shopName'],
                'departmentName' => $v['departmentName'],
                'salesManName' => $v['salesManName'],
                'enableStatus' => ($v['enableStatus'] == StatusCode::$standard) ? "启用" : "禁用",
                'remark' => $v['remark'],
            ];

            foreach ( $rows as $kk => $vv){
                $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8');  //转译编码
            }
            fputcsv($fp, $rs);

            $rows = [];
        }
    }

    public function formatCustomer()
    {
        $result = $this->objMCustomer->formatCustomer();
        if(!$result->isSuccess()){
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }


    /**
     * 充值记录列表
     */
    public function getAllRechargeBalance()
    {
        $params = $this->request->getRawJson();
        if(empty($params)){
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $selectParams['shopId'] = isset($params['shopId']) ? $params['shopId'] : '';
        foreach($selectParams as $key => $value){
            if(empty($value)){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }

        $params['page'] = isset($params['page']) ? $params['page'] : 1;
        $params['pageSize'] = isset($params['pageSize']) ? $params['pageSize'] : 10;
        $pageParams = pageToOffset($params['page'], $params['pageSize']);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        if(isset($params['customerId'])){
            $selectParams['customerId'] = $params['customerId'];
        }

        if(isset($params['userCenterId'])){
            $selectParams['userCenterId'] = $params['userCenterId'];
        }

        $modelResult = $this->objMCustomer->getAllRechargeBalance($selectParams);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        $returnData = $modelResult->getData();

        $pageData = [
            'pageIndex' => $params['page'],
            'pageSize' => $params['pageSize'],
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);
    }

    /**
     * 首字母搜索客户
     */
    public function initialsSearch()
    {
        $params = $this->request->getRawJson();
        $data['condition'] = isset($params['condition']) ? trim($params['condition']) : '';
        $modelResult = $this->objMCustomer->initialsSearch($data);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        parent::sendOutput($modelResult->getData());
    }

    /**
     * 初始化客户首字母
     */
    public function initialsCustomer()
    {
        $modelResult = $this->objMCustomer->initialsCustomer();
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        parent::sendOutput($modelResult->getData());
    }

    /**
     * Doc: (des="查询客户商品购买记录")
     * User: XMing
     * Date: 2021/3/10
     * Time: 10:54 上午
     */
    public function searchCustomerBuyLog()
    {
        $params = $this->request->getRawJson();
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize']) ? $params['pageSize'] : 10;
        $pageParams = pageToOffset($params['page'], $params['pageSize']);
        $params['limit'] = $pageParams['limit'];
        $params['offset'] = $pageParams['offset'];
        $export = isset($params['export']) ? $params['export'] : 0;
        $modelResult = $this->objMCustomer->searchCustomerBuyLog($params,$export);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        $returnData = $modelResult->getData();
        $pageData = [
            'pageIndex' => $page,
            'pageSize' => $pageSize,
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);
    }

    /**
     * Doc: (des="销售排行")
     * User: XMing
     * Date: 2021/3/15
     * Time: 10:06 上午
     * @throws \Exception
     */
    public function salesManRank()
    {
        $params = $this->request->getRawJson();
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize']) ? $params['pageSize'] : 10;
        $pageParams = pageToOffset($params['page'], $params['pageSize']);
        $params['limit'] = $pageParams['limit'];
        $params['offset'] = $pageParams['offset'];
        $params['startTime'] = getArrayItem($params, 'startTime', strtotime(date('y-m-d 00:00:00'))) ;
        $params['endTime'] = getArrayItem($params, 'endTime', strtotime(date('y-m-d 23:59:59')));
        $params['orderStatus'] = getArrayItem($params, 'orderStatus',[4,5]);
        
        $objMOrder = new MOrder($this->onlineUserId,$this->onlineEnterpriseId);
        $export = isset($params['export']) ? $params['export'] : 0;
        $modelResult = $objMOrder->salesManRank($params,$export);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        $returnData = $modelResult->getData();
        $pageData = [
            'pageIndex' => $page,
            'pageSize' => $pageSize,
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);
    }

    /**
     * 积分流水
     */
    public function getAllCustomerIntegralDesc()
    {
        $params = $this->request->getRawJson();

        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize']) ? $params['pageSize'] : 10;
        $pageParams = pageToOffset($params['page'], $params['pageSize']);
        $data['limit'] = $pageParams['limit'];
        $data['offset'] = $pageParams['offset'];

        $data['customerId'] = isset($params['customerId']) ? $params['customerId'] : '';

        if(empty($data['customerId'])){
            parent::sendOutput('customerId参数为空', ErrorCode::$paramError);
        }

        if(isset($params['star']) && !empty($params['star']) && isset($params['end']) && !empty($params['end'])){
            $data['createTime'] = [
                'star' => $params['star'],
                'end' => $params['end']
            ];
        }

        $modelResult = $this->objMCustomer->getAllCustomerIntegralDesc($data);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        $returnData = $modelResult->getData();
        $pageData = [
            'pageIndex' => $page,
            'pageSize' => $pageSize,
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);
    }

    /**
     * 修改积分
     * @throws \Exception
     */
    public function updateCustomerIntegral()
    {
        $params = $this->request->getRawJson();
        $data = [
            'integral' => isset($params['integral']) ? $params['integral'] : '',
            'customerId' => isset($params['customerId']) ? $params['customerId'] : '',
            'type' => isset($params['type']) ? $params['type'] : '',
        ];
        foreach($data as $key => $value){
            if(empty($value)){
                parent::sendOutput($key.'参数为空', ErrorCode::$paramError);
            }
        }
        $data['desc'] = isset($params['desc']) ? $params['desc'] : '';
        if($this->shopId){
            $data['shopId'] = $this->shopId;
        }

        $result = $this->objMCustomer->updateCustomerIntegral($data);
        if(!$result->isSuccess()){
            $objCustomerCache = new CustomerCache();
            $objCustomerCache->delCustomerData($this->onlineEnterpriseId, $params['customerId']);
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }

    /**
     * 新注册未下单统计
     */
    public function noOrderCustomer()
    {
        $params = $this->request->getRawJson();
        if(!$params){
            parent::sendOutput('请求参数为空', ErrorCode::$paramError);
        }

        $data = [
            'intervalDay' => getArrayItem($params, 'intervalDay', 10),
            'customerName' => getArrayItem($params, 'customerName'),
            'salesManId' => getArrayItem($params, 'salesManId'),
            'provinceCode' => getArrayItem($params, 'provinceCode'),
            'cityCode' => getArrayItem($params, 'cityCode'),
            'districtCode' => getArrayItem($params, 'districtCode'),
        ];

        $page = getArrayItem($params, 'page', 1);
        $pageSize = getArrayItem($params, 'pageSize', 10);
        $pageParams = pageToOffset($page, $pageSize);
        $data['limit'] = $pageParams['limit'];
        $data['offset'] = $pageParams['offset'];

        $returnData = $this->objMCustomer->noOrderCustomer($data);
        if(!$returnData->isSuccess()){
            parent::sendOutput($returnData->getData(), $returnData->getErrorCode());
        }
        $returnData = $returnData->getData();
        $pageData = [
            'pageIndex' => $page,
            'pageSize' => $pageSize,
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);
    }

    /**
     * 距离最近一次未下单统计
     */
    public function intervalNoOrderCustomer()
    {
        $params = $this->request->getRawJson();
        if(!$params){
            parent::sendOutput('请求参数为空', ErrorCode::$paramError);
        }

        $data = [
            'intervalDay' => getArrayItem($params, 'intervalDay', 10),
            'customerName' => getArrayItem($params, 'customerName'),
            'salesManId' => getArrayItem($params, 'salesManId'),
            'provinceCode' => getArrayItem($params, 'provinceCode'),
            'cityCode' => getArrayItem($params, 'cityCode'),
            'districtCode' => getArrayItem($params, 'districtCode'),
        ];

        $page = getArrayItem($params, 'page', 1);
        $pageSize = getArrayItem($params, 'pageSize', 10);
        $pageParams = pageToOffset($page, $pageSize);
        $data['limit'] = $pageParams['limit'];
        $data['offset'] = $pageParams['offset'];

        $returnData = $this->objMCustomer->intervalNoOrderCustomer($data);
        if(!$returnData->isSuccess()){
            parent::sendOutput($returnData->getData(), $returnData->getErrorCode());
        }
        $returnData = $returnData->getData();
        $pageData = [
            'pageIndex' => $page,
            'pageSize' => $pageSize,
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);
    }

    /**
     * 拉新统计
     */
    public function recommenderStatic()
    {
        $params = $this->request->getRawJson();
        if(!$params){
            parent::sendOutput('请求参数为空', ErrorCode::$paramError);
        }

        $data = [
            'startTime' => getArrayItem($params, 'startTime', 0),
            'endTime' => getArrayItem($params, 'endTime', 0),
            'customerId' => getArrayItem($params, 'customerId', 0),
            'staffId' => getArrayItem($params, 'staffId', 0),
        ];

        $page = getArrayItem($params, 'page', 1);
        $pageSize = getArrayItem($params, 'pageSize', 10);
        $pageParams = pageToOffset($page, $pageSize);
        $data['limit'] = $pageParams['limit'];
        $data['offset'] = $pageParams['offset'];

        $returnData = $this->objMCustomer->recommenderStatic($data);
        if(!$returnData->isSuccess()){
            parent::sendOutput($returnData->getData(), $returnData->getErrorCode());
        }
        $returnData = $returnData->getData();
        $pageData = [
            'pageIndex' => $page,
            'pageSize' => $pageSize,
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);
    }


    //审核，打款公共方法
    public function updateReflectDetail()
    {
        $params = $this->request->getRawJson();
        if (empty($params['id']) || empty($params['createTime'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $result = $this->objMReflectDetail->updateReflectDetail($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 所有提现记录
     */
    public function getAllReflectDetail()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $params['limit'] = $pageParams['limit'];
        $params['offset'] = $pageParams['offset'];
        $params['start'] = getArrayItem($params,'start',"");
        $params['end'] = getArrayItem($params,'end',"");
        $params['customerId'] = getArrayItem($params,'customerId', '');
        $params['reflectStatus'] = getArrayItem($params,'reflectStatus', '');
        $params['auditStatus'] = getArrayItem($params,'auditStatus', '');
        $params['reflectType'] = getArrayItem($params,'reflectType', '');//提现类型

        $returnData = $this->objMReflectDetail->getAllReflectDetail($params);

        if ($returnData->isSuccess()) {
            $returnData = $returnData->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize'  => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($returnData->getData(), ErrorCode::$dberror);
        }
    }

    /**
     * 后台充值
     */
    public function rechargeMemberBalance()
    {

        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        //记录流水
        $memberBalanceDetailData = [
            'customerId' => $params['customerId'],
            'type'       => $params['type'],
            'userCenterId' => $this->onlineUserId,
            'money'         =>$params['money'],
            'purpose'    => isset($params['purpose']) ? $params['purpose']: 0,
            'orderIds'      =>'',
            'remark'     => '充值'.$params['money'],
            'financeType' => '会员余额充值',
            'accountId' => isset($params['accountId']) ? $params['accountId']: 0,
            'accountName' => isset($params['accountName']) ? $params['accountName']: '',
            'accountNumber' => isset($params['accountNumber']) ? $params['accountNumber']: '',
            'explain'      => isset($params['explain']) ? $params['explain']: '',
        ];
        foreach ($memberBalanceDetailData as $k =>$v) {//,'accountId','accountName','accountNumber'
            if(in_array($k, ['customerId','money','purpose']) && empty($v)) {
                $this->sendOutput('请输入'.$k, ErrorCode::$paramError);
            }
        }
        $result = $this->objMMemberBalanceDetail->addMemberBalanceDetail($memberBalanceDetailData,$isbackstage=true);
        if (!$result->isSuccess()) {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }
    
    /**
     * 接收导入客户数据参数
     * @throws \Exception
     */
    public function getCustomerBasicImportParams()
    {
   
        //获取数据文件
        $params = $this->request->getRawJson();
        //企业id
        $enterpriseId = $this->onlineEnterpriseId;
        
        //引用dao
        $objDSysAreaChina = new DSysAreaChina(); //省市区dao
        $objDShop = new DShop();//商铺dao
        $objDShop->setTable('qianniao_shop_1' );
        $objDDepartment = new DDepartment();//销售部门dao
        $objDDepartment->setTable('qianniao_department_' . $enterpriseId);
        $objDDStaff = new DStaff();//员工表
        $objDDStaff->setTable('qianniao_staff_' . $enterpriseId);
        //获取数据
        $postArray = [];
        foreach ($params as $value) {
            $customerArray = $value;
            //客户信息
            $name       = isset($customerArray['name']) ? trim($customerArray['name']) : '';//客户名称
            $mobile     = isset($customerArray['mobile']) ? trim($customerArray['mobile']) : '';//登录账号
            $contacts   = isset($customerArray['contacts']) ? trim($customerArray['contacts']) : '';//联系人
            $nameMobile = isset($customerArray['nameMobile']) ? trim($customerArray['nameMobile']) : 4;//联系人电话
            $birthday   = isset($customerArray['birthday']) ? trim($customerArray['birthday']) : '';//客户生日
            $remark     = isset($customerArray['remark']) ? trim($customerArray['remark']) : '';//客户备注
            $customerType = isset($customerArray['type']) ? trim($customerArray['type']) : '';//客户类型
    
            //省市区
            $provinceName = isset($customerArray['provinceName']) ? trim($customerArray['provinceName']) : '';//省名称
            $cityName     = isset($customerArray['cityName']) ? trim($customerArray['cityName']) : '';//市名称
            $areaName     = isset($customerArray['areaName']) ? trim($customerArray['areaName']) : '';//区名称
            $address      = isset($customerArray['address']) ? trim($customerArray['address']) : '';//详细地址

            $shopName     = isset($customerArray['shopName']) ? trim($customerArray['shopName']) : '';//商铺名称
            $departmentId = isset($customerArray['departmentId']) ? trim($customerArray['departmentId']) : '';//销售部门id
            $salesManId = isset($customerArray['salesManId']) ? trim($customerArray['salesManId']) : '';//业务员Id
            $salesManCode = createCode(StatusCode::$code['staff']['prefix'],$salesManId, StatusCode::$code['staff']['length']);
    
            if (empty($name)) {
                continue;
            }
//            //业务员
//            $salesManId = 0;
//            $salesManCode ='';
//            if(!empty($salesManName)){
//                $dbResult = $objDDStaff->get(['staffName'=> $salesManName]);
//                if($dbResult !== false){
//                  $salesManId = $dbResult['id'];
//                    $salesManCode = createCode(StatusCode::$code['staff']['prefix'],$salesManId, StatusCode::$code['staff']['length']);
//
//                }
//            }
            //商铺
            $shopId = 0;
            if(!empty($shopName)){
                $dbResult = $objDShop->get(['name'=>$shopName]);
                if($dbResult !== false){
                    $shopId = $dbResult['id'];
                }
            }
            //销售部门
//            $departmentId = 0;
//            if(!empty($departmentName)){
//                $dbResult = $objDDepartment->get(['departmentName'=>$departmentName]);
//                if($dbResult !== false){
//                    $departmentId = $dbResult['id'];
//                }
//            }
            //省市区
            $provinceCode ='';
            $cityCode = '';
            $areaCode = '';
            if(!empty($provinceName)){
                //省编码
                $dbResult = $objDSysAreaChina->get(['name'=>$provinceName]);
                if($dbResult !== false){
                    $provinceCode = $dbResult['code'];
                    //市编码
                    $dbResult = $objDSysAreaChina->get(['name'=>$cityName,'pcode'=>$provinceCode]);
                    if($dbResult !== false){
                        $cityCode = $dbResult['code'];
                        //区编码
                        $dbResult = $objDSysAreaChina->get(['name'=>$areaName,'pcode'=>$cityCode]);
                        if($dbResult !== false){
                            $areaCode = $dbResult['code'];
                        }
                    }
                }
               
            }
            
            $postData =  array (
                        'tempSave' => '',
                        'latitude' => '',
                        'longitude' => '',
                        'password' => '',
                        'area' => '',
                        'mobile' => $mobile,
                        'enableStatus' => 5,
                        'name' => $name,
                        'code' => '',
                        'type' => $customerType,
                        'provinceCode' => $provinceCode,
                        'cityCode' => $cityCode,
                        'districtCode' => $areaCode,
                        'address' => $address,
                        'managerMobile' => '',
                        'shopId' => $shopId,
                        'departmentId' => $departmentId,
                        'salesManId' => $salesManId,
                        'salesManCode' => $salesManCode,
                        'salesManName' => '',
                        'birthday' => $birthday,
                        'remark' => $remark,
                        'reservoirId' => $customerType,
                        'recommenderType' => '',
                        'recommenderId' => '',
                        'extend' =>
                            array (
                                'license' => '',
                            ),
                        'contact' =>
                            array (
                                'area' => '',
                                'name' => $contacts,
                                'mobile' => $nameMobile,
                                'provinceCode' => $provinceCode,
                                'cityCode' => $cityCode,
                                'districtCode' => $areaCode,
                                'address' => $address,
                            ),
                    );
            
            $postArray[] = $postData;
        }
        return $postArray;
    }
    
    /**
     * 导入客户资料
     * @throws \Exception
     */
    public function customerImport()
    {
        //把页面传来的参数对应到符合的字段中全部传递过来;
        $paramsArray = self::getCustomerBasicImportParams();
        if (empty($paramsArray)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
       
        $customerBasic = [];
        foreach ($paramsArray as $params) {
            $customerData = [
                'mobile' => isset($params['mobile']) ? $params['mobile'] : '',//账号
                'name' => isset($params['name']) ? $params['name'] : '',
                'type' => isset($params['type']) ? $params['type'] : '',//客户类型
            ];
            //非暂存则验空
            if (!isset($params['tempSave']) || $params['tempSave'] == false) {
                foreach ($customerData as $key => $value) {
                    if (empty($value) && $value !== 0) {
                        $this->sendOutput($key . '参数错误', ErrorCode::$paramError);
                    }
                }
            }
            $customerData['enableStatus'] = isset($params['enableStatus']) ? $params['enableStatus'] : StatusCode::$standard;//启用状态
            $customerData['contact'] = isset($params['contact']) ? $params['contact'] : '';
            $customerData['provinceCode'] = isset($params['provinceCode']) ? $params['provinceCode'] : '';
            $customerData['cityCode'] = isset($params['cityCode']) ? $params['cityCode'] : '';
            $customerData['districtCode'] = isset($params['districtCode']) ? $params['districtCode'] : '';
            $customerData['shopId'] = isset($params['shopId']) ? $params['shopId'] : '';
            $customerData['longitude'] = isset($params['longitude']) ? $params['longitude'] : '';
            $customerData['latitude'] = isset($params['latitude']) ? $params['latitude'] : '';
            $customerData['tempSave'] = isset($params['tempSave']) ? $params['tempSave'] : false;
            $customerData['password'] = isset($params['password']) ? $params['password'] : '';//密码
            $customerData['address'] = isset($params['address']) ? $params['address'] : '';
            $customerData['managerMobile'] = isset($params['managerMobile']) ? $params['managerMobile'] : '';
            $customerData['avatar'] = isset($params['avatar']) ? $params['avatar'] : '';//客户头像
            // $customerData['sortingId'] = isset($params['sortingId']) ? $params['sortingId'] : '';
            $customerData['departmentId'] = isset($params['departmentId']) ? $params['departmentId'] : '';
            $customerData['salesManId'] = isset($params['salesManId']) ? $params['salesManId'] : '';
            $customerData['salesManCode'] = isset($params['salesManCode']) ? $params['salesManCode'] : '';
            $customerData['salesManName'] = isset($params['salesManName']) ? $params['salesManName'] : '';
            $customerData['birthday'] = isset($params['birthday']) ? $params['birthday'] : '';
            $customerData['remark'] = isset($params['remark']) ? $params['remark'] : '';
            $customerData['deleteStatus'] = StatusCode::$standard;
            $customerData['status'] = isset($params['status']) ? $params['status'] : '';
            $customerData['area'] = isset($params['area']) ? $params['area'] : [];
            $customerData['shopName'] = isset($params['shopName']) ? $params['shopName'] : '';
            $customerData['reservoirId'] = isset($params['reservoirId']) ? $params['reservoirId'] : '';
            (isset($params['extend']) && !empty($params['extend'])) && $customerData['extend'] = json_encode($params['extend']);
            $customerData['memberBalance'] = getArrayItem($params, 'memberBalance', '');
            $customerData['recommenderType'] = getArrayItem($params, 'recommenderType', '');
            $customerData['recommenderId'] = getArrayItem($params, 'recommenderId', '');
    
            $customerData['createTime'] = time();
            $customerData['updateTime'] = time();
            //联系人信息
            $customerData['contact'] = getArrayItem($params, 'contact', []);
            $customerBasic[] = $customerData;
        }
        unset($customerData);
        
        $total = 0;
        $true  = 0;
        $false = 0;
        $exportError = date('Ymd_H:i:s').'.txt';
        foreach ($customerBasic as $key => $customerData){
            if ($customerData['tempSave']) {
                parent::sendOutput('暂存成功');
            }
            unset($customerData['tempSave']);
            unset($customerData['area']);
            unset($customerData['shopName']);
            $result = $this->objMCustomer ->addCustomer($customerData);
            if(!$result->isSuccess()){
                if(!is_dir(UPLOAD_FILE_PATH.'/exportError/')){
                    mkdir(UPLOAD_FILE_PATH.'/exportError/',0777,true);
                }
                $a = $key+1;
                file_put_contents(UPLOAD_FILE_PATH.'/exportError/'.$exportError,'第 '. $a .'行导入失败,原因'.var_export($result->getData().$result->getErrorCode(),true).PHP_EOL,FILE_APPEND);
                $false++;
            } else {
                $true++;
            }
            $total++;
        }
        
        $returnData = [
            'successMsg' => '共'.$total.'条客户数据,成功'.$true.'条客户数据,失败'.$false.'条客户数据',
            'errorNum'   => $false,
            'url'        => URL_UPLOAD.'exportError/'.$exportError,
        ];
        parent::sendOutput($returnData);
    }


    /**
     * 客户分布
     */
    public function getCustomerDistributed()
    {
        $returnData = $this->objMCustomer->getCustomerDistributed();
        if(!$returnData->isSuccess()){
            parent::sendOutput($returnData->getData(), $returnData->getErrorCode());
        }
        parent::sendOutput($returnData->getData());
    }

    /**
     * 批量设置客户类型
     */
    public function setCustomerType()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $params['customerIds'] = getArrayItem($params,'customerIds',[]);
        $params['type'] = getArrayItem($params,'type',0);

        $result = $this->objMCustomer->setCustomerType($params);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

























    
}