<?php
/**
 * 客户渠道(类型)模块
 * Created by PhpStorm.
 * User: wxj
 * Date: 2019/10/30
 * Time: 14:02
 */

namespace JinDouYun\Model\System;

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

use JinDouYun\Dao\System\DCustomerSource;
use JinDouYun\Dao\System\DCustomerSourceDeploy;


class MCustomerSource
{

    private $objDCustomerSource;
    private $objDCustomerSourceDeploy;
    private $enterpriseId;

    public function __construct($enterpriseId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->objDCustomerSource = new DCustomerSource('default');
        $this->objDCustomerSourceDeploy = new DCustomerSourceDeploy('default');

    }

    /**
     * 添加客户渠道(类型)
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addCustomerSource($params)
    {

        //添加source名称表
        $sourceInsert = [
            'name' => $params['name'],
            'type' => 0,
            'createTime' => time(),
            'updateTime' => time(),
            'modelType' => getArrayItem($params,'modelType',0),
        ];
        $dbResult = $this->objDCustomerSource->insert($sourceInsert);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        //如果新增数据为默认 把表里所有数据改为非默认
        if($params['defaultStatus'] == StatusCode::$standard){
            $endDbResult = $this->objDCustomerSourceDeploy->update(['defaultStatus' => StatusCode::$delete, 'updateTime' => time()], ['enterpriseId' => $this->enterpriseId]);
            if($endDbResult === false){
                return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
            }
        }
        //添加deploy表
        $deployInsert = [
            'sId' => $dbResult,
            'deleteStatus' => StatusCode::$standard,
            'defaultStatus' => $params['defaultStatus'],
            'enableStatus' => $params['enableStatus'],
            'createTime' => time(),
            'updateTime' => time(),
            'enterpriseId' => $this->enterpriseId,
        ];
        unset($dbResult);
        $dbResult = $this->objDCustomerSourceDeploy->insert($deployInsert);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取指定客户渠道(类型)信息,获取联系人信息
     * @param $CustomerSourceIds
     * @return ResultWrapper
     * @throws Exception
     */
    public function getCustomerSourceInfo($CustomerSourceIds)
    {
        //获取名称和配置信息
        $sql = 'select s.id,s.name,s.type,d.defaultStatus,d.enableStatus from '.$this->objDCustomerSource->get_Table().' s left join '.$this->objDCustomerSourceDeploy->get_Table().' d on s.id = d.sId where s.id = '.$CustomerSourceIds.' and deleteStatus = '.StatusCode::$standard;
        $dbResult = $this->objDCustomerSource->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        $dbResult = array_shift($dbResult);
        return ResultWrapper::success($dbResult);
    }

