<?php

/**
 * 服务商补贴管理
 *
 * @author lixiaolin
 * @Date: 2021/08/01
 * @Time: 下午18:10
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Models\Leadsubsidie;
use App\Models\GhPrice;
use App\Models\PjGoods;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Log;

class SubsidyService extends Service
{
    public static $instance;
    public $modelMain = null;

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

    /**
     * @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)
    {
        $Db = Leadsubsidie::leftJoin('pj_goods', 'ld_goodid', '=', 'pg_id')
            ->leftJoin('gh_price', function ($query) {
                $query->on('gh_price.goods_id', '=', 'ld_goodid')
                    ->where('ser_id', 0);
            });

        if ($param['order_time']) {
            $Db = $Db->where('start_time', '<=', $param['order_time']);
            $Db = $Db->where('end_time', '>=', $param['order_time']);
        }

        if ($param['brand_name']) {
            $Db->where("ld_brand", '=',  $param['brand_name']);
        }
        if ($param['goods_name']) {
            $Db->whereRaw("(version like '%".$param['goods_name']."%' or pg_series like '%".$param['goods_name']."%' or brand_name like '%".$param['goods_name']."%')");
        }
        $count = $Db->count();
        $totalPage = ceil($count / $pageSize);
        if ($pageSize > 0) {
            $offset = ($page - 1) * $pageSize;
            $list = $Db->select('ld_id', 'ld_release', 'brand_name', 'pg_series', 'version', 'ld_price', 'ld_creacter', 'ld_brand', 'ld_type', 'supply_price','ld_goodid','le_setyid')
                ->offset($offset)
                ->limit($pageSize)
                ->orderBy('ld_id', 'desc')
                ->get();
        } else {
            $list = $Db->select('ld_id', 'ld_release', 'brand_name', 'pg_series', 'version', 'ld_price', 'ld_creacter', 'ld_brand', 'ld_type', 'supply_price','ld_goodid','le_setyid')
                ->orderBy('ld_id', 'desc')
                ->get();
        }
        $result = [];
        $result['page'] = ['totalPage' => $totalPage, 'count' => $count, 'page' => $page, 'page_size' => $pageSize];
        $result['list'] = $list;

        return $result;
    }

    public function formatPageContent($token, $priID, $data)
    {
        $list = $data['list'];

        $all_button = BmmcService::whereButton($token, $priID);
        $export = BmmcService::getTopButton('addLead,EditAllk,EditAllg', '', $all_button);
        $data['button_top'] = $export['button_top'] ?? [];//顶部按钮
        $data['button_search'] = $export['button_search'] ?? [];//搜索栏按钮
        $res = [];
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            $releasename = self::getReleaseName(true);
            $lableName = self::getLableName(true);
            foreach ($list as $k => $v) {
                $res[$k]['ld_id'] = $v['ld_id'];
                $res[$k]['ld_release'] = $v['ld_release'];
                $res[$k]['ld_releasename'] = $releasename[$v['ld_release']]??'未定义';
                $res[$k]['ld_brand'] = $v['ld_brand'];
                $res[$k]['ld_creacter'] = $v['ld_creacter'];
                $res[$k]['ld_price'] = $v['ld_price'];
                $res[$k]['ld_type'] = $v['ld_type'];
                $res[$k]['ld_goodid'] = $v['ld_goodid'];
                $res[$k]['supply_price'] = (int)$v['supply_price'] ?? 0;
                $res[$k]['sum_price'] = $v['ld_price'] + $res[$k]['supply_price'];
                $res[$k]['le_setyid'] = $v['le_setyid'];
                $res[$k]['le_setyname'] = $lableName[$v['le_setyid']]??'未定义';
                if ($v['pg_series'] == '') {
                    $res[$k]['ld_goodsname'] = $v['brand_name'] . '-' . $v['version'];
                } else {
                    $res[$k]['ld_goodsname'] = $v['brand_name'] . '-' . $v['pg_series'] . '-' . $v['version'];
                }
                $buttonData = [];
                $buttonData[] = 'editLead';
                if ($v['ld_release'] == 1) {
                    $buttonData[] = 'edit_releasekg';
                } elseif ($v['ld_release'] == 2) {
                    $buttonData[] = 'edit_releasek';
                }
                $buttonData[] = 'delLead';
                $button = BmmcService::getListButton($buttonData,$all_button);
                $res[$k]['button_one'] = $button['button_one']??[];
                $res[$k]['button_two'] = $button['button_two']??[];
                $res[$k]['button_three'] = $button['button_three']??[];
            }
            $data['ld_releasename'] = self::getReleaseName();
            $data['le_setyname'] = self::getLableName();
            $data['list'] = $res;
        }

        return $data;
    }


    /**
     * 检查系统是不是已经存在这个价格设置
     *
     * @param $supplierID
     * @param $goodsID
     * @return mixed
     */
    public static function getSubsidy($ldID)
    {
        $entity = Leadsubsidie::find($ldID);

        if ($entity) {
            return $entity;
        }

        return false;
    }

    /**
     * 获取服务商的指定商品签约价
     *
     * @param int $platformID 平台id
     * @param int $platformGoodsID 平台商品id
     * @return mixed
     */
    public static function findGoodsSubsidy($goodsID)
    {
        $entity = Leadsubsidie::where('pg_id', $goodsID)
            ->first()
            ->toArray();

        if ($entity) {
            return $entity;
        }

        return false;
    }

    public static function switches($type, $ids = [])
    {
        if (!empty($ids)) {
            Leadsubsidie::where('ld_id', 'in', $ids)->update(['ld_release' => $type]);
        } else {
            Leadsubsidie::where('ld_release','!=',$type)->update(['ld_release' => $type]);
        }

        return true;
    }
    /**|---------------------------------------------------------------------------------
     * @name 根据指定条件（多条件）获取补贴
     * @param array $params 查询条件
     * @param array $select 查询内容
     * @retrun /multitype:array
     * @author dou 2021/10/14 10:51
     * |---------------------------------------------------------------------------------
    */
    public static function getLeadsubsidieBy ( $params , $select = [] , $type = 'get' , $limit = '20'){
        $db = new Leadsubsidie();
        $list = CommonService::getMysqlData($db, $params,$select,[],$type,$limit);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取数据状态名称
     * @retrun /multitype:array
     * @author dou 2021/10/21 10:41
     * |---------------------------------------------------------------------------------
    */
    public static function getReleaseName ( $key = false ){
        $data = array(array('type'=>'1','name'=>'开启'),array('type'=>'2','name'=>'关闭'));
        if($key){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取支持类型
     * @param 订单单号
     * @retrun /multitype:array
     * @author dou 2021/10/21 15:18
     * |---------------------------------------------------------------------------------
    */
    public static function getLableName ( $key = false ){
        $lable = LabtypeService::getLable('sety_id',['14','19']);
        $data = [];
        foreach($lable as $k => $v){
            $lables['type'] = $v['sety_id'];
            $lables['name'] = $v['sety_name'];
            $data[] = $lables;
        }
        if($key){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

}
