<?php
/**
 * 客户管理模块
 * Created by PhpStorm.
 * User: haoren
 * Date: 2020/10/30
 * Time: 14:02
 */

namespace JinDouYun\Model\Customer;

use Exception;

use JinDouYun\Dao\Customer\DCustomerCommunication;
use JinDouYun\Dao\Enterprise\DEnterprise;
use JinDouYun\Dao\Finance\DReceive;
use JinDouYun\Dao\Finance\DReceived;
use JinDouYun\Dao\Finance\DReceivedIndex;
use JinDouYun\Dao\Finance\DReceiveReceiptIndex;
use JinDouYun\Dao\Shop\DShop;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Controller\Common\Logger;

use JinDouYun\Dao\Integral\DIntegralRule;
use JinDouYun\Dao\Customer\DCustomer;
use JinDouYun\Dao\Customer\DCustomerBalanceTurnover;
use JinDouYun\Dao\Customer\DCustomerRechargeRecord;
use JinDouYun\Dao\Customer\DCustomerIntegralDesc;
use JinDouYun\Dao\UserCenter\DUserCenter;
use JinDouYun\Dao\Enterprise\DUserBindEnterprise;
use JinDouYun\Dao\Stock\DReservoirArea;
use JinDouYun\Dao\Department\DStaff;

use JinDouYun\Model\UserCenter\MUserCenterRegister;
use JinDouYun\Model\SysAreaChina\MSysAreaChina;
use JinDouYun\Model\Shop\MShop;
use JinDouYun\Model\Department\MDepartment;
use JinDouYun\Model\Department\MStaff;
use JinDouYun\Model\System\MCustomerSource;
use JinDouYun\Model\System\MBasicSetup;
use JinDouYun\Model\MBaseModel;
use JinDouYun\Model\Enterprise\MEnterprise;
use JinDouYun\Model\Finance\MCustomerBalanceDetail;
use JinDouYun\Model\Goods\MGoodsCollect;
use JinDouYun\Model\Market\MUserCoupon;
use JinDouYun\Model\Market\MVipCard;
use JinDouYun\Model\Order\MOrder;
use JinDouYun\Model\Stock\MReservoirArea;
use JinDouYun\Model\System\MPaymentSetting;

use JinDouYun\Cache\CustomerCache;
use JinDouYun\Cache\OverviewCache;
use JinDouYun\Cache\SystemCache;

use Util\Common\ChineseCharacter;
use Util\WeiXin\Pay;
use const Grpc\STATUS_ABORTED;

class MCustomer extends MBaseModel
{

    private $objDCustomer;
    private $objMCustomerContact;
    private $objDUserCenter;
    private $objDCustomerBalanceTurnover;
    private $objDCustomerRechargeRecord;
    private $objMShop;
    private $objMDepartment;
    private $objMStaff;
    private $objMCustomerSource;
    private $objDUserBindEnterprise;
    private $objCustomerCache;
    private $objOverviewCache;
    private $objMShippingAddress;
    private $objDCustomerIntegralDesc;
    private $cutTable = 1;//客户按照企业id分表
    private $enterpriseId;
    private $userCenterId;

    public function __construct($enterpriseId, $userCenterId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        parent::__construct($this->enterpriseId, $this->userCenterId);

        $this->objMCustomerContact = new MCustomerContact($enterpriseId, $userCenterId);
        $this->objMShop = new MShop($enterpriseId, $userCenterId);
        $this->objMDepartment = new MDepartment($enterpriseId);
        $this->objMStaff = new MStaff($enterpriseId, $userCenterId);
        $this->objDCustomerIntegralDesc = new DCustomerIntegralDesc();
        $this->objMCustomerSource = new MCustomerSource($enterpriseId);
        $this->objMShippingAddress = new MShippingAddress($enterpriseId);
        $this->objCustomerCache = new CustomerCache();
        $this->objOverviewCache = new OverviewCache();
        $this->objDCustomerBalanceTurnover = new DCustomerBalanceTurnover();
        $this->objDCustomerBalanceTurnover->setTable('qianniao_customer_balance_turnover_'.$enterpriseId);
        $this->objDCustomerRechargeRecord = new DCustomerRechargeRecord();
        $this->objDCustomerRechargeRecord->setTable('qianniao_customer_recharge_record_'.$enterpriseId);
        $this->objDCustomerIntegralDesc->setTable('qianniao_customer_integral_desc_'.$enterpriseId);

        $this->objDCustomer = new DCustomer('default');
        $this->objDUserCenter = new DUserCenter('default');
        $tableName = $this->objDCustomer->getTableName($this->objDCustomer->get_Table(), $this->enterpriseId, $this->cutTable);
        $this->objDCustomer->setTable($tableName);
        $this->objDUserBindEnterprise = new DUserBindEnterprise('default');
        $this->objDCustomer->setSearchIndex('customer_search')->setType('customer');
       }

