<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2017/11/21
 * Time: 8:59
 */

namespace App\Modules\Channel\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class Channel extends Model
{
    protected $table = 'distribution_channels';
    protected $fillable = ['id', 'name', 'pay_merchant_id', 'phone', 'nickname', 'person_in_charge_name', 'latest_login_time', 'remark', 'latest_login_ip', 'password', 'register_ip', 'is_enabled', 'distribution_manages_id', 'channel_user_id', 'site_nick_name','is_outer_site','is_old_user_site','is_yq_move'];

    /**
     * 获取所有渠道
     * @param array $params
     * @return mixed
     */
    static function getAllChannels($params = [])
    {
        $sqlObj = self::orderBy('created_at', 'desc');
        if (isset($params['channel_user_id']) && $params['channel_user_id']) {
            $sqlObj->where('channel_user_id', $params['channel_user_id']);
        }
        return $channelResult = $sqlObj->get();
    }

    static function getByPhone($phone)
    {
        return self::where('phone', $phone)->first();
    }

    static function getById($id)
    {
        return self::where('id', $id)->first();
    }

    static function getChannelNameById($id)
    {
        return self::where('id', $id)->select('name')->first();
    }

    static function getUserIdById($id)
    {
        return self::where('id', $id)->select('channel_user_id')->first();
    }

    static function getIdByNickName($nickname)
    {
        return self::where('nickname', 'like', '%' . $nickname . '%')->select('id')->get();
    }

    static function getChannelCompanyNameById($id)
    {
        $companies = self::select('companies.name')
            ->join('channel_users','channel_users.id','=','distribution_channels.channel_user_id')
            ->join('companies','companies.id','=','channel_users.company_id')
            ->where('distribution_channels.id',$id)
            ->first();
        if($companies){
            return $companies->name;
        }
        return '';
    }
    
    /**
     * 获取渠道公司等信息
     */
    static function get_distribution_channel_info($distribution_channel_id)
    {
    	$info = self::select('channel_users.company_name','channel_users.person_in_charge_name')
    	->join('channel_users','channel_users.id','=','distribution_channels.channel_user_id')
    	->where('distribution_channels.id',$distribution_channel_id)
    	->first();
 
    	return $info;
    }

    static function getChanneIdByCompanyId($companyId)
    {
        return self::select('distribution_channels.id')
            ->join('channel_users','channel_users.id','=','distribution_channels.channel_user_id')
            ->join('companies','companies.id','=','channel_users.company_id')
            ->where('companies.id',$companyId)
            ->get()->pluck('id')->all();
    }

    static function getSelectChannelData($id)
    {
        return self::where('id', $id)->select('name')->first();
    }

    static function getChannelNicknameById($id)
    {
        return self::where('id', $id)->select('nickname')->first();
    }

    //创建渠道
    static function createChannel($params)
    {
        $name = isset($params['name']) ? trim($params['name']) : '';
        $pay_type = isset($params['pay_type']) ? trim($params['pay_type']) : 'ALLINPAY_NALAN';
        $phone = isset($params['phone']) ? trim($params['phone']) : '';
        $password = isset($params['password']) ? trim($params['password']) : '';
        $nickname = isset($params['nickname']) ? trim($params['nickname']) : '';
        $latest_login_time = date("Y-m-d H:i:s");
        $remark = isset($params['remark']) ? trim($params['remark']) : '';
        $person_in_charge_name = isset($params['person_in_charge_name']) ? trim($params['person_in_charge_name']) : '';
        $distribution_manages_id = isset($params['distribution_manages_id']) ? trim($params['distribution_manages_id']) : 0;
        $latest_login_ip = $register_ip = isset($params['register_ip']) ? trim($params['register_ip']) : '';
        $channel_user_id = isset($params['channel_user_id']) ? trim($params['channel_user_id']) : '';

        //if(!$phone || !$password) return response()->error('PARAM_ERROR');

        return self::create(compact('phone', 'password', 'name', 'pay_type', 'nickname', 'latest_login_ip', 'latest_login_time', 'remark', 'register_ip', 'distribution_manages_id', 'person_in_charge_name', 'channel_user_id'));
    }

