<?php
/**
 * 客户联系人管理模块
 * Created by PhpStorm.
 * User: wxj
 * Date: 2019/10/30
 * Time: 14:02
 */

namespace JinDouYun\Model\Customer;



use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Cache\CustomerCache;

use JinDouYun\Model\MBaseModel;
use JinDouYun\Model\SysAreaChina\MSysAreaChina;
use JinDouYun\Model\Customer\MCustomer;

use JinDouYun\Dao\Customer\DCustomerContact;

class MCustomerContact extends MBaseModel {

    private $objDCustomerContact;
    private $enterpriseId;
    private $userCenterId;
    private $cutTable = 1;//客户联系人按照企业id分表

    public function __construct($enterpriseId, $userCenterId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        parent::__construct($this->enterpriseId, $this->userCenterId);
        $this->objDCustomerContact = new DCustomerContact('default');
        $tableName = $this->objDCustomerContact->getTableName('qianniao_customer_contact_', $enterpriseId, $this->cutTable);
        $this->objDCustomerContact->setTable($tableName);
    }

    /**
     * 添加客户联系人
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addCustomerContact($params)
    {
        $objMCustomer = new MCustomer($this->enterpriseId, $this->userCenterId);
        $customerUserCenterId = $objMCustomer->getUserCenterIdByCustomerId($params['customerId']);
        if(empty($customerUserCenterId)){
            return ResultWrapper::fail('当前客户不存在', ErrorCode::$contentNotExists);
        }

        $dbResult = $this->objDCustomerContact->get(['customerId' => $params['customerId'], 'mobile' => $params['mobile']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerContact->error(), ErrorCode::$dberror);
        }
        if(!empty($dbResult)){
            return ResultWrapper::fail('手机号已存在', ErrorCode::$paramError);
        }
        unset($dbResult);
        $CustomerContactId = $this->objDCustomerContact->insert($params);

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


        //$objMCustomer->updateEsData($params['customerId']);

        $objCustomerContactCache = new CustomerCache();
        $objCustomerContactCache->delCustomerData($this->enterpriseId, $params['customerId']);
        $objCustomerContactCache->delCustomerUserData($this->enterpriseId, $customerUserCenterId);
        return ResultWrapper::success($CustomerContactId);

    }

    /**
     * 获取指定客户联系人信息
     */
    public function getCustomerContactInfo($CustomerContactIds)
    {
        $dbResult = $this->objDCustomerContact->select($CustomerContactIds);

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


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

        $updateCustomerContactId = $params['id'];
        unset($params['id']);

        if(isset($params['area'])) unset($params['area']);

        $dbResult = $this->objDCustomerContact->update($params, $updateCustomerContactId);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerContact->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 删除客户联系人
     *
     * @param array $delCustomerContactIds  要删除的客户联系人id
     *
     * @return ResultWrapper
     */
    public function delCustomerContact($delCustomerContactIds)
    {
        if (empty($delCustomerContactIds)) {
            return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
        }
        $dbResult = $this->objDCustomerContact->update( ['deleteStatus'=>StatusCode::$delete], $delCustomerContactIds );

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

    /**
     * 客户联系人启用和禁用
     * @param array $params
     * @return ResultWrapper
     */
    public function updateCustomerContactStatus($params)
    {
        $dbResult = $this->objDCustomerContact->update( ['status'=>$params['status']], $params['CustomerContactId'] );

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

    /**
     * 获取所有客户联系人数据
     *
     * @param array $selectParams 过滤条件
     *
     * @return ResultWrapper
     */
    public function getAllCustomerContact($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $selectParams['deleteStatus'] = StatusCode::$standard;
        $dbResult = $this->objDCustomerContact->select($selectParams, '*', 'createTime desc', $limit, $offset);

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

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

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

        return ResultWrapper::success($return);

    }

    /**
     * 获取客户id对应的联系人信息
     * @param $customerIds  mixed  客户id
     * @return array|bool
     * @throws Exception
     */
    public function getContactInfoById($customerIds) {
        if(is_array($customerIds)) {
            $where = "customerId in (". implode(',',$customerIds) .")";
        }else {
            $where = "customerId = $customerIds";
        }
        $where .= ' AND deleteStatus = ' . StatusCode::$standard;
        $dbResult = $this->objDCustomerContact->select($where, '*');
        if($dbResult ===  false) {
            return [];
        }
        $objMSysAreaChina = new MSysAreaChina();
        foreach ($dbResult as &$contact) {
            $areaName = $objMSysAreaChina->getNameByCode([
                $contact['provinceCode'],
                $contact['cityCode'],
                $contact['districtCode']
            ]);
            $contact['area']['provinceName'] = isset($areaName[$contact['provinceCode']]) ? $areaName[$contact['provinceCode']] : '';
            $contact['area']['cityName'] = isset($areaName[$contact['cityCode']]) ? $areaName[$contact['cityCode']] : '';
            $contact['area']['districtName'] = isset($areaName[$contact['districtCode']]) ? $areaName[$contact['districtCode']] : '';
            $contact['area']['address'] = $contact['address'];
        }
        return $dbResult;
    }
    
}