<?php

/**
 * 平台服务
 * 平台管理服务
 * @author lixiaolin
 * @Date: 2021/4/2
 * @Time: 下午13:50
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Models\Pt;
use BlueCity\Core\Service\Service;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use DB;
class PlatformService extends Service
{
    public static $instance;
    public $modelMain = null;

    public function __construct()
    {
        $this->modelMain = new Pt();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 根据条件搜索数据内容
     *
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function search($param, $columns = array('*'), $page = 1, $pageSize = 20,$session='')
    {
        $where = [];
        if ($session['admin_groupnew'] != 7){//管理员可以看全部
            $where[] = ['company_id', '=', $session['company_id']];
        }
        if ($param['type']) {
            $where[] = ['type', '=', $param['type']];
        }
        if ($param['pt_name']) {//平台名称
            $where[] = ['pt_name', 'like', '%'.$param['pt_name'] . '%'];
        }
        if ($param['pt_zt']) {//状态 1:启用;2:停用
            $where[] = ['pt_zt', '=', $param['pt_zt']];
        }
        if ($param['three_pd']) {//0:自家;1:第三方
            $where[] = ['three_pd', '=', $param['three_pd']];
        }
        if ($param['p_paytype']) {//开票公司
            $where[] = ['p_paytype', '=', $param['p_paytype']];
        }
        if ($param['bus_type']) {
            if ($param['bus_type'] == 2) {
                $where[] = ['bus_type', '=', 2];
            } else {
                $where[] = ['bus_type', '!=', 2];
            }
        }
        if ($param['sord_asc']) {//字母排序
            $orderBy[0] = 'sord';
            $orderBy[1] = $param['sord_asc'];
        }else{
            //$orderBy[0] = 'id';
            $orderBy[0] = 'sord';
            $orderBy[1] = 'ASC';
        }
        $count = $this->modelMain
            ->where($where)
            ->count();
        $totalPage = ceil($count / $pageSize);
        if ($pageSize > 0) {
            $offset = ($page - 1) * $pageSize;

            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                //->orderBy('sord','ASC')
                ->orderBy($orderBy[0], $orderBy[1])
                ->offset($offset)
                ->limit($pageSize)
                ->get();
        } else {
            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                //->orderBy('sord','ASC')
                ->orderBy($orderBy[0], $orderBy[1])
                ->get();
        }
        $result = [];
        $result['page'] = ['totalPage' => $totalPage, 'count' => $count, 'page' => $page, 'page_size' => $pageSize];
        $result['list'] = $list;

        return $result;
    }

    public function formatPageContent($token, $priID, $data)
    {
        $all_button = BmmcService::wherebutton($token, $priID);
        $addPt = BmmcService::getTopButton('addPt,export', '', $all_button);
        $data['button_top'] = $addPt['button_top'] ?? [];//顶部按钮
        $data['button_search'] = $addPt['button_search'] ?? [];//搜索栏按钮
        $list = $data['list'];
        if (!$list->isEmpty()) {
            $invoiceType = PlatformService::getInvoiceType();
            $list = $data['list']->toArray();
            foreach ($list as $k => $v) {
                if($v['cd_ids'] == ''){
                    $list[$k]['cd_ids'] = [];
                }else{
                    $list[$k]['cd_ids'] = CommonService::strToint(explode(',', $v['cd_ids']));
                }
                if($v['gs_bids'] == ''){
                    $list[$k]['gs_bids'] = [];
                }else{
                    $list[$k]['gs_bids'] = CommonService::strToint(explode(',', $v['gs_bids']));
                }
                //            $v = $v->toArray();
                // -----------button 处理开始-----------
                $button = BmmcService::getListButton(['delPt', 'editPt','prerecharge'], $all_button);//编辑，删除按钮
                $list[$k]['button_one'] = $button['button_one'] ?? [];
                $list[$k]['button_two'] = $button['button_two'] ?? [];
                $list[$k]['button_three'] = $button['button_three'] ?? [];
                // -----------button 处理结束-----------

                // -----------数据内容描述开始-----------
                //            $bmmc_name = (new BmmcService())->find($v['admin_groupnew'], ['bmmc_name']);
                $list[$k]['bmmc_name'] = '平台';
                if ($v['three_pd'] == 0) {
                    $list[$k]['three_pd_name'] = "自有";
                } elseif ($v['three_pd'] == 1) {
                    $list[$k]['three_pd_name'] = "第三方";
                }
                if ($v['pt_zt'] == 1) {
                    $list[$k]['pt_zt_name'] = "启用";
                } elseif ($v['pt_zt'] == 2) {
                    $list[$k]['pt_zt_name'] = "停用";
                }
                $list[$k]['p_paytype_name'] = $invoiceType[$v['p_paytype']] ?? '暂无';
                //            if ($v['p_paytype'] == 1) {
                //                $list[$k]['p_paytype_name'] = "无";
                //            } elseif ($v['p_paytype'] == 2) {
                //                $list[$k]['p_paytype_name'] = "速电付款";
                //            } elseif ($v['p_paytype'] == 5) {
                //                $list[$k]['p_paytype_name'] = "蓝城付款";
                //            } elseif ($v['p_paytype'] == 6) {
                //                $list[$k]['p_paytype_name'] = "个人付款";
                //            }
                // -----------数据内容描述结束-----------
            }
            $data['list'] = $list;
        }

        return $data;
    }

    public static function getInvoiceType( $type = true)
    {
       // $invoiceType = array(array('type'=>'1','name'=>'暂无'),array('type'=>'2','name'=>'速电付款'),array('type'=>'5','name'=>'蓝城付款'),array('type'=>'6','name'=>'个人付款'));
        $invoiceType = ServiceCenterService::getTypeName();
        if($type){
            $invoiceType = array_column($invoiceType, 'name','type');
        }
        return $invoiceType;
    }

    public static function getStates()
    {
        return [1 => "启动", 2 => "停用"];
    }

    public static function getBusType()
    {
        return [1 => 'B2C', 2 => "B2B"];
    }

    public static function getPdName()
    {
        return [0 => '自有', 1 => "第三方"];
    }

    /**
     * @param int $id
     *
     * @param int $enable
     * @return mixed
     */
    public function setEnable(int $id, $enable = 1)
    {
        return $this->modelMain->where('id', $id)
            ->update(['enabled' => $enable]);
    }

    /**
     * 获取平台公用接口展示数据
     *
     * @param array $ptIDs 用户可操作平台id组
     * @param sting $key
     *
     * @return mixed $data
     */
    public static function getAll($ptIDs = true, $key = '')
    {
        $data = [];
        $ptList = RedisService::redisGet('ptList');
        if ($ptList && $ptIDs) {
            $data = $ptList;
//            $data = CommonService::filterIds($ptIDs, $ptList, 'id');
        } else {
            $ptData = pt::select('id', 'sord' , 'pt_name' ,'three_pd','pt_zt','cd_ids','gs_bids','company_id');
           /* if ($session&&$session['admin_groupnew'] != 7){
                $ptData = $ptData->where('company_id',$session['company_id']);
            }*/

            $ptData = $ptData->get()->toArray();


//            $data = CommonService::filterIds($ptIDs, $ptData, 'id');
            $data = $ptData;
            RedisService::redisSet('ptList', $ptData);
        }
        if ($key) {
            $data = CommonService::jointArrayKey($data, $key);
        }
        return $data;
    }
    /**
     * 获取平台数据
     * @param int $id
     * @param $fields
     * @return int
     * @author du 2021年8月6日上午9:49:50
     */
    public static function getFieldsById($id, $fields = []){
        $db = new Pt();
        if(count($fields) == 1){
            $type = 'value';
        }else{
            $type = 'first';
        }
        $platForm = CommonService::getMysqlData($db, ['id'=>$id],$fields,[],$type);

    	return $platForm;
    }

    /**|---------------------------------------------------------------------------------
     * @name 查询平台信息
     * @param string $key 查询键
     * @param string/array $value 查询值
     * @param array $select 待查询参数
     * @param string $type 查询类型
     * @retrun /multitype:array
     * @author dou 2021/9/27 20:14
     * |---------------------------------------------------------------------------------
     */
    public static function getPtBy ( $key , $value , $select = [] , $type = 'get' ){
        $db = new Pt();
        if(is_array($value)){
            $key .= '_searchin';
        }else{
            if($key == 'id'){
                $type = 'first';
            }
        }
        if($type =='first' && count($select) == 1){
            $type = 'value';
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加平台
     * @param string $sord 首字母排序
     * @param string $pt_name 平台名称
     * @param string $pt_other 备注
     * @param string $three_pd 第三方判定：0：自家；1：第三方
     * @param string $company_type 公司类型：1极限2其它
     * @param string $is_code 是否验证1不验证2验证
     * @param string $company_id 公司id
     * @param string/array $cd_ids 品类ID组
     * @param string/array $gs_bids 品牌ID组
     * @retrun /multitype:array
     * @author dou 2021/9/28 20:13
     * |---------------------------------------------------------------------------------
    */
    public static function creactPt ( $sord , $pt_name , $pt_other , $three_pd = 0 , $company_type = 1 , $is_code = 1 , $company_id = 1 , $cd_ids = '' , $gs_bids = '' , $zp_id = 0, $pt_type = 1 ){
        $poss['sord'] = $sord;
        $poss['pt_name'] = $pt_name;
        $poss['pt_other'] = $pt_other;
        $poss['three_pd'] = $three_pd;
        $poss['company_type'] = $company_type;
        $poss['is_code'] = $is_code;
        $poss['company_id'] = $company_id;
        $poss['zp_id'] = $zp_id;
        $poss['pt_type'] = $pt_type;
        if(is_array($cd_ids)){
            $cd_ids = implode(',', $cd_ids);
        }
        $poss['cd_ids'] = $cd_ids;
        if(is_array($gs_bids)){
            $gs_bids = implode(',', $gs_bids);
        }
        $poss['gs_bids'] = $gs_bids;
        $id = Pt::insertGetId($poss);
        self::getAll(false);
//        $ptData = pt::select('id', 'sord' , 'pt_name' ,'three_pd','pt_zt')
//            ->get()
//            ->toArray();
//        RedisService::redisSet('ptList', $ptData);
        return $id;
    }

    /**
     * @name 获取平台类型
     * @param string $type
     * @return array|\string[][]
     * @author du
     * @date 2022/4/18
     */
    public static function getPtType($type=''){

        $data = DB::table('pt_type')->select('type_name','id')->get()->toarray();
        $res = [];
        foreach ($data as $k => $v){
            $res[$k]['type'] = $v['id'];
            $res[$k]['name'] = $v['type_name'];
        }
        if($type){
            $res = array_column($res, 'name','type');
        }
        return $res;
/*
        $invoiceType = array(array('type'=>1,'name'=>'普通'),array('type'=>2,'name'=>'线下分销'));
        if($type){
            $invoiceType = array_column($invoiceType, 'name','type');
        }
        return $invoiceType;*/
    }

    /**
     * @return mixed
     * @param $pt_type 平台类型
     * @param $type 返回数据类型
     * @author du
     * @date 2022/4/22
     */
    public static function getPtIdByPtType( $pt_type =2 , $type = 2){
        $data = Pt::whereRaw('FIND_IN_SET(2,pt_type)',true)->pluck('id')->toarray();
        if($data){
            if(is_array($data[0])) {
                $data = array_column($data, 'id');
            }
        }else{
            $data = array('453');
        }
        if($type == 1){
            $data = implode(',',$data);
        }
        return $data;

    }

}