    //修改密码
    static function modifyPassword($phone, $password)
    {
        return self::where('phone', $phone)->update(compact('password'));
    }

    /**
     * 获取渠道列表
     * @param $id 渠道ID
     * @param $params []
     *                  name:渠道名称 可选
     *                  nickname:渠道昵称 可选
     *                  pay_merchant_id: 支付通道 可选
     *                  distribution_manages_id: 管理员 可选
     *                  phone:电话 可选
     *                  person_in_charge_name:负责人 可选
     *                  remark:备注 可选
     *                  is_enabled: 是否开通 0:未审核； 1:审核通过
     * @return mixed
     */
    public static function updateChannelData($id, $params = [])
    {
        $data = self::getById($id);
        if (!empty($data)) {
            if (isset($params['name']) && $params['name']) {
                $data['name'] = $params['name'];
            }
            if (isset($params['nickname']) && $params['nickname']) {
                $data['nickname'] = $params['nickname'];
            }
            if (isset($params['pay_merchant_id']) && $params['pay_merchant_id'] && is_numeric($params['pay_merchant_id'])) {
                $data['pay_merchant_id'] = $params['pay_merchant_id'];
            }
            if (isset($params['distribution_manages_id']) && $params['distribution_manages_id'] && is_numeric($params['distribution_manages_id'])) {
                $data['distribution_manages_id'] = $params['distribution_manages_id'];
            }
            if (isset($params['phone']) && $params['phone']) {
                $data['phone'] = $params['phone'];
            }
            if (isset($params['person_in_charge_name']) && $params['person_in_charge_name']) {
                $data['person_in_charge_name'] = $params['person_in_charge_name'];
            }
            if (isset($params['remark']) && $params['remark']) {
                $data['remark'] = $params['remark'];
            }
            if (isset($params['is_enabled']) && is_numeric($params['is_enabled']) && ($params['is_enabled'] == 0 || $params['is_enabled'] == 1)) {
                $data['is_enabled'] = $params['is_enabled'];
            }
            $data->save();
        }
        return $data;
    }

    /**
     * 获取渠道列表
     * @param $params []
     *                  channel_id:渠道ID 可选
     *                  channel_name:渠道名称 可选
     *                  search_name: 搜索名称
     *                  start_date:开始时间 可选
     *                  end_date:结束时间 可选
     *                  is_enabled: 是否开通 0:未审核； 1:审核通过
     *                  distribution_manages_id: 管理员 可选
     * @param $isAll
     * @return mixed
     */
    public static function getChannelList($params = [], $isAll = '')
    {
        $search_object = self::select([
            'distribution_channels.id',
            'distribution_channels.name',
            'distribution_channels.pay_merchant_id',
            'distribution_channels.phone',
            'distribution_channels.nickname',
            'distribution_channels.person_in_charge_name',
            'distribution_channels.latest_login_time',
            'distribution_channels.remark',
            'distribution_channels.latest_login_ip',
            'distribution_channels.password',
            'distribution_channels.register_ip',
            'distribution_channels.is_enabled',
            'distribution_channels.distribution_manages_id',
            'distribution_channels.created_at',
            'distribution_manages.account as distribution_manages_account',
            'distribution_manages.number as distribution_manages_number',
            'distribution_manages.nickname as distribution_manages_nickname',
        ])
            ->leftjoin('distribution_manages', 'distribution_manages.id', '=', 'distribution_channels.distribution_manages_id')
            ->orderBy('distribution_channels.created_at', 'desc')
            ->orderBy('distribution_channels.id', 'asc');


        if (isset($params['channel_id']) && $params['channel_id']) $search_object->where('distribution_channels.id', $params['channel_id']);
        if (isset($params['channel_name']) && $params['channel_name']) $search_object->where('distribution_channels.name', 'like', "%" . $params['channel_name'] . "%");

        if (isset($params['search_name']) && $params['search_name']) {
            $search_object->where(function ($query) use ($params) {
                $query->where('distribution_channels.name', 'like', "%" . $params['search_name'] . "%")
                    ->orWhere('distribution_channels.nickname', 'like', "%" . $params['search_name'] . "%")
                    ->orWhere('distribution_channels.person_in_charge_name', 'like', "%" . $params['search_name'] . "%");
            });
        }

        if(isset($params['company_name']) && $params['company_name']) {
            $search_object->join('channel_users','channel_users.id','=','distribution_channels.channel_user_id')
                ->join('companies','companies.id','=','channel_users.company_id')
                ->where('companies.name','like','%'.$params['company_name'].'%');

        }

        if (isset($params['start_date']) && $params['start_date']) $search_object->where('distribution_channels.created_at', '>=', $params['start_date']);
        if (isset($params['end_date']) && $params['end_date']) $search_object->where('distribution_channels.created_at', '<=', $params['end_date']);

        if (isset($params['is_enabled']) && is_numeric($params['is_enabled'])) {
            $search_object->where('distribution_channels.is_enabled', $params['is_enabled']);
        }

        if (isset($params['distribution_manages_id']) && is_numeric($params['distribution_manages_id'])) {
            $search_object->where('distribution_channels.distribution_manages_id', $params['distribution_manages_id']);
        }

        if ($isAll) {
            return $search_object->get();

        } else {

            return $search_object->paginate();
        }
    }