    /**
     * 添加客户
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addCustomer($params)
    {
        $beginStatus = $this->objDCustomer->beginTransaction();
        $contact = $params['contact'];
        unset($params['contact']);
        
        if(!isMobile($params['mobile'])){
            return ResultWrapper::fail('该手机号格式有问题', ErrorCode::$mobileishaved);
        }
        //判断账号密码是否在该企业下被注册过
        $objMUserCenterRegister = new MUserCenterRegister();
        $isRegister = $objMUserCenterRegister->mobileIsRegister($params['mobile'], $this->enterpriseId);
        if ($isRegister) {
            $this->objDCustomer->rollBack();
            return ResultWrapper::fail('该手机号已经被注册', ErrorCode::$mobileishaved);
        }


        //添加userCenter表
        $dbResult = $this->objDUserCenter->get(['mobile' => $params['mobile']]);
        if($dbResult === false){
            $this->objDCustomer->rollBack();
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }

        if(empty($dbResult)){
            $userCenterData = [
                'mobile'     => $params['mobile'],
                'source'     => StatusCode::$source['manage'],
                'isCustomer' => StatusCode::$customerType['customer'],
                'createTime' => time(),
                'updateTime' => time(),
            ];
            $userCenterId = $this->objDUserCenter->insert($userCenterData);

            if ($userCenterId === false) {
                $this->objDCustomer->rollBack();
                return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
            }
        }else{
            $userCenterId = $dbResult['id'];
        }
        $params['enterpriseId'] = $this->enterpriseId;
        $params['userCenterId'] = $userCenterId;
        //添加负责人电话
        $params['managerMobile'] = $params['mobile'];
        unset($params['mobile']);
        unset($params['password']);
        //后台添加客户 状态为已审核
        $params['status'] = StatusCode::$auditStatus['auditPass'];
        $objChineseCharacter = new ChineseCharacter();
        $condition = $objChineseCharacter->getInitials(trim($params['name']));
        $params['condition'] = $condition;
        $customerId = $this->objDCustomer->insert($params);
        if ($customerId === false) {
            $this->objDCustomer->rollBack();
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

        //增加客户公司关系表
        $UserBindEnterpriseData = [
            'userCenterId' => $userCenterId,
            'roleType'     => StatusCode::$roleType['customer'],
            'enterpriseId' => $this->enterpriseId,
            'updateTime'   => time(),
            'createTime'   => time(),
        ];
        $dbResult = $this->objDUserBindEnterprise->insert($UserBindEnterpriseData);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }

        if(!empty($contact)){
            //保存联系人信息
            $customerContactData = [
                'customerId'   => $customerId,
                'name'         => isset($contact['name']) ? $contact['name'] : '',
                'mobile'       => isset($contact['mobile']) ? $contact['mobile'] : '',
                'provinceCode' => isset($contact['provinceCode']) ? $contact['provinceCode'] : '',
                'cityCode'     => isset($contact['cityCode']) ? $contact['cityCode'] : '',
                'districtCode' => isset($contact['districtCode']) ? $contact['districtCode'] : '',
                'address'      => isset($contact['address']) ? $contact['address'] : '',
                'deleteStatus' => StatusCode::$standard,
                'createTime'   => time(),
                'updateTime'   => time()
            ];

            $result = $this->objMCustomerContact->addCustomerContact($customerContactData);
            if ($result->isSuccess() === false) {
                $this->objDCustomer->rollBack();
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }

            //把联系人信息保存为收货地址
            $ShippingAddressData = [
                'name'          => $customerContactData['name'],
                'mobile'        => $customerContactData['mobile'],//客户收货手机号
                'provinceCode'  => $customerContactData['provinceCode'],//客户收货地址省份编码
                'cityCode'      => $customerContactData['cityCode'],//客户收货地址城市编码
                'districtCode'  => $customerContactData['districtCode'],//客户收货地址区县编码
                'address'       => $customerContactData['address'],//详细收货地址
                'deleteStatus'  => StatusCode::$standard,
                'defaultStatus' => StatusCode::$standard,
                'customerId'    => $customerId,
                'extend'        => json_encode(['createType' => StatusCode::$roleType['admin']]),
                'updateTime'    => time()
            ];
            $result = $this->objMShippingAddress->addShippingAddress($ShippingAddressData);
            if ($result->isSuccess() === false) {
                $this->objDCustomer->rollBack();
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
        }

        $beginStatus && $this->objDCustomer->commit();
        //self::updateEsData($customerId);
        return ResultWrapper::success($customerId);
    }

    /**
     * 获取指定客户信息，获取联系人信息
     * @param $CustomerIds
     * @return ResultWrapper
     * @throws Exception
     */
    public function getCustomerInfo($CustomerIds)
    {
        $dbResult = $this->objDCustomer->get_by('id', $CustomerIds);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        } else {
            $dbResult = self::format([$dbResult]);
            $dbResult = array_shift($dbResult);
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 获取指定客户信息，获取客戶信息
     * @param $CustomerIds
     * @return ResultWrapper
     * @throws Exception
     */
    public function getCustomerName($CustomerIds)
    {
        $dbResult = $this->objDCustomer->get_by('id', $CustomerIds, 'id,name,managerMobile');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取客户
     * @param $where
     * @param string $field
     * @param bool $isOne
     * @param bool $isFormat
     * @return ResultWrapper
     */
    public function getCustomerData($where, $field = '*', $isOne = true, $isFormat = false)
    {
        if($isOne){
            $dbResult = $this->objDCustomer->get($where, $field);
        }else{
            $dbResult = $this->objDCustomer->select($where, $field);
        }
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        if($isFormat){
            $dbResult = self::format($dbResult);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取客户
     * @param $sql
     * @return ResultWrapper
     */
    public function getCustomerDataByQuery($sql)
    {
        $dbResult = $this->objDCustomer->query($sql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 处理客户联系人信息
     * @param $data
     * @param bool $flag 二维数组传true
     * @return array
     * @throws Exception
     */
    public function format($data)
    {
        if (!$data) {
            return $data;
        }

        $objMSysAreaChina = new MSysAreaChina();
        $customerIds = [];
        $userCenterIds = [];
        $shopIds = [];
        $departmentIds = [];
        $recommenderCustomerIds = [];
        $staffIds = [];
        $customerSourceIds = [];//客户类型
        $reservoirAreaIds = []; // 分拣区id
        foreach ($data as $key => $customer) {
            !empty($customer['id']) && $customerIds[] = $customer['id'];
            !empty($customer['userCenterId']) && $userCenterIds[] = $customer['userCenterId'];
            !empty($customer['shopId']) && $shopIds[] = $customer['shopId'];
            !empty($customer['departmentId']) && $departmentIds[] = $customer['departmentId'];
            !empty($customer['salesManId']) && $staffIds[] = $customer['salesManId'];
            if (isset($customer['type'])) {
                $customerSourceIds[] = $customer['type'];
            }
            if(isset($customer['sortingId'])){
                $reservoirAreaIds = $customer['sortingId'];
            }

            if( empty($customer['recommenderId']) ) continue;
            if($customer['recommenderType'] == StatusCode::$roleType['customer']){
                !empty($customer['recommenderId']) && $recommenderCustomerIds[] = $customer['recommenderId'];
            }else{
                !empty($customer['recommenderId']) && $staffIds[] = $customer['recommenderId'];
            }
        }
        //获取用户账号信息
        $userCenters = [];
        if ($userCenterIds) {
            $userCenterDatas = $this->objDUserCenter->select(array_unique(array_filter($userCenterIds)), 'id,mobile,source,createTime');
            foreach ($userCenterDatas as $userCenterData){
                $userCenters[$userCenterData['id']] = $userCenterData;
            }
        }
        
        //获取联系人信息
        $customerContacts = [];
        if ($customerIds) {
            $contacts = $this->objMCustomerContact->getContactInfoById($customerIds);
            foreach ($contacts as $contact)
                $customerContacts[$contact['customerId']][] = $contact;
        }

        //获取店铺
        $shops = [];
        if ($shopIds) {
            $shopData = $this->objMShop->getShopName(array_unique(array_filter($shopIds)));
            foreach ($shopData as $shop)
                $shops[$shop['id']] = $shop['name'];
        }

        //获取部门
        $departments = [];
        if ($departmentIds) {
            $departmentData = $this->objMDepartment->departmentDataByDepartmentIds(array_unique(array_filter($departmentIds)));
            foreach ($departmentData as $department)
                $departments[$department['id']] = $department['departmentName'];
        }

        //获取业务员
        $staffs = [];
        if ($staffIds) {
            $staffData = $this->objMStaff->getStaffDataByStaffIds(array_unique(array_filter($staffIds)));
            foreach ($staffData as $staff)
                $staffs[$staff['id']] = $staff['staffName'];
        }

        // 根据客户ids批量获取客户名称
        $customerIdBindName = [];
        if( !empty($recommenderCustomerIds) ){
            $dbResult = $this->objDCustomer->select($recommenderCustomerIds, 'id,name');
            if($dbResult !== false){
                foreach ($dbResult as $key => $value){
                    $customerIdBindName[$value['id']] = $value['name'];
                }
            }
        }

        //查询客户类型
        $customerSourceArr = [];
        if ($customerSourceIds) {
            $customerSourceData = $this->objMCustomerSource->getCustomerSourceNameByIds($customerSourceIds);
            if ($customerSourceData->isSuccess()) {
                $customerSourceArray = $customerSourceData->getData();
                foreach ($customerSourceArray as $customerSource)
                    $customerSourceArr[$customerSource['id']] = $customerSource['name'];
            }
        }


        foreach ($data as &$customer) {
            $customer['customerDays'] = intval((time() - $customer['createTime']) / 86400);//注册天数
            $customer['code'] = createCode(StatusCode::$code['customer']['prefix'], $customer['id'], StatusCode::$code['customer']['length']);
            $customer['taglib'] = isset($customer['taglib']) ? json_decode($customer['taglib'], true) : [];
            $customer['extend'] = isset($customer['extend']) ? json_decode($customer['extend'], true) : [];
            //处理客户地址
            if (isset($customer['provinceCode']) && isset($customer['cityCode']) && isset($customer['districtCode'])) {
                $areaName = $objMSysAreaChina->getNameByCode([
                    $customer['provinceCode'],
                    $customer['cityCode'],
                    $customer['districtCode']
                ]);
                $customer['area']['provinceName'] = isset($areaName[$customer['provinceCode']]) ? $areaName[$customer['provinceCode']] : '';
                $customer['area']['cityName'] = isset($areaName[$customer['cityCode']]) ? $areaName[$customer['cityCode']] : '';
                $customer['area']['districtName'] = isset($areaName[$customer['districtCode']]) ? $areaName[$customer['districtCode']] : '';
                $customer['area']['address'] = getArrayItem($customer, 'address');
            }

            //处理店铺
            $customer['shopName'] = isset($shops[$customer['shopId']]) ? $shops[$customer['shopId']] : '';
            //处理销售部门
            $customer['departmentName'] = isset($departments[$customer['departmentId']]) ? $departments[$customer['departmentId']] : '';
            //处理业务员
            $customer['salesManName'] = isset($staffs[$customer['salesManId']]) ? $staffs[$customer['salesManId']] : '';
            //处理客户类型
            $customer['customerType'] = isset($customerSourceArr[$customer['type']]) ? $customerSourceArr[$customer['type']] : '';
            $customer['mobile'] = '';
            $customer['password'] = '';
            $customer['registerTime'] = '';
            $customer['source'] = '';
            //处理注册手机号/时间/来源
            if (isset($userCenters[$customer['userCenterId']]) && $userCenters[$customer['userCenterId']]) {
                $userCenter = $userCenters[$customer['userCenterId']];
                $customer['mobile'] = ($this->enterpriseId == 4) ? substr_replace($userCenter['mobile'],'****',3,4) : $userCenter['mobile'];
                $customer['registerTime'] = date('Y-m-d H:i:s', $userCenter['createTime']);
                $customer['source'] = array_search($userCenter['source'], StatusCode::$source);
            }
            $defaultContact[] = [
                'name'   => '',
                'mobile' => ''
            ];
            $customer['contact'] = isset($customerContacts[$customer['id']]) ? $customerContacts[$customer['id']] : $defaultContact;

            // 处理推荐人
            if(isset($customer['recommenderType'])){
                if($customer['recommenderType'] == StatusCode::$roleType['customer']){
                    $customer['recommenderName'] = isset($customerIdBindName[$customer['recommenderId']]) ? $customerIdBindName[$customer['recommenderId']] : '';
                }else{
                    $customer['recommenderName'] = isset($staffs[$customer['recommenderId']]) ? $staffs[$customer['recommenderId']] : '';
                }
            }
        }
        return $data;
    }

    /**
     * 处理时间戳
     * @param $timestamp
     * @param string $type
     * @return false|string
     */
    function time_format($timestamp, $type = 'Y-m-d')
    {
        $time = explode('-', $timestamp);
        if (count($time) > 1) {
            return $timestamp;
        }
        return date($type, $timestamp);
    }

    /**
     * 编辑客户
     * 事务修改联系人信息
     * @param int|array $params 修改客户的数据
     *
     * @return ResultWrapper
     * @throws Exception
     */
    public function editCustomer($params)
    {
        if (empty($params['id'])) {
            return ResultWrapper::fail('没有指定要修改的客户id', ErrorCode::$paramError);
        }

        $updateCustomerId = $params['id'];
        unset($params['id']);
        $contact = $params['contact'];
        unset($params['contact']);


        $beginStatus = $this->objDCustomer->beginTransaction();
        //修改客户账号密码
        $userCenterId = $this->objDCustomer->get_field('userCenterId', 'id = ' . $updateCustomerId);

        $userCenterInfo = $this->objDUserCenter->get_by('id', $userCenterId, '*');
        if ($userCenterInfo === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }

        //手机号不应该随意修改
/*        if (isset($userCenterInfo['mobile']) && isset($userCenterInfo['password'])) {
            //比对手机号和密码有没有发生变化
            $updateUserCenterData = [];
            if ($params['mobile'] != $userCenterInfo['mobile']) {
                $updateUserCenterData['mobile'] = $params['mobile'];
            }
            //如果输入了密码，则判断密码与原来的密码是否一致
            if ($params['password'] && password_verify($params['password'], $userCenterInfo['password']) === false) {
                $updateUserCenterData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
            }

            if (!empty($updateUserCenterData)) {
                $userCenterResult = $this->objDUserCenter->update($updateUserCenterData, $userCenterId);
                if ($userCenterResult === false) {
                    return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
                }
            }
        }*/
        unset($params['mobile']);
        unset($params['password']);

        if(isset($params['name'])){
             $objChineseCharacter = new ChineseCharacter();
             $condition = $objChineseCharacter->getInitials(trim($params['name']));
             $params['condition'] = $condition;
        }
        // 修改手机号
//        $params['managerMobile'] = $params['mobile'];
        //修改客户基本信息
        $dbResult = $this->objDCustomer->update($params, $updateCustomerId);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

        $customerContactData = [
            'name'         => isset($contact['name']) ? $contact['name'] : '',
            'mobile'       => isset($contact['mobile']) ? $contact['mobile'] : '',
            'provinceCode' => isset($contact['provinceCode']) ? $contact['provinceCode'] : '',
            'cityCode'     => isset($contact['cityCode']) ? $contact['cityCode'] : '',
            'districtCode' => isset($contact['districtCode']) ? $contact['districtCode'] : '',
            'address'      => isset($contact['address']) ? $contact['address'] : '',
            'updateTime'   => time()
        ];

        //修改联系人信息
        if (isset($contact['id']) && !empty($contact['id'])) {
            $customerContactData['id'] = $contact['id'];
            $dbResult1 = $this->objMCustomerContact->editCustomerContact($customerContactData);
        } else {
            $customerContactData['customerId'] = $updateCustomerId;
            $customerContactData['createTime'] = time();
            $customerContactData['deleteStatus'] = StatusCode::$standard;
            $dbResult1 = $this->objMCustomerContact->addCustomerContact($customerContactData);
        }
        if ($dbResult1->isSuccess() === false) {
            $this->objDCustomer->rollBack();
            return ResultWrapper::fail($dbResult1->getData(), $dbResult1->getErrorCode());
        }

        $objCustomerCache = new CustomerCache();
        $objCustomerCache->delCustomerData($this->enterpriseId, $updateCustomerId);
        $objCustomerCache->delCustomerUserData($this->enterpriseId, $userCenterId);

        $beginStatus && $this->objDCustomer->commit();
        //self::updateEsData($updateCustomerId);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 后台批量分配部门及业务员
     * @param array $params
     * @return ResultWrapper
     */
    public function batchEditCustomer(array $params)
    {
        $dbResult = $this->objDCustomer->update(
            [
                'departmentId' => $params['departmentId'],
                'salesManId'   => $params['salesManId'],
                'updateTime'   => time()
            ],
            ['id' => $params['ids']]
        );
        if ($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success("操作成功");
    }

    //前台修改客户信息
    public function editCustomerInfo($params)
    {
        $userCenterId = $params['userCenterId'];
        unset($params['userCenterId']);

        $updateCustomerId = self::getCustomerIdByUserCenterId($userCenterId);
        if (empty($updateCustomerId)) {
            return ResultWrapper::fail('没有指定要修改的客户id', ErrorCode::$paramError);
        }


        $contact = $params['contact'];
        unset($params['contact']);

        //状态 为已审核
        $params['status'] = StatusCode::$auditStatus['auditPass'];
        $params['auditFailReason'] = '';
        //查询系统设置
        $objMBasicSetup = new MBasicSetup($this->enterpriseId);
        $modelResult = $objMBasicSetup->getBasicSetup();
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $system = $modelResult->getData();
        //判断完善资料内容
        if (isset($system['basicData']) && isset($system['basicData']['finishData']) && $system['basicData']['finishData'] == StatusCode::$standard) {
            //如果完善资料 限制资料提交内容
            if(!isset($params['name']) || empty($params['name'])){
                return ResultWrapper::fail('请输入真实名称', ErrorCode::$paramError);
            }
        }
        //判断系统设置审核
        if (isset($system['basicData']) && isset($system['basicData']['personnelReview']) && $system['basicData']['personnelReview'] == StatusCode::$standard) {
            //如果开启客户审核 把状态改为待审核
            $params['status'] = StatusCode::$auditStatus['auditing'];
        }

        //修改客户基本信息
        $dbResult = $this->objDCustomer->update($params, $updateCustomerId);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

        $objCustomerCache = new CustomerCache();
        $objCustomerCache->delCustomerUserData($this->enterpriseId, $userCenterId);
        $objCustomerCache->delCustomerData($this->enterpriseId, $updateCustomerId);
        //修改联系人信息
        if (isset($contact['id'])) {
            $contact['updateTime'] = time();
            $dbResult1 = $this->objMCustomerContact->editCustomerContact($contact);
        } else {
            $dbResult1 = true;
            if (
                (isset($contact['provinceCode']) && !empty($contact['provinceCode'])) ||
                (isset($contact['cityCode']) && !empty($contact['cityCode'])) ||
                (isset($contact['districtCode']) && !empty($contact['districtCode'])) ||
                (isset($contact['address']) && !empty($contact['address'])) ||
                (isset($contact['name']) && !empty($contact['name'])) ||
                (isset($contact['mobile']) && !empty($contact['mobile']))
            ) {
                $contact['customerId'] = $updateCustomerId;
                $contact['createTime'] = time();
                $contact['updateTime'] = time();
                $dbResult1 = $this->objMCustomerContact->addCustomerContact($contact);
            }
        }
        //获取客户所属的商铺
        /*$shopId = $this->objMShop->getShopIdByArea($params);
        if ($shopId) {
            $this->objDCustomer->update(['shopId' => $shopId], $updateCustomerId);
        }*/

        if (!$dbResult1->isSuccess()) {
            $this->objDCustomer->rollBack();
            return ResultWrapper::fail($dbResult1->getData(), $dbResult1->getErrorCode());
        } else {
            $this->objDCustomer->commit();
//            $_id = self::createEsDocumentId($updateCustomerId);
//            $result = $this->objDCustomer->esupdateTypeFieldVaule($params, $_id);
            return ResultWrapper::success($params['status']);
        }
    }

    private function createEsDocumentId($customerId)
    {
        return 'EnterpriseId_' . $this->enterpriseId . '_CustomerId_' . $customerId;
    }

    /**
     * 更新ES
     * @param $customerId
     * @throws Exception
     */
    public function updateEsData($customerId)
    {
        //每次查询一遍，避免客户在数据库存在，在ES中不存在的情况
        $userCenterId = $this->objDCustomer->get_field('userCenterId', 'id = ' . $customerId);
        $userCenterInfo = $this->objDUserCenter->get_by('id', $userCenterId, '*');

        $customerInfo = $this->objDCustomer->get_by('id', $customerId);
        if ($customerInfo !== false) {
            $customerInfo['shopName'] = $this->objMShop->getShopNameById($customerInfo['shopId']);
            $customerInfo['departmentName'] = $this->objMDepartment->getNameById($customerInfo['departmentId']);
            $salesManDate = $this->objMStaff->getNameById($customerInfo['salesManId']);
            $customerInfo['salesManName'] = isset($salesManDate['staffName']) ? $salesManDate['staffName']:'';
            $objMSysAreaChina = new MSysAreaChina();
            if (isset($customerInfo['provinceCode']) && isset($customerInfo['cityCode']) && isset($customerInfo['districtCode'])) {
                $areaName = $objMSysAreaChina->getNameByCode([
                    $customerInfo['provinceCode'],
                    $customerInfo['cityCode'],
                    $customerInfo['districtCode']
                ]);
                $customerInfo['provinceName'] = isset($areaName[$customerInfo['provinceCode']]) ? $areaName[$customerInfo['provinceCode']] : '';
                $customerInfo['cityName'] = isset($areaName[$customerInfo['cityCode']]) ? $areaName[$customerInfo['cityCode']] : '';
                $customerInfo['districtName'] = isset($areaName[$customerInfo['districtCode']]) ? $areaName[$customerInfo['districtCode']] : '';
            }

            $customerInfo['tag'] = $customerInfo['tag'] ? json_decode($customerInfo['tag'], true) : [];
            $customerInfo['mobile'] = $userCenterInfo['mobile'];
            $customerInfo['source'] = $userCenterInfo['source'];
            $customerInfo['contact'] = $this->objMCustomerContact->getContactInfoById($customerId);
            if (!empty($customerInfo['latitude']) && !empty($customerInfo['longitude'])) {
                $customerInfo['location'] = [
                    'lat' => $customerInfo['latitude'],
                    'lon' => $customerInfo['longitude']
                ];
            }
            unset($customerInfo['latitude']);
            unset($customerInfo['longitude']);
            $_id = self::createEsDocumentId($customerId);
            $result = $this->objDCustomer->addUpSearchIndexDocument($customerInfo, $_id);

            if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
                // echo "es操作成功";die;
            }
            //echo "es操作失败";
        }
    }

    /**
     * 删除客户
     *
     * @param array $userCenterIds 要删除的客户id
     * @return ResultWrapper
     * @throws Exception
     */
    public function delCustomer($userCenterIds)
    {
        if (empty($userCenterIds)) {
            return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
        }
        $deleteDate =[
            'userCenterId'=> $userCenterIds,
        ];
        
        $dbResult = $this->objDCustomer->update(['deleteStatus' => StatusCode::$delete], $deleteDate);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
       
        unset($deleteDate);
        $objDUserBindEnterprise = new DUserBindEnterprise();
        $deleteDate =[
            'userCenterId'=> $userCenterIds,
            'enterpriseId'=> $this->enterpriseId
        ];
        $dbResult = $objDUserBindEnterprise->delete($deleteDate);
        if ($dbResult === false) {
            return ResultWrapper::fail($objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }
        //在ES删除
        // $_id = self::createEsDocumentId($delCustomerIds);
        //  $this->objDCustomer->esdeleteTypeDocument($_id);
            return ResultWrapper::success($dbResult);
        
    }

    /**
     * 客户启用和禁用
     * @param array $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function updateCustomerStatus($params)
    {
        $dbResult = $this->objDCustomer->get($params['id']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $customerData = $dbResult;
        unset($dbResult);
        if(empty($customerData)){
            return ResultWrapper::fail('修改客户不存在', ErrorCode::$paramError);
        }

        $dbResult = $this->objDCustomer->update(['enableStatus' => $params['enableStatus']], $params['id']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

        //self::updateEsData($params['id']);
        $objCustomerCache = new CustomerCache();
        $objCustomerCache->delCustomerData($this->enterpriseId, $params['id']);
        $objCustomerCache->delCustomerUserData($this->enterpriseId, $customerData['userCenterId']);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 修改客户
     * @param $update
     * @param $where
     * @return ResultWrapper
     * @throws Exception
     */
    public function updateCustomer($update, $where)
    {
        if(empty($where)){
            return ResultWrapper::fail('修改客户参数错误', ErrorCode::$paramError);
        }
        $where['deleteStatus'] = StatusCode::$standard;
        $dbResult = $this->objDCustomer->get($where);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $customerData = $dbResult;
        unset($dbResult);
        if(empty($customerData)){
            return ResultWrapper::fail('修改客户不存在', ErrorCode::$paramError);
        }

        $dbResult = $this->objDCustomer->update($update, $where);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

//        self::updateEsData($customerData['id']);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 客户审核和未审核
     * @param array $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function updateCustomerCheckStatus($params)
    {
        $data = [
            'status'          => $params['status'],
            'auditFailReason' => ''
        ];
        if ($params['status'] == StatusCode::$auditStatus['auditNotPass']) {
            $data['auditFailReason'] = $params['reason'];
        }
        $dbResult = $this->objDCustomer->update($data, $params['id']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        } else {
            /*//redis添加客户总数
            $this->objCustomerCache->incrCustomerNum($this->enterpriseId);
            //近一个月注册的用户
            $this->objCustomerCache->incrCustomer($params['id'], $this->enterpriseId);
            //添加今日新增客户数
            $this->objOverviewCache->saveBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', 1);
            $shopId = $this->objDCustomer->get_field('shopId', $params['id']);
            if ($shopId) {
                $this->objOverviewCache->saveBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', 1, $shopId);
            }*/
            $customerData = $this->objDCustomer->get($params['id']);
            self::setCustomerCache($customerData['shopId']);//缓存用户数据
//            self::updateEsData($params['id']);

            $objCustomerCache = new CustomerCache();
            $objCustomerCache->delCustomerData($this->enterpriseId, $params['id']);
            $objCustomerCache->delCustomerUserData($this->enterpriseId, $customerData['userCenterId']);
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     *
     * 缓存用户数据
     * @param int $shopId
     * @return ResultWrapper
     */
    public function setCustomerCache($shopId = false)
    {
        $result = self::querySelectCondition(['status'=>StatusCode::$auditStatus['auditPass']]);
        if (!$result->isSuccess()){
            return ResultWrapper::fail($result->getData(),$result->getErrorCode());
        }
        $total =(int) $result->getData();
        //缓存客户总数
        $this->objCustomerCache->setCustomerNum($this->enterpriseId,$total);

        //今日新增客户数
        $todayStart = date('Y-m-d 00:00:00', time());
        $todayEnd = date('Y-m-d 23:59:59', time());
        $todayResult = self::querySelectCondition(
            [
                //'status'=>StatusCode::$auditStatus['auditPass'],
                'createTime'=>[
                    'lt'=> strtotime($todayStart),
                    'gt'=> strtotime($todayEnd)
                ]
            ]
        );
        if (!$result->isSuccess()){
            return ResultWrapper::fail($result->getData(),$result->getErrorCode());
        }
        $todayCustomerNum =(int) $todayResult->getData();
        $this->objOverviewCache->setBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $todayCustomerNum);

        //对应店铺
        if ($shopId) {
            $this->objOverviewCache->setBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $todayCustomerNum, $shopId);
        }
    }


    /**
     * @param $condition
     * @param bool $total
     * @return ResultWrapper
     */
    public function querySelectCondition($condition,$total = true)
    {
        $field = 'id,status';
        $sql = 'select '.$field.' from qianniao_customer_'.$this->enterpriseId.' 
                where deleteStatus = '.StatusCode::$standard;
        if (isset($condition['status']) && !empty($condition['status'])){
            $sql .= ' and status = '.StatusCode::$auditStatus['auditPass'];
        }
        if (isset($condition['createTime']) && !empty($condition['createTime'])){
            $sql .= ' and createTime BETWEEN '.$condition['createTime']['lt'] .' and '.$condition['createTime']['gt'];
        }
        $dbResult = $this->objDCustomer->query($sql);
        if ($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success(count((array)$dbResult));
    }

    /**
     * 不同状态下用户的数量
     * @return ResultWrapper
     * @throws Exception
     */
    public function getNumberUser()
    {
        $field = 'COUNT(id) AS totalCount, SUM(CASE WHEN enableStatus='.StatusCode::$standard.
            ' and status ='.StatusCode::$auditStatus['auditPass'].' THEN 1 ELSE 0 END) AS valid,SUM(CASE WHEN enableStatus='.StatusCode::$delete.' OR status !='.StatusCode::$auditStatus['auditPass'].' THEN 1 ELSE 0 END) AS void';

        $sql = 'select '.$field.' from qianniao_customer_'.$this->enterpriseId.' 
                where deleteStatus = '.StatusCode::$standard;
        $dbResult = $this->objDCustomer->query($sql);

        if ($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success(reset($dbResult));
    }
    /**
     * 客户列表
     * @param array $params 过滤条件
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllCustomer($params)
    {
        $limit = $params['limit'];
        unset($params['limit']);
        $offset = $params['offset'];
        unset($params['offset']);
        $selectParams = 'deleteStatus = ' . StatusCode::$standard . ' AND enterpriseId = ' . $this->enterpriseId;

        if (!empty($params['keyword'])) {
            $selectParams .= ' AND (name LIKE "%' . $params['keyword'] . '%" or managerMobile LIKE "%' . $params['keyword'] . '%")';
        }

        if (!empty($params['type'])) {
            $selectParams .= ' AND type =' . $params['type'];
        }

        if (!empty($params['provinceCode'])) {
            $selectParams .= ' AND provinceCode =' . $params['provinceCode'];
        }

        if (!empty($params['cityCode'])) {
            $selectParams .= ' AND cityCode =' . $params['cityCode'];
        }

        if (!empty($params['districtCode'])) {
            $selectParams .= ' AND districtCode =' . $params['districtCode'];
        }

        if (isset($params['status'])) {
            if ($params['status'] == StatusCode::$auditStatus['completion']) {
                $selectParams .= ' AND status in (' . StatusCode::$auditStatus['completion'] . ',' . StatusCode::$auditStatus['auditNotPass'] . ')';
            } else {
                $selectParams .= ' AND status =' . $params['status'];
            }

        }

        if (!empty($params['enableStatus'])) {
            $selectParams .= ' AND enableStatus =' . $params['enableStatus'];
        }

        if (!empty($params['shopId'])) {
            $selectParams .= ' AND shopId =' . $params['shopId'];
        }

        if (!empty($params['departmentId'])) {
            $selectParams .= ' AND departmentId =' . $params['departmentId'];
        }

        if (!empty($params['salesManId'])) {
            $selectParams .= ' AND salesManId =' . $params['salesManId'];
        }

        if (!empty($params['start'])) {
            $selectParams .= ' AND createTime >=' . $params['start'];
        }

        if (!empty($params['end'])) {
            $selectParams .= ' AND createTime <=' . $params['end'];
        }
        $selectParams = parent::getSalesManQueryParams($selectParams);
        $dbResult = $this->objDCustomer->select($selectParams, '*', 'createTime desc', $limit, $offset);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        
        $total = $this->objDCustomer->count($selectParams);
        
        $return = [
            'data'  => self::format($dbResult),
            'total' => ($total) ? intval($total) : 0,
        ];
        return ResultWrapper::success($return);

    }

    /**
     * 获取企业下的所有客户余额
     *
     * @param array $selectParams 过滤条件
     *
     * @return ResultWrapper
     * @throws Exception
     */
    public function getCustomerMoney($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $where = 'deleteStatus=' . StatusCode::$standard . ' AND enterpriseId=' . $this->enterpriseId;
        if (isset($selectParams['id'])) {
            $where .= ' AND id=' . $selectParams['id'];
        }
        if (isset($selectParams['tag']) && $selectParams['tag'] == StatusCode::$standard) {
            //有财务纠纷
            $where .= ' AND (money != 0)';
        }
        if (isset($selectParams['tag']) && $selectParams['tag'] == StatusCode::$delete) {
            //无财务纠纷
            $where .= ' AND (money=0)';
        }
        $selectParams = parent::getSalesManQueryParams($where);
        $dbResult = $this->objDCustomer->select($selectParams, 'id AS customerId,name,money,memberBalance', 'createTime desc', $limit, $offset);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }



        foreach ($dbResult as $key => $value) {
            //获取销售金额，收款金额
            $saleMoney = 0;// 销售金额
            $collectionMoney = 0;// 收款金额

            $objReceiveTable = new DReceive('finance');
            $objReceivedTable = new DReceived('finance');

            $objReceiveIndexTable = new DReceiveReceiptIndex('finance');
            $objReceiveIndexTable->setTable('qianniao_receive_receipt_index_'.$this->enterpriseId);
            $objReceivedIndexTable = new DReceivedIndex('finance');
            $objReceivedIndexTable->setTable('qianniao_received_index_'.$this->enterpriseId);

            $receiveIndexSql = 'select * from '.$objReceiveIndexTable->get_Table().' WHERE customerId='.$value['customerId'] .' AND offsetStatus='.StatusCode::$standard;
            $receiveIndexDate = $objReceiveIndexTable->query($receiveIndexSql);
            if($receiveIndexDate === false){
                return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
            }

            if(!empty($receiveIndexDate)){
                foreach ($receiveIndexDate as $receiveKey => $receiveValue){
                    $suffix = date('Y', $receiveValue['createTime']) . '_' . ceil(date('m', $receiveValue['createTime']) / 3);
                    $objReceiveTable->setTable('qianniao_receive_receipt_' . $this->enterpriseId . '_' . $suffix);
                    $receiveDate = $objReceiveTable->get($receiveValue['id']);
                    $saleMoney = bcadd($saleMoney,$receiveDate['receiveMoney'],2);
                }
            }

            $receivedIndexSql = 'select * from '.$objReceivedIndexTable->get_Table().' WHERE customerId='.$value['customerId'] .' AND offsetStatus='.StatusCode::$standard;
            $receivedIndexDate = $objReceivedIndexTable->query($receivedIndexSql);
            if($receiveIndexDate === false){
                return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
            }
            if(!empty($receivedIndexDate)){
                foreach ($receivedIndexDate as $receivedKey => $receivedValue){
                    $objReceivedTable->setTable('qianniao_received_' . $this->enterpriseId . '_' . date('Y', $receivedValue['createTime']) . '_' . ceil(date('m', $receivedValue['createTime']) / 3));
                    $receivedDate = $objReceivedTable->get($receivedValue['id']);
                    $collectionMoney = bcadd($collectionMoney,isset($receivedDate['totalFinalMoney']) ? $receivedDate['totalFinalMoney'] :0,2);
                }
            }


            $dbResult[$key]['openingBalance'] = $value['money'];
//            $dbResult[$key]['interimBalance'] = 0;
            $dbResult[$key]['saleMoney'] = $saleMoney;
            $dbResult[$key]['collectionMoney'] = $collectionMoney;
            $dbResult[$key]['endingBalance'] = $value['money'];
            $dbResult[$key]['memberBalance'] = $value['memberBalance'];
            unset($dbResult[$key]['money']);
        }

        $total = $this->objDCustomer->count($selectParams);

        $return = [
            'data'  => $dbResult,
            'total' => ($total) ? intval($total) : 0,
        ];

        return ResultWrapper::success($return);

    }

    /**
     * 查询客户标签
     * @param $id
     * @return array
     */
    public function getCustomerTag($id)
    {
        $dbResult = $this->objDCustomer->get($id, 'tag');
        return $dbResult;
    }

    /**
     * 添加客户标签
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addCustomerTag($params)
    {
        $tagResult = $this->getCustomerTag($params['id']);

        //判断标签是否已经存在
        $tags = isset($tagResult['tag']) ? json_decode($tagResult['tag'], true) : [];
        if ($tags && in_array($params['tag'], $tags)) {
            return ResultWrapper::fail("客户标签已存在", ErrorCode::$resubmit);
        }

        $tags[] = $params['tag'];
        $dbResult = $this->objDCustomer->update(['tag' => json_encode($tags)], $params['id']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        } else {
//            self::updateEsData($params['id']);
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 删除客户标签
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function delCustomerTag($params)
    {
        $tagResult = $this->getCustomerTag($params['id']);
        //判断标签是否已经存在
        $tags = json_decode($tagResult['tag'], true);
        if (!$tags || !in_array($params['tag'], $tags)) {
            return ResultWrapper::fail("客户标签不存在", ErrorCode::$resubmit);
        }
        //标签存在，进行删除
        foreach ($tags as $key => $tag) {
            if ($tag == $params['tag']) {
                unset($tags[$key]);
            }
        }

        $dbResult = $this->objDCustomer->update(['tag' => json_encode($tags)], $params['id']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        } else {
//            self::updateEsData($params['id']);
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 搜索
     *
     * @param array $selectParams 过滤条件
     *
     * @return ResultWrapper
     * @throws Exception
     */
    public function search($selectParams)
    {
        $defaultDSL = [
            'from' => $selectParams['offset'],
            'size' => $selectParams['limit'],
            'sort' => [
                'createTime' => [
                    'order' => 'desc'
                ],
            ],
        ];


        $dsl = [];
        $dsl['query']['bool']['must'][] = [
            'term' => ['deleteStatus' => StatusCode::$standard],
            //'term' => ['enterpriseId' => $this->enterpriseId],
        ];
        $dsl['query']['bool']['must'][] = [
            //'term' => ['deleteStatus' => StatusCode::$standard],
            'term' => ['enterpriseId' => $this->enterpriseId],
        ];

        //客户名称/手机号
        if (!empty($selectParams['keyword'])) {
            $dsl['query']['bool']['must'][] = [
                'multi_match' => [
                    'fields'               => ['name^1.5', 'mobile', 'tag', 'managerMobile'],
                    'query'                => $selectParams['keyword'],
                    //'fuzziness' => 'AUTO',
                    "type"                 => "best_fields",
                    "tie_breaker"          => 0.3,
                    "minimum_should_match" => "100%"
                ],
            ];
        }

        //客户类型
        if (!empty($selectParams['type'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['type' => $selectParams['type']]];
        }

        //省code
        if (!empty($selectParams['provinceCode'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['provinceCode' => $selectParams['provinceCode']]];
        }

        //市code
        if (!empty($selectParams['cityCode'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['cityCode' => $selectParams['cityCode']]];
        }

        //区code
        if (!empty($selectParams['districtCode'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['districtCode' => $selectParams['districtCode']]];
        }

        //客户审核状态
        if (!empty($selectParams['status'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['status' => $selectParams['status']]];
        }

        //客户启用状态
        if (!empty($selectParams['enableStatus'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['enableStatus' => $selectParams['enableStatus']]];
        }

        //商铺id
        if (!empty($selectParams['shopId'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['shopId' => $selectParams['shopId']]];
        }

        //部门id
        if (!empty($selectParams['departmentId'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['departmentId' => $selectParams['departmentId']]];
        }

        parent::getAccessSalesManIds();
        if (parent::$salesManIds) {
            $dsl['query']['bool']['filter'][] = [
                'terms' => ['salesManId' => parent::$salesManIds]
            ];
        }

        //业务员id
        if (!empty($selectParams['salesManId'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['salesManId' => $selectParams['salesManId']]];
        }

        if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
            $dsl['query']['bool']['must'][] = [
                'range' => [
                    'createTime' => [
                        'gte' => $selectParams['start'],
                        'lte' => $selectParams['end'],
                    ]
                ]
            ];
        } else {
            if (!empty($selectParams['start'])) {
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'createTime' => [
                            'gte' => $selectParams['start'],
                        ]
                    ]
                ];
            }

            if (!empty($selectParams['end'])) {
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'createTime' => [
                            'lte' => $selectParams['end'],
                        ]
                    ]
                ];
            }
        }

        $dsl = array_merge($defaultDSL, $dsl);
        $result = $this->objDCustomer->getSearchQueryDsl($dsl);

        if (isset($result['status']) && $result['status'] == 400) {
            if ($result['error']['reason'] == 'all shards failed') {
                return ResultWrapper::success([
                    'data'  => [],
                    'total' => 0
                ]);
            }
            return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
        }

        if (!isset($result['hits']) || $result['hits']['total'] == 0) {
            return ResultWrapper::success([
                'data'  => [],
                'total' => 0
            ]);
        }
        $total = $result['hits']['total'];
        $dbResult = $result['hits']['hits'];

        $list = [];
        foreach ($dbResult as $key => &$value) {
            $data = [];
            $data = $value['_source'];
            //$data['id'] = $value['_id'];
            $list[] = $data;
        }

        $return = [
            'data'  => self::format($list),
            'total' => ($total) ? intval($total) : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 搜索  客户查询
     *
     * @param array $selectParams 过滤条件
     *
     * @return ResultWrapper
     * @throws Exception
     */
    public function query($selectParams)
    {
        $defaultDSL = [
            'from' => $selectParams['offset'],
            'size' => $selectParams['limit'],
            'sort' => [
                'createTime' => [
                    'order' => 'desc'
                ],
            ],
        ];


        $dsl = [];
        $dsl['query']['bool']['must'][] = [
            'term' => ['deleteStatus' => StatusCode::$standard],
            //'term' => ['enterpriseId' => $this->enterpriseId],
        ];
        $dsl['query']['bool']['must'][] = [
            //'term' => ['deleteStatus' => StatusCode::$standard],
            'term' => ['enterpriseId' => $this->enterpriseId],
        ];
        //客户名称/手机号
        if (!empty($selectParams['keyword'])) {
            $dsl['query']['bool']['must'][] = [
                'multi_match' => [
                    'fields'               => ['name', 'mobile', 'managerMobile'],
                    'query'                => $selectParams['keyword'],
                    //'fuzziness' => 'AUTO',
                    "type"                 => "best_fields",
                    "tie_breaker"          => 0.3,
                    "minimum_should_match" => "100%"
                ],
            ];
        }

        //标签
        if (!empty($selectParams['tag'])) {
            $dsl['query']['bool']['must'][] = [
                'match' => [
                    'tag' => $selectParams['tag'],
                ],
            ];
        }


        //省code
        if (!empty($selectParams['provinceCode'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['provinceCode' => $selectParams['provinceCode']]];
        }

        //市code
        if (!empty($selectParams['cityCode'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['cityCode' => $selectParams['cityCode']]];
        }

        //区code
        if (!empty($selectParams['districtCode'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['districtCode' => $selectParams['districtCode']]];
        }

        //客户启用状态
        if (!empty($selectParams['enableStatus'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['enableStatus' => $selectParams['enableStatus']]];
        }

        //商铺id
        if (!empty($selectParams['shopId'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['shopId' => $selectParams['shopId']]];
        }

        //来源
        if (!empty($selectParams['source'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['source' => $selectParams['source']]];
        }

        parent::getAccessSalesManIds();
        if (parent::$salesManIds) {
            $dsl['query']['bool']['filter'][] = [
                'terms' => ['salesManId' => parent::$salesManIds]
            ];
        }

        //业务员id
        if (!empty($selectParams['salesManId'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['salesManId' => $selectParams['salesManId']]];
        }

        if (!empty($selectParams['birthday_start']) && !empty($selectParams['birthday_end'])) {
            $dsl['query']['bool']['must'][] = [
                'range' => [
                    'createTime' => [
                        'gte' => $selectParams['birthday_start'],
                        'lte' => $selectParams['birthday_end'],
                    ]
                ]
            ];
        } else {
            if (!empty($selectParams['birthday_start'])) {
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'createTime' => [
                            'gte' => $selectParams['birthday_start'],
                        ]
                    ]
                ];
            }

            if (!empty($selectParams['birthday_end'])) {
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'createTime' => [
                            'lte' => $selectParams['birthday_end'],
                        ]
                    ]
                ];
            }
        }

        $dsl = array_merge($defaultDSL, $dsl);
        $result = $this->objDCustomer->getSearchQueryDsl($dsl);

        if (isset($result['status']) && $result['status'] == 400) {
            if ($result['error']['reason'] == 'all shards failed') {
                return ResultWrapper::success([
                    'data'  => [],
                    'total' => 0
                ]);
            }
            return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
        }

        if (!isset($result['hits']) || $result['hits']['total'] == 0) {
            return ResultWrapper::success([
                'data'  => [],
                'total' => 0
            ]);
        }
        $total = $result['hits']['total'];
        $dbResult = $result['hits']['hits'];

        $list = [];
        foreach ($dbResult as $key => &$value) {
            $data = [];
            $data = $value['_source'];
            //$data['id'] = $value['_id'];
            $list[] = $data;
        }

        $return = [
            'data'  => self::format($list),
            'total' => ($total) ? intval($total) : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 根据code获取今日下单客户的经纬度信息
     * @param string $code 省市区编码
     * @return ResultWrapper
     */
    public function getTodayOrderCustomerLocation($code = '')
    {
        $result = [];
        $objCustomerCache = new CustomerCache();
        $customerIds = $objCustomerCache->getTodayCustomerOrderInfo($this->enterpriseId, $code);

        $dsl = [];
        $dsl['query']['terms'] = [
            '_id' => $customerIds,
        ];
        $result = $this->objDCustomer->getSearchQueryDsl($dsl);

        if (isset($result['status']) && $result['status'] == 400) {
            return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
        }

        if (!isset($result['hits']) || $result['hits']['total'] == 0) {
            return ResultWrapper::success([]);
        }

        $dbResult = $result['hits']['hits'];
        $list = [];
        foreach ($dbResult as $key => &$value) {
            $location = $value['_source']['location'];
            $list[] = [
                'lng' => $location['lon'],
                'lat' => $location['lat']
            ];
        }
        return ResultWrapper::success($list);

    }

    /**
     * 根据code获取客户分布图
     * @param string $code 省市区编码
     * @return ResultWrapper
     */
    public function getCustomerLocation($code = '')
    {
        $dsl = [];
        parent::getAccessSalesManIds();
        if (parent::$salesManIds) {
            $dsl['query']['bool']['filter'][] = [
                'terms' => ['salesManId' => parent::$salesManIds]
            ];
        }

        if (!empty($code)) {
            $dsl['query']['bool']['must'][] = [
                'term' => ['districtCode' => $code],
            ];
        }

        $result = $this->objDCustomer->getSearchQueryDsl($dsl);

        if (isset($result['status']) && $result['status'] == 400) {
            if ($result['error']['reason'] == 'all shards failed') {
                return ResultWrapper::success([]);
            }
            return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
        }

        if (!isset($result['hits']) || $result['hits']['total'] == 0) {
            return ResultWrapper::success([]);
        }

        $dbResult = $result['hits']['hits'];
        $list = [];
        foreach ($dbResult as $key => &$value) {
            if (isset($value['_source']['location'])) {
                $location = $value['_source']['location'];
                $list[] = [
                    'lng' => $location['lon'],
                    'lat' => $location['lat']
                ];
            }
        }
        return ResultWrapper::success($list);

    }

    /**
     * 根据userCenterId获取customerId
     * @param $userCenterId
     * @return mixed
     */
    public function getCustomerIdByUserCenterId($userCenterId)
    {
        $customerId = $this->objDCustomer->get_field('id', ['userCenterId' => $userCenterId]);
        return $customerId ? $customerId : 0;
    }

    /**
     * 根据customerId获取userCenterId
     * @param $customerId
     * @return mixed
     */
    public function getUserCenterIdByCustomerId($customerId)
    {
        $userCenterId = $this->objDCustomer->get_field('userCenterId', ['id' => $customerId]);
        return $userCenterId ? $userCenterId : 0;
    }

    /**
     * 根据openId获取userCenterId
     * @param $openId
     * @return mixed
     */
    public function getUserCenterIdByOpenId($openId)
    {
        $userCenterId = $this->objDCustomer->get_field('userCenterId', ['openId' => $openId]);
        return $userCenterId ? $userCenterId : 0;
    }

    /**
     * 通过openId或者uniondId获取userCenterId
     * @param $params
     * @param $source
     * @return ResultWrapper
     * @throws Exception
     */
    public function getUserCenterIdByOpenIdOrUnionId($params, $source)
    {
        $whereSql = '';
        if( in_array($source, [StatusCode::$source['miniProgram'],StatusCode::$source['android'],StatusCode::$source['ios'],StatusCode::$source['weiXinBrowser']]) ) {
            //微信
            $whereSql = ' where openId = "' . $params['openId'] . '"';
            !empty($params['unionId']) && $whereSql .= ' or unionId = "' . $params['unionId'] . '"';
        }
        if ($source == StatusCode::$source['ByteProgram']) {
            //抖音
            $whereSql = ' where byteOpenId = "' . $params['openId'] . '"';
        }
        if (empty($whereSql)) {
            return ResultWrapper::fail('查询客户source参数错误', ErrorCode::$paramError);
        }
        $this->objDCustomer->setTable('qianniao_customer_' . $this->enterpriseId);
        $sql = 'select * from ' . $this->objDCustomer->get_Table() . $whereSql;
        $dbResult = $this->objDCustomer->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        //是空仍然返回
        return ResultWrapper::success($dbResult);
    }

    /**
     * 指定字段修改用户数据
     * @param $where
     * @param $update
     * @return ResultWrapper
     */
    public function setCustomerData($where, $update)
    {
        $dbResult = $this->objDCustomer->update($update, $where);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }


    /**
     * 绑定覆盖unionId (微信, 抖音)
     * @param $source
     * @param $userCenterId
     * @param $openId
     * @param $unionId
     * @param string $avatar
     * @param string $name
     * @return ResultWrapper
     */
    public function bindOpenIdAndMobile($source, $userCenterId, $openId, $unionId, $avatar = '', $name = '')
    {
        //判断是微信还是抖音
        if ( in_array($source, [StatusCode::$source['miniProgram'],StatusCode::$source['ios'],StatusCode::$source['android'],StatusCode::$source['weiXinBrowser']])) {
            !empty($openId) && $param['openId'] = $openId;
            $param['unionId'] = $unionId;
        } elseif ($source == StatusCode::$source['ByteProgram']) {
            $param['byteOpenId'] = $openId;
        } else {
            return ResultWrapper::fail('覆盖客户绑定数据source参数错误', ErrorCode::$paramError);
        }

        if (empty($param)) {
            return ResultWrapper::fail('覆盖客户绑定修改数据为空', ErrorCode::$paramError);
        }
        $dbResult = $this->objDCustomer->update($param, ['userCenterId' => $userCenterId]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 根据userCenterId和企业id查询客户数据
     * @param $userCenterId
     * @param $enterpriseId
     * @return ResultWrapper
     * @throws Exception
     */
    public function getCustomerDataByUserCenterIdAndEnterpriseId($userCenterId, $enterpriseId = false)
    {
        !$enterpriseId && $enterpriseId = $this->enterpriseId;
        $this->objDCustomer->setTable('qianniao_customer_' . $enterpriseId);
        $dbResult = $this->objDCustomer->get(['userCenterId' => $userCenterId, 'enterpriseId' => $enterpriseId, 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取客户基本信息
     */
    public function getCustomerBasicInfoByUserCenterIds($userCenterIds = [])
    {
        if(empty($userCenterIds)){
            return ResultWrapper::success('未指定查询的userCenterIds', ErrorCode::$paramError);
        }

        $sql = 'select c.*,u.mobile from qianniao_customer_'.$this->enterpriseId.' as c left join qianniao_user_center as u on u.id = c.userCenterId where c.userCenterId in ('. implode(',', $userCenterIds) .')';
        $dbResult = $this->objDCustomer->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 根据userCenterId获取客户完整信息 看不懂？？？？？
     * @param $userCenterId
     * @param $fields
     * @return ResultWrapper
     * @throws Exception
     */
    public function getCustomerInfoByUserCenterId($userCenterId,$isMini = false)
    {
        $customerInfo = $this->objCustomerCache->getCustomerUserData($this->enterpriseId,$userCenterId);

//        if (empty($customerInfo)) {
            $sql = 'SELECT u.mobile,c.*,c.money as balance FROM ' . $this->objDUserCenter->get_Table() . ' AS u JOIN ' . $this->objDCustomer->get_Table() . ' AS c ON u.id=c.userCenterId AND u.id = ' . $userCenterId . ' LIMIT 1';

            $dbResult = $this->objDCustomer->query($sql);
            if ($dbResult === false) {
                return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
            }
            if (empty($dbResult)) {
                return ResultWrapper::fail('要查询的客户不存在', ErrorCode::$contentNotExists);
            }
            //查业务员名称
            $customerInfo = array_shift($dbResult);
            $sourceType = isset($customerInfo['type']) ? $customerInfo['type'] : null;
            $dbResult['customerSourceTypeName'] = '';
            $dbResult['modelType'] = '';
            if (!empty($sourceType)) {
                //映射客户类型名称
                $fields = 'id,name,modelType';
                $customerSource = $this->objDCustomer->query('select ' . $fields . ' from qianniao_customer_source where id = ' . $sourceType);
                if ($customerSource === false) {
                    return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
                }
                $customerSourceInfo = array_shift($customerSource);
                $dbResult['customerSourceTypeName'] = isset($customerSourceInfo['name']) ? $customerSourceInfo['name'] : '';
                $dbResult['modelType'] = isset($customerSourceInfo['modelType']) ? $customerSourceInfo['modelType'] : '';
            }

            $customerInfo['extend'] = json_decode($customerInfo['extend'], true);
            $salesManDate = $this->objMStaff->getNameById($customerInfo['salesManId']);
            $customerInfo['salesManName'] = isset($salesManDate['staffName']) ? $salesManDate['staffName'] : '';
            $customerInfo['salesManMobile'] = isset($salesManDate['userMobile']) ? $salesManDate['userMobile'] : '';
            $customerInfo['modelType'] = $dbResult['modelType'];
            $customerInfo['customerSourceTypeName'] = $dbResult['customerSourceTypeName'];

            //联系人
            $customerInfo['contact'] = $this->objMCustomerContact->getContactInfoById($customerInfo['id']);
            $this->objCustomerCache->cacheCustomerUserData($this->enterpriseId,$userCenterId,$customerInfo);
//        }

        if ($isMini === true){
            $objMUserCoupon = new MUserCoupon($this->userCenterId,$this->enterpriseId);
            $couponNumResult = $objMUserCoupon->getCouponNum($userCenterId);
            if (!$couponNumResult->isSuccess()){
                return ResultWrapper::fail($couponNumResult->getData(),$couponNumResult->getErrorCode());
            }
            $objMVipCard = new MVipCard($this->enterpriseId,$this->userCenterId);
            $vipNumResult = $objMVipCard->getVipCardNum($userCenterId);
            if (!$vipNumResult->isSuccess()){
                return ResultWrapper::fail($vipNumResult->getData(),$vipNumResult->getErrorCode());
            }
            $customerInfo['vipNum'] = (int)$vipNumResult->getData();
            $customerInfo['couponNum'] = $couponNumResult->getData();

            $objMGoodsCollect = new MGoodsCollect($this->enterpriseId,$this->userCenterId);
            $collNumResult = $objMGoodsCollect->getCollNum($userCenterId);
            if (!$collNumResult->isSuccess()){
                return ResultWrapper::fail($collNumResult->getData(),$collNumResult->getErrorCode());
            }
            $customerInfo['collNum'] = (int)$collNumResult->getData();
        }

        //查询店铺信息
        $customerInfo['shopDate'] = [];
        $objDShop = new DShop();
        $objDShop->setTable('qianniao_shop_1');
        $shopResult = $objDShop->get(['enterpriseId'=>$this->enterpriseId]);
        if ($shopResult === false) {
            return ResultWrapper::fail($objDShop->error(), ErrorCode::$dberror);
        }
        $customerInfo['shopDate'] = $shopResult;

        return ResultWrapper::success($customerInfo);
    }

    /**
     * @param $selectParams
     * @param string $field
     * @return ResultWrapper
     */
    public function getCustomer($selectParams, $field = 'name,id')
    {
        $dbResult = $this->objDCustomer->select($selectParams, $field);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $customerData = [];
        if (!empty($dbResult)) {
            foreach ($dbResult as $info) {
                $customerData[$info['id']] = $info;
            }
        }
        return ResultWrapper::success($customerData);
    }

    /**
     * 获取客户总数
     */
    public function getCustomerTotalNum()
    {
        $result = $this->objCustomerCache->getAllCustomerNum($this->enterpriseId);
        if ($result === false){
            //缓存客户数据
            self::setCustomerCache();
            $result = $this->objCustomerCache->getAllCustomerNum($this->enterpriseId);
        }
        return $result ? $result : 0;
    }

    /**
     * 今日新增客户数
     * @param null $shopId
     * @return bool|int
     */
    public function getTodayCustomerTotalNum($shopId = null)
    {
        /*$result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
        if ($result === false){
            self::setCustomerCache();
            $result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
        }*/
        self::setCustomerCache($shopId);
        $result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
        return $result ? $result : 0;
    }


    /**
     * 获取总的应收款
     */
    public function getTotalShouldReceive()
    {
        $result = $this->objOverviewCache->getAggregateStatistics($this->enterpriseId, 'totalShouldReceive');
        return $result ? $result : 0;
    }

    /**
     *获取新增客户数（近30天注册但未交易）
     */
    public function getNewCustomerNum()
    {
        $result = $this->objCustomerCache->getNewCustomerNum($this->enterpriseId);
        return $result ? $result : 0;
    }

    /**
     *获取兴趣人群数
     */
    public function getInterestCustomerNum()
    {
        $result = $this->objCustomerCache->getInterestCustomerNum($this->enterpriseId);
        return $result ? $result : 0;
    }

    /**
     * 今日客户排行
     * @param int $ranking 1销量排行  2销额排行
     * @return array
     */
    public function todayCustomerRanking($ranking = 1)
    {
        if ($ranking == 1) {
            $result = $this->objOverviewCache->getRanking($this->enterpriseId, 'customerRanking');
        } else {
            $result = $this->objOverviewCache->getSalesMoneyRanking($this->enterpriseId, 'customerRanking');
        }

        if (empty($result)) {
            return [];
        }

        //拼接customerId
        $customerIds = [];
        foreach ($result as $customerId => $v) {
            $i = 1;
            $customerIds[] = $customerId;
            $i++;

            if ($i >= 8) {
                break;
            }
        }

        //查找客户名称
        $customerResult = self::getCustomer($customerIds);
        $customerNameData = [];
        if ($customerResult->isSuccess()) {
            $customerNameData = $customerResult->getData();
        }

        //拼接返回数据
        $return = [];
        foreach ($result as $customerId => $v) {
            $i = 1;
            $rank = [];
            $rank['id'] = $i;
            $rank['customerName'] = isset($customerNameData[$customerId]['name']) ? $customerNameData[$customerId]['name'] : '';
            $rank['numberOrMoney'] = $v;
            $return[] = $rank;

            $i++;
            if ($i >= 8) {
                break;
            }
        }
        return $return;
    }

    /**
     * 格式化客户
     */
    public function formatCustomer()
    {
        //查询所有企业
        $sql = 'select id from qianniao_enterprise_1 where deleteStatus = 5';
        $dbResult = $this->objDCustomer->query($sql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $ii = 0;
        $enterprise = $dbResult;
        unset($dbResult);
        foreach($enterprise as $enterpriseValue){
            //查询客户
            $this->objDCustomer->setTable('qianniao_customer_'.$enterpriseValue['id']);
            $dbResult = $this->objDCustomer->select();
            if($dbResult === false){
                return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
            }
            if(empty($dbResult)){
                continue;
            }

            //循环客户
            foreach($dbResult as $value){
                //修改营业执照
                $extend = json_decode($value['extend'], true);
                if(isset($extend['license']) && !empty($extend['license']) && strpos($extend['license'],'?imageView2') !== false){
                    $extend['license'] = substr($extend['license'], 0, strrpos($extend['license'],'?imageView2'));
                    $update['extend'] = json_encode($extend);
                    //保存客户
                    $result = $this->objDCustomer->update($update, ['id' => $value['id']]);
                    if($result === false){
                        return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
                    }
                    $ii++;
                }
            }
        }

        return ResultWrapper::success('修改成功, 共修改'.$ii.'条数据');
    }

    /**
     * 充值余额
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function rechargeBalance($params)
    {
        $where['userCenterId'] = $params['userCenterId'];
        //查询客户信息
        $dbResult = $this->objDCustomer->get($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $customerData = $dbResult;
        unset($dbResult);

        //记录充值记录
        $recordInsert = [
            'no' => createOrderSn(StatusCode::$source['miniProgram'], 0, $customerData['userCenterId']),
            'customerId' => $customerData['id'],
            'money' => $params['money'],
            'userCenterId' => $customerData['userCenterId'],
            'shopId' => $customerData['shopId'],
            'payStatus' => StatusCode::$delete,
            'desc' => '充值余额'.$params['money'].'元',
            'createTime' => time(),
            'updateTime' => time(),
        ];
        $dbResult = $this->objDCustomerRechargeRecord->insert($recordInsert);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
        }
        $recordId = $dbResult;
        unset($dbResult);

        //获取支付配置
        $objMPaymentSetting = new MPaymentSetting($this->enterpriseId, $this->userCenterId);
        $result = $objMPaymentSetting->getPayData($params['payType']);
        if (!$result->isSuccess() || empty($result->getData())) {
            return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
        }
        $payment = $result->getData();

        // 获取当前登录企业的小程序配置
        $objSystemCache = new SystemCache();
        $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->enterpriseId);
        if (empty($miniprogramSetting)) {
            return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
        }
        $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
        $appid = $miniprogramSetting['appid'];
        $paySource = 'miniProgram';
        $weixinConfigData = [
            'mch_id'        => $payment['mchId'],
            'apiPartnerKey' => $payment['apiPartnerKey'],
            'appid'         => $appid
        ];
        $attach = $this->enterpriseId . '|' . $this->userCenterId . '|' . $recordId;
        $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
        $modelResult = $objPay->unifiedorder($recordInsert['no'], $params['money'], $params['ip'], $paySource, '千鸟云商', $customerData['openId'], $attach);
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        return ResultWrapper::success($modelResult->getData());
    }


    /**
     * 支付完成调用方法
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function payTrue($params)
    {
        //查询充值记录
        $dbResult = $this->objDCustomerRechargeRecord->get(['id' => $params['id']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
        }
        $record = $dbResult;
        unset($dbResult);

        //查询客户
        $dbResult = $this->objDCustomer->get(['id' => $record['customerId']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $customerData = $dbResult;
        unset($dbResult);

        //客户修改数据
        $update = [
            'money' => bcadd($customerData['money'], $record['money'], 4),
            'updateTime' => time(),
        ];

        //修改充值记录状态
        $updateRecord = [
            'balance' => $update['money'],
            'payStatus' => StatusCode::$standard,
            'updateTime' => time(),
        ];
        //开启事务
        $this->objDCustomerRechargeRecord->beginTransaction();
        $dbResult = $this->objDCustomerRechargeRecord->update($updateRecord, ['id' => $params['id']]);
        if($dbResult === false){
            $this->objDCustomerRechargeRecord->rollBack();
            return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
        }

        //记录余额流水
        $turnoverInsert = [
            'sourceId' => $record['id'],
            'sourceNo' => $record['no'],
            'source' => 1,//来源  1:充值余额
            'customerId' => $customerData['id'],
            'userCenterId' => $customerData['userCenterId'],
            'shopId' => $customerData['shopId'],
            'money' => $record['money'],
            'balance' => $update['money'],
            'type' => StatusCode::$standard,
            'desc' => '充值余额'.$record['money'].'元',
            'createTime' => time(),
            'updateTime' => time(),
        ];
        $dbResult = $this->objDCustomerBalanceTurnover->insert($turnoverInsert);
        if($dbResult === false){
            $this->objDCustomerRechargeRecord->rollBack();
            return ResultWrapper::fail($this->objDCustomerBalanceTurnover->error(), ErrorCode::$dberror);
        }

        //增加财务客户余额流水
        $objMCustomerBalanceDetail = new MCustomerBalanceDetail($this->enterpriseId, $this->userCenterId);
        $detailInsert = [
            'customerId'             => $customerData['id'],//'客户id',
            'receiptTime'            => time(),//'单据日期',
            'sourceId'               => $customerData['id'],
            'sourceNo'               => createOrderSn(StatusCode::$source['miniProgram'], 8, $customerData['userCenterId']),//'单据编号',
            'financeType'            => '会员余额充值收款',//'财务类型名称',
            'financeTypeId'          => 8,//'财务类型id',
            'sourceId'               => $record['id'],
            'sourceNo'               => $record['no'],//'源订单销货号',
            'salesAmount'            => $record['money'],//总金额
            'discountMoney'          => 0,// '优惠金额',
            'customerAmount'         => $record['money'],// '客户承担金额',
            'receivableAmount'       => $record['money'],// '应收金额',
            'actualReceivableAmount' => $record['money'],//'实际收款金额',
            'receivableBalance'      => $update['money'],//'应收后余额',
            'remark'                 => '客户充值余额 本次实收' . $record['money'] . '元',//'备注',
            'createTime'             => time(),//'创建日期',
            'updateTime'             => time(),//'修改日期',
        ];
        $modelResult = $objMCustomerBalanceDetail->addCustomerBalanceDetail($detailInsert);
        if(!$modelResult->isSuccess()){
            $this->objDCustomerRechargeRecord->rollBack();
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }

        //修改客户余额
        $dbResult = $this->objDCustomer->update($update, ['id' => $customerData['id']]);
        if($dbResult === false){
            $this->objDCustomerRechargeRecord->rollBack();
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        //提交事务
        $this->objDCustomerRechargeRecord->commit();
        return ResultWrapper::success('支付成功');
    }

    /**
     * 充值记录列表
     * @param $params
     * @return ResultWrapper
     */
    public function getAllRechargeBalance($params)
    {
        $limit = $params['limit'];
        $offset = $params['offset'];
        $where = [];
        if(isset($params['customerId'])){
            $where['customerId'] = $params['customerId'];
        }
        if(isset($params['userCenterId'])){
            $where['userCenterId'] = $params['userCenterId'];
        }
        $dbResult = $this->objDCustomerRechargeRecord->select($where, '*', 'createTime desc', $limit, $offset);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
        }
        $data = $dbResult;
        unset($dbResult);
        $count = $this->objDCustomerRechargeRecord->count($where);
        $return = [
            'data' => $data,
            'total' => $count ? $count : 0
        ];
        return ResultWrapper::success($return);
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2021/1/15
     * Time: 5:35 下午
     * @param $ids
     * @return ResultWrapper
     * @throws Exception
     */
    public function getCustomerByIds($ids): ResultWrapper
    {
        if (empty($ids)){
            return ResultWrapper::success([]);
        }
        $lists = $this->objDCustomer->select(['id' => $ids]);
        if ($lists === false){
            return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
        }
        $formatLists = self::format($lists);
        return ResultWrapper::success($formatLists);
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/11/14
     * Time: 10:40 上午
     * @param $customerId
     * @return ResultWrapper
     */
    public function getCustomerByCustomerId($customerId): ResultWrapper
    {
        if (empty($customerId)){
            return ResultWrapper::success([]);
        }
        $fields = ' u.mobile,c.id,c.salesManId,c.avatar,c.name,c.birthday,c.provinceCode,c.cityCode,c.districtCode,c.status,c.auditFailReason,c.enableStatus,c.openId,c.type,c.remark,c.extend ';
        $sql = 'SELECT '.$fields.' FROM ' . $this->objDUserCenter->get_Table() . ' 
                AS u JOIN ' . $this->objDCustomer->get_Table() . ' 
                AS c ON u.id=c.userCenterId AND c.id=' . $customerId . ' LIMIT 1';
        $dbResult = $this->objDCustomer->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $dbResult = (array)$dbResult;
        $dbResult = array_shift($dbResult);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 首字母搜索客户
     * @param $data
     * @return ResultWrapper
     */
    public function initialsSearch($data)
    {
        $condition = isset($data['condition']) && !empty($data['condition']) ? $data['condition'] : '';
        if (empty($condition)) return ResultWrapper::success([]);
        $objChineseCharacter = new ChineseCharacter();
        $condition = $objChineseCharacter->getInitials($condition);
        $sql = 'select c.* from '.$this->objDCustomer->get_Table().' c left join qianniao_user_center u on c.userCenterId = u.id where c.deleteStatus = '.StatusCode::$standard.' and c.enableStatus = '.StatusCode::$standard.' and c.condition like "%'.$condition.'%" or u.mobile like "%'.$condition.'%" order by c.createTime desc';
        $dbResult = $this->objDCustomer->query($sql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 初始化客户首字母
     */
    public function initialsCustomer()
    {
        $objChineseCharacter = new ChineseCharacter();
        $dbResult = $this->objDCustomer->select();
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        foreach($dbResult as $value){
            $condition = $objChineseCharacter->getInitials(trim($value['name']));
            $result = $this->objDCustomer->update(['condition' => $condition], ['id' => $value['id']]);
            if($result === false){
                return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
            }
        }
        return ResultWrapper::success('执行成功');
    }

    /**
     * Doc: (des="根据客户id获取客户实时的分拣区")
     * User: XMing
     * Date: 2020/12/25
     * Time: 4:57 下午
     * @param $ids
     * @return ResultWrapper
     */
    public function getReservoirByCustomerIds($ids): ResultWrapper
    {
        if (empty($ids)){
            return ResultWrapper::success([]);
        }
        $customer = $this->objDCustomer->select($ids);
        if ($customer === false){
            return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
        }
        $reservoirIds = [];
        foreach ($customer as $value){
            if (empty($value['reservoirId'])){
                continue;
            }
            $reservoirIds[] = $value['reservoirId'];
        }
        $objMReservoirArea = new MReservoirArea($this->enterpriseId,$this->userCenterId);

        $reservoir = [];
        if(!empty($reservoirIds)){
            $reservoirResult = $objMReservoirArea->getReservoirMapByIds(['id' => $reservoirIds]);
            if (!$reservoirResult->isSuccess()){
                return ResultWrapper::fail($reservoirResult->getData(),$reservoirResult->getErrorCode());
            }
            $reservoir = $reservoirResult->getData();
        }

        $reservoirMap = [];
        foreach ($customer as $value){
            $reservoirId = $value['reservoirId'];
            $row = getArrayItem($reservoir,$reservoirId,[]);
            $reservoirMap[$value['id']] = [
                'name'        => getArrayItem($row, 'name', ''),
                'warehouseId' => getArrayItem($row, 'warehouseId', 0),
                'code'        => getArrayItem($row, 'code', ''),
                'type'        => getArrayItem($row, 'type', 0)
            ];
        }
        return ResultWrapper::success($reservoirMap);
    }

    /**
     * Doc: (des="查询客户商品购买记录")
     * User: XMing
     * Date: 2021/3/10
     * Time: 10:59 上午
     * @param array $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function searchCustomerBuyLog(array $params ,$export = 0): ResultWrapper
    {
        $objMOrder = new MOrder($this->userCenterId,$this->enterpriseId);
        if($export){
            $params['limit'] = null;
            $params['offset'] = null;
        }
        $dbResult = $objMOrder->getGoodsListsByUserCenterId($params);
        if (!$dbResult->isSuccess()){
            return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
        }
        //客户购买记录导出
        if($export){
            self::exportCustomerBuyLog($dbResult->getData()['data']);
            exit;
        }
        return ResultWrapper::success($dbResult->getData());
    }

    /**
     * Doc: (des="获取客户的余额")
     * User: XMing
     * Date: 2021/3/18
     * Time: 10:55 上午
     * @param int $customerId
     * @return ResultWrapper
     */
    public function getCustomerBalance(int $customerId): ResultWrapper
    {
        $result = $this->objDCustomer->get($customerId);
        if ($result === false){
            return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
        }
        if (empty($result)){
            return ResultWrapper::fail('为获取到客户的余额信息',ErrorCode::$paramError);
        }
        $money = getArrayItem($result,'money',0);
        return ResultWrapper::success($money);
    }

    /**
     * Doc: (des="修改客户的余额并增加流水记录")
     * User: XMing
     * Date: 2021/3/18
     * Time: 11:41 上午
     * @param int $customerId
     * @param float $changeMoney
     * @return ResultWrapper
     */
    public function decCustomerBalance(int $customerId,float $changeMoney,$tmpOuterTradeNo): ResultWrapper
    {
        if (empty($changeMoney)){
            return ResultWrapper::fail('支付金额异常',ErrorCode::$paramError);
        }
        $customerResult = self::getCustomerBalance($customerId);
        if (!$customerResult->isSuccess()){
            return ResultWrapper::fail($customerResult->getData(),$customerResult->getErrorCode());
        }
        $customerMoney = $customerResult->getData();

        if($customerMoney >= 0){
            return ResultWrapper::fail('余额不足,至少需要'.$changeMoney,ErrorCode::$paramError);
        }

        if ($customerMoney <0 && (bccomp($changeMoney,abs($customerMoney),2) > 0)){
            return ResultWrapper::fail('余额不足,至少需要'.$changeMoney,ErrorCode::$paramError);
        }

        //扣除余额，
        $update = [
            'money' => bcsub($customerMoney,$changeMoney,2),
            'updateTime' => time()
        ];
        $updateResult = $this->objDCustomer->update($update,$customerId);
        if ($updateResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$paramError);
        }
        //TODO(增加流水)
        $trans = [
            'tmpOuterTradeNo' => $tmpOuterTradeNo,
            'oldMoney' => $customerMoney,
            'payMoney' => $changeMoney,
            'createTime' => time(),
            'money' => $update['money']
        ];
        $update['tmpOuterTradeNo'] = $tmpOuterTradeNo;
        Logger::logs(E_USER_ERROR,'订单余额支付记录'.$tmpOuterTradeNo,__CLASS__,__LINE__,$trans);
        return ResultWrapper::success(true);
    }
    
    /**
     * 添加余额支付密码
     * User: kang
     * Date: 2021/3/25
     * Time: 17:00 下午
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addpayPassword($payPasswordData)
    {
        $ifPayPassword = $this->objDCustomer->get(['id'=>$payPasswordData['id']]);
        if(!empty($ifPayPassword['payPassword'])){
            return ResultWrapper::fail('该用户密码已添加', ErrorCode::$accountfail);
        }
        $payPasswordId= $payPasswordData['id'];
        unset($payPasswordData['id']);
        $dbResult = $this->objDCustomer->update($payPasswordData,$payPasswordId);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }
    
    /**
     * 修改余额支付密码
     * User: kang
     * Date: 2021/3/25
     * Time: 17:25 下午
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function updatePayPassword($updatePayPasswordData)
    {
        $customerid = $updatePayPasswordData['id'];
        unset($updatePayPasswordData['id']);
        $dbResult = $this->objDCustomer->update($updatePayPasswordData,$customerid);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($dbResult);
        }
    }
    
    /**
     * 校验余额支付密码
     * User: kang
     * Date: 2021/3/25
     * Time: 17:25 下午
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function checkPayPassword($checkPayPasswordData)
    {
        $oldPayPassword = $this->objDCustomer->get(['id'=>$checkPayPasswordData['id']]);
        if($oldPayPassword === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        
        if(password_verify($checkPayPasswordData['payPassword'], $oldPayPassword['payPassword'] ) !== true){
            return ResultWrapper::fail('密码错误', ErrorCode::$accountfail);
        }
        return ResultWrapper::success();
    }

    /**
     * 客户积分流水
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAllCustomerIntegralDesc($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $dbResult = $this->objDCustomer->get(['id' => $selectParams['customerId']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $customerData = $dbResult;
        unset($dbResult);

        isset($selectParams['search']) && $selectParams['search'] = ['title' => $selectParams['search']];
        $selectParams = self::formatSqlWhere($selectParams);
        $dbResult = $this->objDCustomerIntegralDesc->select($selectParams,'*', 'createTime desc', $limit, $offset);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
        }
        $data = $dbResult;
        unset($dbResult);

        $countResult = $this->objDCustomerIntegralDesc->count($selectParams);
        if ($countResult === false) {
            return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
        }

        $return = [
            'data' => [
                'lists' => $data,
                'customer' => $customerData,
            ],
            'total' => ($countResult) ? intval($countResult) : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 修改积分
     * @param $params
     * @return ResultWrapper
     */
    public function updateCustomerIntegral($params)
    {
        if (empty($params['integral'])) {
            return ResultWrapper::fail('修改积分不能为空', ErrorCode::$paramError);
        }
        if ($params['integral'] < 0) {
            return ResultWrapper::fail('修改积分不能为空', ErrorCode::$paramError);
        }
        $dbResult = $this->objDCustomer->get(['id' => $params['customerId']]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $customer = $dbResult;
        unset($dbResult);
        if (empty($customer)) {
            return ResultWrapper::fail('用户不存在', ErrorCode::$dberror);
        }

        if ($params['type'] == 5) {
            $money = bcadd($customer['integral'], $params['integral'], 2);
        } else {
            $money = bcsub($customer['integral'], $params['integral'], 2);
        }
        if($money < 0){
            return ResultWrapper::fail('修改后积分不能为负数', ErrorCode::$paramError);
        }
        $update = [
            'integral' => $money,
            'updateTime' => time()
        ];
        $dbResult = $this->objDCustomer->update($update, ['id' => $params['customerId']]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

        if(isset($params['desc']) && !empty($params['desc'])){
            //增加记录
            $insertDesc = [
                'userCenterId' => $customer['userCenterId'],
                'customerId' => $customer['id'],
                'shopId' => isset($params['shopId']) ? $params['shopId'] : 0,
                'title' => $params['desc'],
                'amount' => $params['integral'],
                'changeAmount' => $money,
                'type' => $params['type'],
                'source' => 3,
                'createTime' => time(),
                'updateTime' => time()
            ];
            $result = $this->objDCustomerIntegralDesc->insert($insertDesc);
            if ($result === false) {
                return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
            }
        }

        return ResultWrapper::success(true);
    }

    /**
     * 根据订单增加客户积分
     * @param int $shopId
     * @param array $customer
     * @param array $order
     * @param array $orderGoods
     * @return ResultWrapper
     */
    public function addCustomerIntegralByOrder($shopId = 0, $customer = [], $order = [], $orderGoods = [])
    {
        //查询规则
        $objDIntegralRule = new DIntegralRule();
        $objDIntegralRule->setTable('qianniao_integral_rule_'.$this->enterpriseId);
        $dbResult = $objDIntegralRule->get(['shopId' => $shopId, 'enableStatus' => StatusCode::$standard, 'deleteStatus' => StatusCode::$standard], '*', 'createTime DESC');
        if($dbResult === false){
            return ResultWrapper::fail($objDIntegralRule->error(), ErrorCode::$dberror);
        }
        $rule = $dbResult;
        unset($dbResult);
        if(empty($rule)){
            return ResultWrapper::success(false);
        }
        $ruleGoods = json_decode($rule['goods'], true);

        if(empty($rule['startMoney']) || $rule['startMoney'] < 0){
            $rule['startMoney'] = 0;
        }

        //匹配商品
        $goodsIntegral = 0;
        $orderAmount = 0;
        foreach($orderGoods as $value){
            if(isset($ruleGoods[$value['skuId']])){
                //计算商品积分
                if($ruleGoods[$value['skuId']]['integral'] > 0){
                    $goodsIntegral = bcadd($goodsIntegral, bcmul($ruleGoods[$value['skuId']]['integral'], $value['buyNum']),2);
                }
            }else{
                if($order['totalMoney'] >= $rule['startMoney']){
                    $orderAmount = bcadd($orderAmount, $value['totalMoney'], 2);
                }
            }
        }
        $insertIntegralDesc = [];
        if($goodsIntegral > 0){
            //增加记录
            $insertIntegralDesc[] = [
                'userCenterId' => $customer['userCenterId'],
                'customerId' => $customer['id'],
                'shopId' => $shopId,
                'originId' => $order['id'],
                'originNo' => $order['no'],
                'ruleId' => $rule['id'],
                'title' => '购买指定商品奖励积分',
                'amount' => $goodsIntegral,
                'changeAmount' => bcadd($customer['integral'], $goodsIntegral, 2),
                'type' => StatusCode::$standard,
                'source' => 2,
                'createTime' => time() - 1,
                'updateTime' => time() - 1,
            ];
        }

        //计算订单积分
        $orderIntegral = 0;
        if($orderAmount > 0 && $rule['amount'] > 0 && $rule['integral'] > 0){
            $orderIntegral = bcmul(intval($orderAmount / $rule['amount']), $rule['integral'], 2);
            //增加记录
            $insertIntegralDesc[] = [
                'userCenterId' => $customer['userCenterId'],
                'customerId' => $customer['id'],
                'shopId' => $shopId,
                'originId' => $order['id'],
                'originNo' => $order['no'],
                'ruleId' => $rule['id'],
                'title' => '订单满足'.bcmul(intval($orderAmount / $rule['amount']), $rule['amount'], 2).',奖励积分',
                'amount' => $orderIntegral,
                'changeAmount' => bcadd($customer['integral'], bcadd($orderIntegral, $goodsIntegral,2), 2),
                'type' => StatusCode::$standard,
                'source' => 1,
                'createTime' => time(),
                'updateTime' => time(),
            ];
        }

        //累加积分
        $addIntegral = bcadd($orderIntegral, $goodsIntegral, 2);

        //增加客户积分
        if($addIntegral > 0){
            $updateCustomer = [
                'integral' => bcadd($customer['integral'], $addIntegral, 2),
                'updateTime' => time(),
            ];
            $dbResult = $this->objDCustomer->update($updateCustomer, ['id' => $customer['id']]);
            if($dbResult === false){
                return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
            }
        }

        //累加规则赠送积分
        $updateRule = [
            'integralTotal' => bcadd($rule['integralTotal'], $addIntegral, 2),
            'updateTime' => time(),
        ];
        $dbResult = $objDIntegralRule->update($updateRule, ['id' => $rule['id']]);
        if($dbResult === false){
            return ResultWrapper::fail($objDIntegralRule->error(), ErrorCode::$dberror);
        }

        //保存记录
        if(!empty($insertIntegralDesc)){
            $dbResult = $this->objDCustomerIntegralDesc->insert($insertIntegralDesc, true);
            if($dbResult === false){
                return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
            }
        }
        return ResultWrapper::success('执行成功');
    }


    /**
     * 新注册未下单统计
     */
    public function noOrderCustomer($params)
    {
        // 间隔天数转时间戳
        $endTime = time() - (86400 * $params['intervalDay']);

        $where = '';
        if( isset($params['customerName']) && !empty($params['customerName']) ){
            $where .= ' and c.name like "%'.$params['customerName'].'%" ';
        }

        if( isset($params['salesManId']) && !empty($params['salesManId']) ){
            $where .= ' and c.salesManId = '.$params['salesManId'];
        }

        if( isset($params['provinceCode']) && !empty($params['provinceCode']) ){
            $where .= ' and c.provinceCode = '.$params['provinceCode'];
        }

        if( isset($params['cityCode']) && !empty($params['cityCode']) ){
            $where .= ' and c.cityCode = '.$params['cityCode'];
        }

        if( isset($params['districtCode']) && !empty($params['districtCode']) ){
            $where .= ' and c.districtCode = '.$params['districtCode'];
        }

        $sql = ' from (select c.*,count(o.id) as total from qianniao_customer_'.$this->enterpriseId.' c left join qianniao_order_index_'.$this->enterpriseId.' o on o.customerId = c.id where c.deleteStatus = 5 and c.createTime >= '.$endTime.' '.$where.'  GROUP BY c.id) tmp where tmp.total = 0';
        $listSql = $sql.' ORDER BY tmp.createTime desc limit '.$params['offset'].','.$params['limit'];

        $fields = 'select tmp.name,tmp.id,tmp.createTime,tmp.provinceCode,tmp.cityCode,tmp.districtCode,tmp.type,tmp.salesManId,tmp.userCenterId,tmp.shopId,tmp.departmentId';

        $dbResult = $this->objDCustomerRechargeRecord->query($fields.$listSql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
        }
        
        //拿到范围内的客户
        $customerIds = [];
        foreach ($dbResult as $value){
            $customerIds[] = $value['id'];
        }
       
        $customerIds = implode(',',$customerIds);
        
        $objMCustomerCommunication = new MCustomerCommunication($this->enterpriseId);
        //根据客户id查询客户本年拜访次数
        $dbYearNum = $objMCustomerCommunication->getCustomerYearVisitNumber($customerIds);
        if(!$dbYearNum->isSuccess()){
            return ResultWrapper::fail($dbYearNum->getData(),$dbYearNum->getErrorCode());
        }
        $yearNumDbResult = $dbYearNum->getData();
     
        $yearNum = [];
        foreach ($yearNumDbResult as $v){
            $yearNum[$v['customerId']]= $v['yearNum'];//所查出客户本年拜访次数
        }
        
        //根据客户id查询客户距离上次拜访相差多少天
        $dbDayNum = $objMCustomerCommunication->getCustomerlastTimeDay($customerIds);
        if(!$dbDayNum->isSuccess()){
            return ResultWrapper::fail($dbDayNum->getData(),$dbDayNum->getErrorCode());
        }
        $dayNumDbResult = $dbDayNum->getData();
    
        $dayNum = [];
        foreach ($dayNumDbResult as $v){
            $dayNum[$v['customerId']]= $v['time'];//所查出客户距离上次拜访相差多少天
        }
        
        //根据查出天数范围内的客户查出所对应的日期并归组
        $result = $objMCustomerCommunication->getCustomerDate($customerIds);
        if(!$result->isSuccess()){
            return ResultWrapper::fail($result->getData(),$result->getErrorCode());
        }
        $dbResultDate = $result->getData();
   
        //按照查出的年 本月 上月进行分组
        $data = [];
        $year = strtotime(date('Y-1-1'));
        $thisMonth = mktime(0,0,0,date('m'),1,date('Y'));
        $lastMonth = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));
        foreach ( $dbResultDate as $value ){
            //年
            $time = strtotime($value['time']);
            if( $time>$year ){
                if( isset($data[$value['customerId']]['year']) ){
                    $data[$value['customerId']]['year']['orderNum'] += $value['orderNum'];
                    $data[$value['customerId']]['year']['orderMoney'] += $value['orderMoney'];
                } else {
                    $data[$value['customerId']]['year']['orderNum'] = $value['orderNum'];
                    $data[$value['customerId']]['year']['orderMoney'] = $value['orderMoney'];
                }
            }
            //月
            if( $time>$thisMonth ){
                if( isset($data[$value['customerId']]['thisMonth']) ){
                    $data[$value['customerId']]['thisMonth']['orderNum'] += $value['orderNum'];
                    $data[$value['customerId']]['thisMonth']['orderMoney'] += $value['orderMoney'];
                } else {
                    $data[$value['customerId']]['thisMonth']['orderNum'] = $value['orderNum'];
                    $data[$value['customerId']]['thisMonth']['orderMoney'] = $value['orderMoney'];
                }
            }
            //上月
            if( $time>$lastMonth && $time < $thisMonth ){
                if( isset($data[$value['customerId']]['lastMonth']) ){
                    $data[$value['customerId']]['lastMonth']['orderNum'] += $value['orderNum'];
                    $data[$value['customerId']]['lastMonth']['orderMoney'] += $value['orderMoney'];
                } else {
                    $data[$value['customerId']]['lastMonth']['orderNum'] = $value['orderNum'];
                    $data[$value['customerId']]['lastMonth']['orderMoney'] = $value['orderMoney'];
                }
            }
        }
    
        foreach($dbResult as &$value) {
        
            //年
            if ( isset($data[$value['id']]['year']) ) {
                $value['year']['orderNum'] = $data[$value['id']]['year']['orderNum'];
                $value['year']['orderMoney'] = $data[$value['id']]['year']['orderMoney'];
            } else {
                $value['year']['orderNum'] = 0;
                $value['year']['orderMoney'] = 0;
            }
        
            //月
            if ( isset($data[$value['id']]['thisMonth']) ) {
                $value['thisMonth']['orderNum'] = $data[$value['id']]['thisMonth']['orderNum'];
                $value['thisMonth']['orderMoney'] = $data[$value['id']]['thisMonth']['orderMoney'];
            } else {
                $value['thisMonth']['orderNum'] = 0;
                $value['thisMonth']['orderMoney'] = 0;
            }
        
            //上月
            if ( isset($data[$value['id']]['lastMonth']) ) {
                $value['lastMonth']['orderNum'] = $data[$value['id']]['lastMonth']['orderNum'];
                $value['lastMonth']['orderMoney'] = $data[$value['id']]['lastMonth']['orderMoney'];
            } else {
                $value['lastMonth']['orderNum'] = 0;
                $value['lastMonth']['orderMoney'] = 0;
            }
        
            //客户本年拜访次数
            if(isset($yearNum[$value['id']])){
                $value['yearNum'] = isset( $yearNum[$value['id']]) ?  $yearNum[$value['id']] : 0;
            } else {
                $value['yearNum'] = 0;
            }
            //客户距离上次多少天
            if(isset($dayNum[$value['id']])){
                $value['dayNum'] = isset( $dayNum[$value['id']]) ?  $dayNum[$value['id']] : 0;
            } else {
                $value['dayNum'] = 0;
            }
        
        }
        
        if(empty($dbResult)){
            return ResultWrapper::success([
                'data'   => [],
                'total'  => 0,
            ]);
        }

        $fields = 'select count(*) as total ';
        $count = $this->objDCustomerRechargeRecord->query($fields.$sql);



        $return = [
            'data' => self::format($dbResult),
            'total' => $count ? $count[0]['total'] : 0
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 距离最近一次未下单统计
     */
    public function intervalNoOrderCustomer($params)
    {

        $where = '';
        if( isset($params['customerName']) && !empty($params['customerName']) ){
            $where .= ' and c.name like "%'.$params['customerName'].'%" ';
        }

        if( isset($params['salesManId']) && !empty($params['salesManId']) ){
            $where .= ' and c.salesManId = '.$params['salesManId'];
        }

        if( isset($params['provinceCode']) && !empty($params['provinceCode']) ){
            $where .= ' and c.provinceCode = '.$params['provinceCode'];
        }

        if( isset($params['cityCode']) && !empty($params['cityCode']) ){
            $where .= ' and c.cityCode = '.$params['cityCode'];
        }

        if( isset($params['districtCode']) && !empty($params['districtCode']) ){
            $where .= ' and c.districtCode = '.$params['districtCode'];
        }
        
        $sql = "select * from ( select b.*,b.createTime as lastTime,now() as nowtime,TIMESTAMPDIFF(day,FROM_UNIXTIME(b.createTime,'%Y%m%d'),CURRENT_DATE()) as intervalDay from (
select DISTINCT c.id,o.createTime,c.name,c.provinceCode,c.cityCode,c.districtCode,c.type,c.salesManId,c.userCenterId,c.shopId,c.departmentId from qianniao_customer_".$this->enterpriseId." c LEFT JOIN qianniao_order_index_".$this->enterpriseId." o on c.id = o.customerId where c.deleteStatus = ".StatusCode::$standard." ".$where."  order by o.createTime desc)b GROUP BY id)tmp where intervalDay >= ".$params['intervalDay']." order by intervalDay desc limit ".$params['offset'].",".$params['limit'];
        $dbResult = $this->objDCustomer->query($sql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        
        //拿到范围内的客户
       $customerIds = [];
       foreach ($dbResult as $value){
           $customerIds[] = $value['id'];
       }
       
       $customerIds = implode(',',$customerIds);
       $objMCustomerCommunication = new MCustomerCommunication($this->enterpriseId);
        //根据客户id查询客户本年拜访次数
        $dbYearNum = $objMCustomerCommunication->getCustomerYearVisitNumber($customerIds);
        if(!$dbYearNum->isSuccess()){
            return ResultWrapper::fail($dbYearNum->getData(),$dbYearNum->getErrorCode());
        }
        $yearNumDbResult = $dbYearNum->getData();
        
        $yearNum = [];
        foreach ($yearNumDbResult as $v){
            $yearNum[$v['customerId']]= $v['yearNum'];//所查出客户本年拜访次数
        }
        
        //根据查出天数范围内的客户查出所对应的日期并归组
        $result = $objMCustomerCommunication->getCustomerDate($customerIds);
        if(!$result->isSuccess()){
            return ResultWrapper::fail($result->getData(),$result->getErrorCode());
        }
        $dbResultDate = $result->getData();
        
        //按照查出的年 本月 上月进行分组
        $data = [];
        $year = strtotime(date('Y-1-1'));
        $thisMonth = mktime(0,0,0,date('m'),1,date('Y'));
        $lastMonth = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));
        foreach ( $dbResultDate as $value ){
            //年
            $time = strtotime($value['time']);
            if( $time>$year ){
                if( isset($data[$value['customerId']]['year']) ){
                    $data[$value['customerId']]['year']['orderNum'] += $value['orderNum'];
                    $data[$value['customerId']]['year']['orderMoney'] += $value['orderMoney'];
                } else {
                    $data[$value['customerId']]['year']['orderNum'] = $value['orderNum'];
                    $data[$value['customerId']]['year']['orderMoney'] = $value['orderMoney'];
                }
            }
            //月
            if( $time>$thisMonth ){
                if( isset($data[$value['customerId']]['thisMonth']) ){
                    $data[$value['customerId']]['thisMonth']['orderNum'] += $value['orderNum'];
                    $data[$value['customerId']]['thisMonth']['orderMoney'] += $value['orderMoney'];
                } else {
                    $data[$value['customerId']]['thisMonth']['orderNum'] = $value['orderNum'];
                    $data[$value['customerId']]['thisMonth']['orderMoney'] = $value['orderMoney'];
                }
            }
            //上月
            if( $time>$lastMonth && $time < $thisMonth ){
                if( isset($data[$value['customerId']]['lastMonth']) ){
                    $data[$value['customerId']]['lastMonth']['orderNum'] += $value['orderNum'];
                    $data[$value['customerId']]['lastMonth']['orderMoney'] += $value['orderMoney'];
                } else {
                    $data[$value['customerId']]['lastMonth']['orderNum'] = $value['orderNum'];
                    $data[$value['customerId']]['lastMonth']['orderMoney'] = $value['orderMoney'];
                }
            }
        }
        
        foreach($dbResult as &$value) {
            
            //年
            if ( isset($data[$value['id']]['year']) ) {
                $value['year']['orderNum'] = $data[$value['id']]['year']['orderNum'];
                $value['year']['orderMoney'] = $data[$value['id']]['year']['orderMoney'];
            } else {
                $value['year']['orderNum'] = 0;
                $value['year']['orderMoney'] = 0;
            }
        
            //月
            if ( isset($data[$value['id']]['thisMonth']) ) {
                $value['thisMonth']['orderNum'] = $data[$value['id']]['thisMonth']['orderNum'];
                $value['thisMonth']['orderMoney'] = $data[$value['id']]['thisMonth']['orderMoney'];
            } else {
                $value['thisMonth']['orderNum'] = 0;
                $value['thisMonth']['orderMoney'] = 0;
            }
        
            //上月
            if ( isset($data[$value['id']]['lastMonth']) ) {
                $value['lastMonth']['orderNum'] = $data[$value['id']]['lastMonth']['orderNum'];
                $value['lastMonth']['orderMoney'] = $data[$value['id']]['lastMonth']['orderMoney'];
            } else {
                $value['lastMonth']['orderNum'] = 0;
                $value['lastMonth']['orderMoney'] = 0;
            }
            
            //客户本年拜访次数
            if(isset($yearNum[$value['id']])){
                $value['yearNum'] = isset( $yearNum[$value['id']]) ?  $yearNum[$value['id']] : 0;
            } else {
                $value['yearNum'] = 0;
            }
        }
 
        if(empty($dbResult)){
            return ResultWrapper::success([
                'data'   => [],
                'total'  => 0,
            ]);
        }

        $sql = "select count(*) as total from ( select b.*,b.createTime as lastTime,now() as nowtime,TIMESTAMPDIFF(day,FROM_UNIXTIME(b.createTime,'%Y%m%d'),CURRENT_DATE()) as intervalDay from (
select DISTINCT c.id,o.createTime,c.name,c.provinceCode,c.cityCode,c.districtCode,c.type,c.salesManId,c.userCenterId,c.shopId,c.departmentId from qianniao_customer_".$this->enterpriseId." c LEFT JOIN qianniao_order_index_".$this->enterpriseId." o on c.id = o.customerId where c.deleteStatus = ".StatusCode::$standard." ".$where."  order by o.createTime desc)b GROUP BY id)tmp where intervalDay >= ".$params['intervalDay']." order by intervalDay desc";
        $count = $this->objDCustomer->query($sql);
        if($count === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
     
        
        $return = [
            'data' => self::format($dbResult),
            'total' => $count ? $count[0]['total'] : 0
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 拉新统计
     */
    public function recommenderStatic($params)
    {
        $where = '';
        
        // 时间筛选
        if (isset($params['startTime']) && !empty($params['startTime'])){
            $where .= '  AND c.createTime BETWEEN '.$params['startTime'].' AND '.$params['endTime'];
        }
        
        if( isset($params['customerId']) && !empty($params['customerId']) ){
            $where .= ' and c.id = '.$params['customerId'];
        }

        if( isset($params['staffId']) && !empty($params['staffId']) ){
            $where .= ' and c.salesManId = '.$params['staffId'];
        }


        $sql = ' from qianniao_customer_'.$this->enterpriseId.' c left join  ( select i.customerId,sum(i.payAmount) as OrderTotalMoney,count(g.skuId) as goodsNum,count(distinct g.orderId) as orderNum from qianniao_order_goods_'.$this->enterpriseId.'_1  g LEFT JOIN qianniao_order_'.$this->enterpriseId.'_1 i on i.id = g.orderId where i.deleteStatus ='.StatusCode::$standard.' and i.auditStatus ='.StatusCode::$auditStatus['auditPass'].' group by i.customerId)b on c.id = b.customerId  where c.recommenderId != 0 and c.deleteStatus = '.StatusCode::$standard.$where.' GROUP BY recommenderId';
        $limit = ' limit '.$params['offset'].','.$params['limit'];
        $listSql = $sql.' ORDER BY recommenderTotal desc';
        $fields = 'SELECT c.recommenderId,c.recommenderType,count(*) as recommenderTotal,b.*';
        $this->objDCustomerRechargeRecord->setTable('qianniao_customer_'.$this->enterpriseId);
        $this->objDCustomerRechargeRecord->setTable('qianniao_order_goods_'.$this->enterpriseId);
        $this->objDCustomerRechargeRecord->setTable('qianniao_order_'.$this->enterpriseId);
        $returnData = $this->objDCustomerRechargeRecord->query($fields.$listSql.$limit);
        if($returnData === false){
            return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
        }
        if(empty($returnData)){
            return ResultWrapper::success([
                'data'   => [],
                'total'  => 0,
            ]);
        }
        $sql = 'select count(*) as total from ('.$fields.$sql.') t';
        $count = $this->objDCustomerRechargeRecord->query($sql);


        $customerIds = [];
        $staffIds  = [];
        foreach ($returnData as $key => $value){
            if( empty($value['recommenderId']) ) continue;
            if($value['recommenderType'] == StatusCode::$roleType['customer']){
                $customerIds[] = $value['recommenderId'];
            }else{
                $staffIds[] = $value['recommenderId'];
            }
        }

        // 根据客户ids批量获取客户名称
        $customerIdBindName = [];
        if( !empty($customerIds) ){
            $dbResult = $this->objDCustomer->select($customerIds, 'id,name');
            if($dbResult === false){
                return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
            }

            foreach ($dbResult as $key => $value){
                $customerIdBindName[$value['id']] = $value['name'];
            }
        }

        // 根据员工ids批量获取员工名称
        $staffIdBindName = [];
        if( !empty($staffIds) ){
            $objDStaff = new DStaff();
            $objDStaff->setTable('qianniao_staff_'.$this->enterpriseId);
            $dbResult = $objDStaff->select($staffIds, 'id,staffName');
            if($dbResult === false){
                return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
            }

            foreach ($dbResult as $key => $value){
                $staffIdBindName[$value['id']] = $value['staffName'];
            }
        }

        // 映射上名称
        foreach ($returnData as $key => $value){
            if($value['recommenderType'] == StatusCode::$roleType['customer']){
                $returnData[$key]['recommenderName'] = isset($customerIdBindName[$value['recommenderId']]) ? $customerIdBindName[$value['recommenderId']] : '';
            }else{
                $returnData[$key]['recommenderName'] = isset($staffIdBindName[$value['recommenderId']]) ? $staffIdBindName[$value['recommenderId']] : '';
            }
        }

        $return = [
            'data' => $returnData,
            'total' => $count ? $count[0]['total'] : 0
        ];
        return ResultWrapper::success($return);
    }
    /**
     * 客户购买记录导出方法
     * @param $result
     * @return void
     * @throws Exception
     */
    public function exportCustomerBuyLog($result)
    {
        //导出到本地
        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 ($result as $v) {                           //循环数据
            $specGroupA = '';
            if(!empty($v['specGroup'])){
                foreach ($v['specGroup'] as $kk =>$vv){
                    $specGroupA .=$vv['specName'].','.$vv['specValueName'].',';
                }
                $specGroup = rtrim($specGroupA, ",") ;//剔除追后的字符串
            }
            $num++;
            if ($num == $limit) {
                ob_flush();         //释放内存
                flush();
            }
            $rows['customerName'] = isset($v['customerName']) ? $v['customerName'] : '';//客户
            $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : '';//商品
            $rows['unitName'] = isset($v['unitName']) ? $v['unitName'] : '';//单位
            $rows['specGroup'] = $specGroup;//属性
            $rows['price'] = isset($v['price']) ? $v['price'] : '';//单价
            $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//购买数量
            $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : '';//其他单位
            $rows['totalMoney'] = isset($v['totalMoney']) ? $v['totalMoney'] : '';//商品总价
            $rows['outNum'] = isset($v['outNum']) ? $v['outNum'] : '';//发货数量
            $rows['goodsCode'] = isset($v['goodsCode']) ? $v['goodsCode'] : '';//商品条码
    
            foreach ($rows as $kk => $vv) {
                $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8');  //转译编码
            }
            fputcsv($fp, $rs);
            
            $rows = [];
        }
    }


    /**
     * 客户分布
     * @return ResultWrapper
     */
    public function getCustomerDistributed()
    {
        $sql = 'select provinceCode,count(provinceCode) as total from qianniao_customer_'.$this->enterpriseId.' where deleteStatus = '.StatusCode::$standard.' group by provinceCode';
        $dbResult = $this->objDUserCenter->query($sql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        $objMSysAreaChina = new MSysAreaChina();

        $areaData = [];
        $noTotal = 0;
        foreach($dbResult as $value){
            if(empty($value['provinceCode'])){
                $noTotal += $value['total'];
            }else{
                $areaName = $objMSysAreaChina->getNameByCode([
                    $value['provinceCode'],
                ]);
                if(empty($areaName[$value['provinceCode']])){
                    $noTotal += $value['total'];
                }else{
                    $areaData[] = [
                        'name' => str_replace('省', '',$areaName[$value['provinceCode']]),
                        'value' => $value['total']
                    ];
                }
            }
        }
        if(!empty($noTotal)){
            $areaData[] = [
                'name' => '未知',
                'value' => $noTotal
            ];
        }
        return ResultWrapper::success($areaData);
    }


    /**
     * 批量设置客户类型
     */
    public function setCustomerType($params)
    {
        if(empty($params['customerIds'])){
            return ResultWrapper::fail('客户数据不能为空',ErrorCode::$notAllowAccess);
        }
        
        //更新数据
        $dbResult = $this->objDCustomer->update(['type'=>$params['type']],['id'=>$params['customerIds']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $objCustomerCache = new CustomerCache();
        //删除缓存
        foreach ($params['customerIds'] as $value){
            $objCustomerCache->delCustomerData($this->enterpriseId,$value);
        }
        return ResultWrapper::success($dbResult);
    }


    public function get($where)
    {
        $data = $this->objDCustomer->get($where);
        return $data;
    }

    public function select($where, $limit, $offset)
    {
        $data = $this->objDCustomer->select($where, '*', 'id DESC', $limit, $offset);
        return $data;
    }

    public function count($where)
    {
        $count = $this->objDCustomer->count($where);
        return $count;

    }


}