        /**
     * 编辑客户渠道(类型)
     * 事务修改联系人信息
     * @param int|array $params 修改客户渠道(类型)的数据
     *
     * @return ResultWrapper
     * @throws Exception
     */
    public function editCustomerSource($params)
    {
        //传来的是source表的id
        //查询source表
        $dbResult = $this->objDCustomerSource->get(['id' => $params['id']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        }
        //type = 1 不可编辑
        if($dbResult['type'] == 1){
            return ResultWrapper::fail('系统默认不可编辑', ErrorCode::$dberror);
        }
        unset($dbResult);
        //查询配置表deploy里有没有配置
        $dbResult = $this->objDCustomerSourceDeploy->get(['sId' => $params['id']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        }
        //修改source表的名称
        $midDbResult = $this->objDCustomerSource->update(['modelType' => $params['modelType'],'name' => $params['name'], 'updateTime' => time()], ['id' => $params['id']]);
        if($midDbResult === false){
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        //如果新增数据为默认 把表里所有数据改为非默认
        if($params['defaultStatus'] == StatusCode::$standard){
            $endDbResult = $this->objDCustomerSourceDeploy->update(['defaultStatus' => StatusCode::$delete, 'updateTime' => time()], ['enterpriseId' => $this->enterpriseId]);
            if($endDbResult === false){
                return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
            }
        }
        $data = [
            'sId' => $params['id'],
            'deleteStatus' => StatusCode::$standard,
            'defaultStatus' => $params['defaultStatus'],
            'enableStatus' => $params['enableStatus'],
            'updateTime' => time(),
            'enterpriseId' => $this->enterpriseId,
        ];
        if(empty($dbResult)){
            //没有配置
            //如果没有 新增一条
            $data['createTime'] = time();
            $data['enterpriseId'] = $this->enterpriseId;
            $finalDbResult = $this->objDCustomerSourceDeploy->insert($data);
        }else{
            //如果有 则编辑
            $finalDbResult = $this->objDCustomerSourceDeploy->update(['defaultStatus' => StatusCode::$standard, 'updateTime' => time()], ['id' => $dbResult['id']]);
        }
        if ($finalDbResult === false) {
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 删除客户渠道(类型)
     *
     * @param array $delCustomerSourceIds 要删除的客户渠道(类型)id
     * @return ResultWrapper
     * @throws Exception
     */
    public function delCustomerSource($delCustomerSourceIds)
    {
        //传来的是source表的id
        if (empty($delCustomerSourceIds)) {
            return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
        }

        $dbResult = $this->objDCustomerSourceDeploy->update(['deleteStatus' => StatusCode::$delete, 'updateTime' => time()], ['sId' => $delCustomerSourceIds]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 客户渠道(类型)启用和禁用
     * @param array $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function updateCustomerSourceStatus($params)
    {
        //传来的是source表的id
        //查询配置表deploy里有没有配置
        $dbResult = $this->objDCustomerSourceDeploy->get(['enterpriseId' => $this->enterpriseId, 'sId' => $params['id']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            //没有配置
            //如果没有 新增一条 启用状态为传参
            $insert = [
                'sId' => $params['id'],
                'deleteStatus' => StatusCode::$standard,
                'defaultStatus' => StatusCode::$delete,
                'enableStatus' => $params['enableStatus'],
                'createTime' => time(),
                'updateTime' => time(),
                'enterpriseId' => $this->enterpriseId,
            ];
            $finalDbResult = $this->objDCustomerSourceDeploy->insert($insert);
        }else{
            //把这条数据启用状态改为启用
            $finalDbResult = $this->objDCustomerSourceDeploy->update(['enableStatus' => $params['enableStatus'], 'updateTime' => time()], ['id' => $dbResult['id']]);
        }
        if ($finalDbResult === false) {
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 客户渠道(类型)默认
     * @param array $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function updateDefaultStatus($params)
    {
        //传来的是source表的id
        //查询配置表deploy里有没有配置
        $dbResult = $this->objDCustomerSourceDeploy->get(['enterpriseId' => $this->enterpriseId, 'sId' => $params['id']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        }
        //把该企业其他配置改为非默认
        $midDbResult = $this->objDCustomerSourceDeploy->update(['defaultStatus' => StatusCode::$delete, 'updateTime' => time()], ['enterpriseId' => $this->enterpriseId]);
        if($midDbResult === false){
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            //没有配置
            //如果没有 新增一条 默认状态为默认
            $insert = [
                'sId' => $params['id'],
                'deleteStatus' => StatusCode::$standard,
                'defaultStatus' => StatusCode::$standard,
                'enableStatus' => StatusCode::$standard,
                'createTime' => time(),
                'updateTime' => time(),
                'enterpriseId' => $this->enterpriseId,
            ];
            $finalDbResult = $this->objDCustomerSourceDeploy->insert($insert);
        }else{
            //如果有 把这条数据默认状态改为默认
            $finalDbResult = $this->objDCustomerSourceDeploy->update(['defaultStatus' => StatusCode::$standard, 'updateTime' => time()], ['id' => $dbResult['id']]);
        }
        if ($finalDbResult === false) {
            return ResultWrapper::fail($this->objDCustomerSourceDeploy->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 根据ids获取分类名称
     * @param $customerSourceIds
     * @return ResultWrapper
     */
    public function getCustomerSourceNameByIds($customerSourceIds)
    {
        $dbResult = $this->objDCustomerSource->select(['id' => $customerSourceIds]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取客户类型(不分页)
     * @param array $selectParams
     * @return ResultWrapper
     */
    public function getCustomerSourceList($selectParams = [])
    {
        $selectParams['enterpriseId'] = $this->enterpriseId;
        $selectParams['deleteStatus'] = StatusCode::$standard;
        $selectParams['enableStatus'] = StatusCode::$standard;

        $sql = 'select s.id,s.`name`,s.type,if(d.enterpriseId='.$this->enterpriseId.',d.defaultStatus,'.StatusCode::$delete.') as defaultStatus,if(d.enterpriseId='.$this->enterpriseId.',d.enableStatus,'.StatusCode::$standard.') as enableStatus ,d.enterpriseId,s.isEvidence from '.$this->objDCustomerSource->get_Table().' s left join '.$this->objDCustomerSourceDeploy->get_Table().' d on d.sId = s.id where d.enterpriseId = '.$selectParams["enterpriseId"].' and d.deleteStatus = '.$selectParams['deleteStatus'].' and d.enableStatus = '.$selectParams['enableStatus'].' or (s.type = 1 and s.id not in(select sId from '.$this->objDCustomerSourceDeploy->get_Table().' where enterpriseId = '.$this->enterpriseId.' and deleteStatus = '.StatusCode::$standard.')) GROUP BY s.id order by s.createTime,s.id asc';
        $dbResult = $this->objDCustomerSource->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        $returnData = [];
        foreach($dbResult as $value){
            $array = [
                'id' => $value['id'],
                'name' => $value['name'],
                'type' => $value['type'],
                'isEvidence' => $value['isEvidence'],
                'defaultStatus' => empty($value['defaultStatus']) ? StatusCode::$delete : $value['defaultStatus'],
                'enableStatus' => empty($value['enableStatus']) ? StatusCode::$standard : $value['enableStatus'],
            ];
            $returnData[] = $array;
        }
        return ResultWrapper::success($returnData);
    }

    /**
     * 获取企业下的所有客户渠道(类型)数据
     *
     * @param array $selectParams 过滤条件
     *
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllCustomerSource($selectParams = [])
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $selectParams['deleteStatus'] = StatusCode::$standard;
        $selectParams['enterpriseId'] = $this->enterpriseId;

        $sql = 'select s.id,s.`name`,s.modelType,s.type,s.isEvidence,d.defaultStatus,d.enableStatus,d.enterpriseId from '.$this->objDCustomerSource->get_Table().' s left join '.$this->objDCustomerSourceDeploy->get_Table().' d on d.sId = s.id and d.enterpriseId = '.$selectParams["enterpriseId"].' where s.type = 1 or s.id in(select sId from '.$this->objDCustomerSourceDeploy->get_Table().' where enterpriseId = '.$selectParams['enterpriseId'].' and deleteStatus = '.$selectParams['deleteStatus'].') order by s.createTime,s.id asc limit '.$offset.','.$limit;
        $dbResult = $this->objDCustomerSource->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        $returnData = [];
        foreach($dbResult as $value){
            $array = [
                'id' => $value['id'],
                'name' => $value['name'],
                'type' => $value['type'],
                'modelType' => $value['modelType'],
                'defaultStatus' => empty($value['defaultStatus']) ? StatusCode::$delete : $value['defaultStatus'],
                'enableStatus' => empty($value['enableStatus']) ? StatusCode::$standard : $value['enableStatus'],
            ];
            $returnData[] = $array;
        }
        unset($dbResult);
        $countSql = 'select count(*) as count from '.$this->objDCustomerSource->get_Table().' where type = 1 or id in(select sId from '.$this->objDCustomerSourceDeploy->get_Table().'  where enterpriseId = '.$selectParams['enterpriseId'].' and deleteStatus = '.$selectParams['deleteStatus'].')';
        $dbResult = $this->objDCustomerSource->query($countSql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        $countArray = array_shift($dbResult);
        $total = $countArray['count'];
        unset($dbResult);
        $return = [
            'data'  => $returnData,
            'total' => ($total) ? intval($total) : 0,
        ];

        return ResultWrapper::success($return);

    }

    /**
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getCustomer($selectParams)
    {
        $dbResult=$this->objDCustomerSource->select($selectParams,'name');
        if ($dbResult===false){
            return ResultWrapper::fail($this->objDCustomerSource->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }
}