    /**
     * 获取当前渠道经理下所有渠道ID
     * @param $distribution_manages_id
     * @return mixed
     */
    public static function getChannelIdList($distribution_manages_id = '')
    {
        $search_object = self::select('distribution_channels.id')->orderBy('distribution_channels.id', 'asc');

        if ($distribution_manages_id) {
            $search_object->where('distribution_channels.distribution_manages_id', $distribution_manages_id);
        }

        $result = $search_object->get();

        $dataArray = [];
        foreach ($result as $r) {
            $dataArray[] = $r['id'];
        }
        return $dataArray;
    }

    /**
     * 获取账号下默认渠道
     */
    static function getDefault($channel_user_id)
    {
        return self::where('channel_user_id', $channel_user_id)->orderBy('id', 'asc')->first();
    }

    /**
     *  通过渠道ID、用户ID获取渠道
     */
    static function getUserChannel($distribution_channle_id, $channel_user_id)
    {
        return self::where('id', $distribution_channle_id)->where('channel_user_id', $channel_user_id)->first();
    }

    /**
     * 获取渠道ID
     * @param $channel_user_id
     */
    static function getUserChannelIds($channel_user_id)
    {
        return self::where('channel_user_id', $channel_user_id)->get()->pluck('id')->all();
    }

    /**
     * 根据账号ID获取渠道列表
     * @return mixed
     */
    static function getByChannelUserId($channel_user_id,$is_enabled=1)
    {
        return self::where('channel_user_id', $channel_user_id)->where('is_enabled', $is_enabled)->orderBy('id', 'asc')->get();
    }
    
    static function deleteChannel($distribution_channel_id, $channel_user_id){
    	return self::where('channel_user_id', $channel_user_id)->where('id', $distribution_channel_id)->update(['is_enabled'=>0,'updated_at'=>now()]);
    }
    
    /**
     * 更新外站开关
     * @return mixed
     */
    static function updateDistributionOuterSiteSwitch($distribution_channel_id,$status)
    {
    	return self::where('id', $distribution_channel_id)->update(['is_outer_site'=>$status]);
    }
    
    /**
     * 更新新老站点开关
     * @return mixed
     */
    static function updateDistributionOldUserSiteSwitch($distribution_channel_id,$status)
    {
    	return self::where('id', $distribution_channel_id)->update(['is_old_user_site'=>$status]);
    }
    
    /**
     * 获取渠道信息
     * @return mixed
     */
    static function getDistributionChannel($distribution_channel_id)
    {
    	return self::where('id', $distribution_channel_id)->select('id','phone','nickname','channel_user_id','pay_merchant_id','is_outer_site','is_old_user_site','is_outer_site','site_nick_name','is_yq_move')->first();
    }
    

    static function getByDistributionManagesId($distribution_manage_id)
    {
        $res = self::where('distribution_manages_id', $distribution_manage_id)->select('id')->get();
        $data = [];
        foreach ($res as $item) {
            $data[] = $item->id;
        }
        return $data;
    }
}