<?php
/**
* Created by PhpStorm.
* User: kang
* Date: 2021/3/10
* Time: 10:11
*/

namespace JinDouYun\Model\Customer;

use JinDouYun\Dao\UserCenter\DUserCenter;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Model\MBaseModel;

use JinDouYun\Dao\Customer\DCustomer;
use JinDouYun\Dao\Customer\DCustomerVisitsLog;
use JinDouYun\Dao\GoodsManage\DGoodsBasic;

class MCustomerVisitsLog extends MBaseModel
{
    
    private $objDCustomerVisitsLog;
    private $enterpriseId;
    private $userCenterId;
    private $objDCustomer;
    
    public function __construct($enterpriseId, $userCenterId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        parent::__construct($this->enterpriseId, $this->userCenterId);
        $this->objDCustomerVisitsLog = new DCustomerVisitsLog('default');
        $this->objDCustomerVisitsLog->setTable('qianniao_customer_visits_log_'.$enterpriseId);
        $this->objDCustomer = new DCustomer();
        $this->objDCustomer->setTable('qianniao_customer_'.$enterpriseId);
    }
    
    /**
     * 添加客户访问记录
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addCustomerVisitsLog($visitsLogData)
    {
        $accountTypeId = $this->objDCustomerVisitsLog->insert($visitsLogData);
        if($accountTypeId === false){
            return ResultWrapper::fail($this->objDCustomerVisitsLog->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($accountTypeId);
    }
    
    /**
     * 获取指定客户访问记录
     */
    public function getCustomerVisitsLogInfo($customerVisitsLogId)
    {
        $dbResult = $this->objDCustomerVisitsLog->select($customerVisitsLogId);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerVisitsLog->error(), ErrorCode::$dberror);
        }
        if( empty($dbResult) ){
            return ResultWrapper::success([]);
        }
        return ResultWrapper::success( self::format($dbResult) );
    }
    
    /**
     * 格式化
     * @return array
     */
    public function format($data)
    {
        // 映射客户id对应的名字
        $customerIdBindName = [];
        // 映射客户id对应的手机号
        $userCenterIdBindMobile = [];
        // 映射商品id和商品名称
        $goodsIdBindName = [];
        // 映射商品id和商品图片
        $goodsIdBindImg = [];
        
        $customerIds = array_column($data, 'customerId');
        $goodsIds = array_column($data, 'goodsId');
        $userCenterIds = array_column($data, 'usercenterId');
        
        // 客户数据映射
        if(!empty($customerIds)){
            $customerData = $this->objDCustomer->select($customerIds, 'id,name');
            if($customerData !== false){
                if( !empty($customerData) ){
                    foreach ($customerData as $key => $value){
                        $customerIdBindName[$value['id']] = $value['name'];
                    }
                }
            }
        }
        // 客户电话数据映射
        if(!empty($customerIds)){
            $objDUserCenter = new DUserCenter();
            $userCenterData = $objDUserCenter->select($userCenterIds, 'id,mobile');
            if($userCenterData !== false){
                if( !empty($userCenterData) ){
                    foreach ($userCenterData as $key => $value){
                        $userCenterIdBindMobile[$value['id']] = $value['mobile'];
                    }
                }
            }
        }
        
        // 根据商品ids查询商品名称和图片进行映射
        $objDGoodsBasic = new DGoodsBasic();
        $objDGoodsBasic->setTable('qianniao_goods_basic_'.$this->enterpriseId);
        if(!empty($goodsIds)){
            $dbResult = $objDGoodsBasic->select($goodsIds,'id,title,images');
            if($dbResult !== false){
                if( !empty($dbResult) ){
                    foreach ($dbResult as $key => $value){
                        $goodsIdBindName[$value['id']] = $value['title'];
                        $goodsIdBindImg[$value['id']]  = $value['images'];
                    }
                }
            }
        }

        // 循环主数据，进行对应的字段映射操作
        foreach ($data as $key => $value){
            $data[$key]['customerName'] = '';
            if( isset($customerIdBindName[$value['customerId']]) ){
                $data[$key]['customerName'] = $customerIdBindName[$value['customerId']];
            }
            $data[$key]['mobile'] = '';
            if( isset($userCenterIdBindMobile[$value['usercenterId']]) ){
                $data[$key]['mobile'] = $userCenterIdBindMobile[$value['usercenterId']];
            }
            $data[$key]['goodsName'] = '';
            if( isset($goodsIdBindName[$value['goodsId']]) ){
                $data[$key]['goodsName'] = $goodsIdBindName[$value['goodsId']];
            }
            
            
        }
        return $data;
    }
    
    
    /**
     * 获取所有的客户的浏览记录
     */
    public function getAllCustomerVisitsLog($selectParams)
    {
        
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        
        $returnData = [
            'data'  => [],
            'total' => 0,
        ];
        
        $whereSql = '';
        if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])) {
            $where = empty($whereSql) ? ' where ' : ' AND ';
            $whereSql .= $where . ' a.createTime >=' . $selectParams['startTime'];
        }
        if (isset($selectParams['endTime']) && !empty($selectParams['endTime'])) {
            $where = empty($whereSql) ? ' where ' : ' AND ';
            $whereSql .= $where . ' a.createTime <= '. $selectParams['endTime'];
        }
        if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])) {
            $where = empty($whereSql) ? ' where ' : ' AND ';
            $whereSql .= $where .' FIND_IN_SET('.$selectParams['categoryId'].',b.categoryPath)';
        }
        if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
            $where = empty($whereSql) ? ' where ' : ' AND ';
            $whereSql .= $where . ' a.customerId = '. $selectParams['customerId'];
        }
        //数据域查询
        $objMBaseModel = new MBaseModel($this->enterpriseId,$this->userCenterId);
        $whereSql =  $objMBaseModel->getSalesManQueryParams($whereSql, ' c.salesManId ');
        if(!isset($where) && !empty($whereSql)){
            $whereSql = ' where '. $whereSql;
        }
        $sql = 'select a.* from qianniao_customer_visits_log_'.$this->enterpriseId.' as a LEFT JOIN qianniao_goods_basic_'.$this->enterpriseId.' as b on a.goodsId = b.id LEFT JOIN qianniao_customer_'.$this->enterpriseId.' as c on a.customerId = c.id  '.$whereSql.' order by createTime desc limit '.$offset.','.$limit;
        $dbResult = $this->objDCustomerVisitsLog->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomerVisitsLog->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success($returnData);
        }
    
        $sql = 'select count(*)as total from qianniao_customer_visits_log_'.$this->enterpriseId.' as a LEFT JOIN qianniao_goods_basic_'.$this->enterpriseId.' as b on a.goodsId = b.id LEFT JOIN qianniao_customer_'.$this->enterpriseId.' as c on a.customerId = c.id'.$whereSql;
        $dbTotalResult = $this->objDCustomerVisitsLog->query($sql);
        if ($dbTotalResult === false) {
            return ResultWrapper::fail($this->objDCustomerVisitsLog->error(), ErrorCode::$dberror);
        }
        
        $return = [
            'data'  => $this->format($dbResult),
            'total' => $dbTotalResult[0]['total'],
        ];
        return ResultWrapper::success($return);
    }
    
}