<?php
/**
 * 订单服务
 * 订单基础操作服务
 * @author lixiaolin
 * @Date: 2021/4/2
 * @Time: 下午13:50
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Exports\AfterCustExport;
use App\Exports\ServiceProviderExport;
use App\Models\Admin;
use App\Models\Company;
use App\Models\GoodsBrand;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use DB;

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

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

    /**
     * @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 = Request()->get('session_token');//用户信息
        $query = Admin::leftJoin('admin_infor', 'admin.id', '=', 'admin_infor.admin_id')
            ->leftJoin('certification', 'admin.id', '=', 'certification.ser_id');

        $query->where('admin.admin_groupnew', Request()->input('admin_groupnew',2));
        if (Request()->filled('type')) {
            //$query->where('type', Request()->input('type'));
            $query->where('mouth_pay', Request()->input('type'));//结算方式
        }
//        if (Request()->filled('unified')) {
//            $query->where('unified', Request()->input('unified'));
//        }
        if (Request()->filled('admin_acc')) {
            $query->where('admin.admin_acc', 'like', Request()->input('admin_acc') . '%');//登录名
        }
        if (Request()->filled('admin_name')) {
            $query->where('admin.admin_name', 'like', Request()->input('admin_name') . '%');//姓名
        }
        if (Request()->filled('reward')) {
            $query->where('reward', Request()->input('reward'));//奖惩类型
        }
        if (Request()->filled('enable')) {
            $query->where('enable', Request()->input('enable'));//停启用
        }
        if (Request()->filled('company_name')) {
            $query->where('admin.company_name', 'like', '%' . Request()->input('company_name') . '%');//门店名称
        }
        if (Request()->filled('phone')) {
            $query->where('admin_infor.phone', 'like', Request()->input('phone') . '%');//电话
        }
        if (Request()->filled('admin_province')) {
            $query->where('admin_infor.admin_province', 'like', Request()->input('admin_province') . '%');//省份
        }
        if (Request()->filled('admin_city')) {
            $query->where('admin_infor.admin_city', 'like', Request()->input('admin_city') . '%');//城市
        }
        if (Request()->filled('admin_county')) {
            $query->where('admin_infor.admin_county', 'like', Request()->input('admin_county') . '%');//区县
        }
        if (Request()->filled('verstoreid')) {
            $query->where('admin_infor.verstoreid', 'like', Request()->input('verstoreid') . '%');//京东编号
        }
        if (Request()->filled('verstorename')) {
            $query->where('admin_infor.verstorename', 'like', Request()->input('verstorename') . '%');//京东名称
        }
        if (!in_array($session['admin_groupnew'],[7,8])) {
            $query->where('admin.company_id', $session['company_id']);
        }
        if (in_array($session['admin_groupnew'],[8])) {
            $query->whereIn('admin.company_id', $session['all_company']);
        }
        $count = $query->count();
        $totalPage = 1;

        if(Request()->input('is_excel')==1){
            DB::connection()->enableQueryLog();#开启执行日志
        }

        if ($pageSize > 0) {
            $totalPage = ceil($count / $pageSize);
            $offset = ($page - 1) * $pageSize;

            $list = $query->select($columns)
                ->orderBy('id', 'ASC')
                ->offset($offset)
                ->limit($pageSize)
                ->get();
        } else {
            $list = $query->select($columns)
                ->orderBy('id', 'ASC')
                ->get();
        }
        //导出所需语句
        $data['sqls'] = DB::getQueryLog()[0];

        $data['list'] = $list;
        $data['page'] = [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'totalPage' => $totalPage
        ];

        return $data;
    }


    public function formatPageContent($token, $priID, $data,$Login_id = '')
    {
        $list = $data['list'];
        $brandsArr = GoodsBrand::pluck('brand_name', 'id')->toArray();
        // 查到所有 button
        $all_button = BmmcService::whereButton($token, $priID,$Login_id);
        $export = BmmcService::getTopButton('export,addService', '', $all_button);
        $data['button_top'] = $export['button_top'] ?? [];//顶部按钮
        $data['button_search'] = $export['button_search'] ?? [];//搜索栏按钮
        $data['all_button'] = $all_button;//顶部按钮

        if ($list) {
            $list = $list->toArray();
            $mouth_payname = self::getMouthPay(true);//获取结算方式
            $enablename = self::getEnable(true);//获取账号状态
            $unifiedName = self::getUnifiedName(true);//获取统一价格设定
            $rewardName = self::getRewardName(true);//获取奖惩设置
            $invoiceTypeName = InvoiceService::getInvoiceTypeName(true);
            $fsixName = self::getFsixName(true);
            foreach ($list as $k => $v) {
                $list[$k]['fsixName'] = $fsixName[$v['is_fsix']];
                // -----------button 处理开始-----------
                $button = BmmcService::getListButton(['editService,delService,editServicePassword,getSettleData,getAccountList'], $all_button);
                $list[$k]['button_one'] = $button['button_one'] ?? [];
                $list[$k]['button_two'] = $button['button_two'] ?? [];
                $list[$k]['button_three'] = $button['button_three'] ?? [];
                // -----------button 处理结束-----------

                // -----------数据内容描述开始-----------
                $list[$k]['bmmc_name'] = '服务商';
                if (!$v['certification_num']) {
                    $list[$k]['certification_num'] = "暂无";
                }

                //代理品牌
                if (!empty($v['agent_brand'])) {
                    $agent = explode(',', trim($v['agent_brand'], ','));
                    $brand_name = [];
                    foreach ($agent as $ks => $vs) {
                        if (isset($brandsArr[$vs])) {
                            $brand_name[] = $brandsArr[$vs];
                        }
                    }
                    if (!empty($brand_name)) {
                        $list[$k]['brand_name'] = implode('/', $brand_name);
                    } else {
                        $list[$k]['brand_name'] = "暂无";
                    }
                } else {
                    $list[$k]['brand_name'] = "暂无";
                }
                $list[$k]['mouth_payname'] = $mouth_payname[$v['mouth_pay']]??'未设定';
                $list[$k]['unifiedname'] = $unifiedName[$v['unified']]??'未设定';
                $list[$k]['rewardname'] = $rewardName[$v['reward']]??'未设定';
                $list[$k]['enablename'] = $enablename[$v['enable']]??'未设定';
                $list[$k]['invoicename'] = $invoiceTypeName[$v['invoice']]??'不开票';
                // -----------数据内容描述结束-----------
            }
        }
        $data['mouth_payname'] = self::getMouthPay();
        $data['unifiedname'] = self::getUnifiedName();
        $data['rewardname'] = self::getRewardName();
        $data['enablename'] = self::getEnable();
        $data['list'] = $list;

        return $data;
    }

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


    public function export($data, $fields, $fileName, $fileExt = '.xlsx') {
        $filePath = $fileName.$fileExt;
        $filePath = 'FWS/' . date('Ym') .'/'.$filePath; //服务商的独有目录
        $excel = new ServiceProviderExport($data, $fields);

        if (Excel::store($excel, $filePath)) {
            return $filePath;
        } else {
            return false;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取结款类型
     * @retrun /multitype:array
     * @author dou 2021/9/9 20:57
     * |---------------------------------------------------------------------------------
    */
    public static function getMouthPay ( $key = false){
        $data = [['type'=>2,'name'=>'零散'],['type'=>3,'name'=>'周结'],['type'=>1,'name'=>'月结']];
       // $data = array(array('type'=>1,'name'=>'月结'),array('type'=>2,'name'=>'零散'),array('type'=>3,'name'=>'周结'),array('type'=>4,'name'=>'五大区'));
        if( $key ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取账号状态
     * @retrun /multitype:array
     * @author dou 2021/10/11 15:52
     * |---------------------------------------------------------------------------------
    */
    public static function getEnable ( $key = false ){
        $data = array(array('type'=>1,'name'=>'启用'),array('type'=>2,'name'=>'停用'));
        if( $key ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取价格类型名称
     * @retrun /multitype:array
     * @author dou 2021/10/20 17:25
     * |---------------------------------------------------------------------------------
    */
    public static function getUnifiedName ( $key = false ){
        $data = array(array('type'=>1,'name'=>'统一价格'),array('type'=>2,'name'=>'非统一价格'));
        if( $key ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取奖罚开启状态名称
     * @retrun /multitype:array
     * @author dou 2021/10/20 18:01
     * |---------------------------------------------------------------------------------
    */
    public static function getRewardName ( $key = false ){
        $data = array(array('type'=>1,'name'=>'开启奖惩'),array('type'=>2,'name'=>'关闭奖惩'));
        if( $key ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取服务门店类型
     * @param string $key 订单单号
     * @retrun /multitype:array
     * @author dou 2021/12/4 13:07
     * |---------------------------------------------------------------------------------
     */
    public static function getBrandService ( $key = false ){
        $data = [
            /*['type'=>1,'name'=>'自营'],
            ['type'=>2,'name'=>'3m'],
            ['type'=>3,'name'=>'量子'],
            ['type'=>4,'name'=>'雪佛龙'],
            ['type'=>5,'name'=>'智配贴装'],
            ['type'=>6,'name'=>'摩特'],
            ['type'=>7,'name'=>'原3M'],
            ['type'=>8,'name'=>'智配贴装(横裁)'],
            ['type'=>9,'name'=>'极限(横裁)']*/
        ];
        if( $key ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 是否为F6
     * @retrun /multitype:array
     * @author dou 2021/10/15 18:47
     * |---------------------------------------------------------------------------------
     */
    public static function getFsixName ( $type = false ){
        $invoiceTypeName = array(array('type'=>'1','name'=>'不是F6门店'),array('type'=>'2','name'=>'F6门店'));
        if($type){
            $invoiceTypeName = array_column($invoiceTypeName, 'name','type');
        }
        return $invoiceTypeName;
    }

    /**|---------------------------------------------------------------------------------
     * @name 门店经营类型
     * @retrun /multitype:array
     * @author dou 2022/1/26 16:54
     * |---------------------------------------------------------------------------------
    */
    public static function getServiceType ( $type = false ){
        $data = [
            ['type'=>1,'name'=>'自营蓄电池'],
            ['type'=>2,'name'=>'自营车模'],
            ['type'=>3,'name'=>'分销石总电瓶']
        ];
        if( $type ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取门店账号数据状态
     * @param string $type 数据展示类型
     * @retrun /multitype:array
     * @author dou 2022/6/9 10:30
     * |---------------------------------------------------------------------------------
    */
    public static function getAklStateName ( $type = false ){
        $data = [['type'=>1,'name'=>'正常'],['type'=>2,'name'=>'停用']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取门店账号数据类型
     * @param string $type 数据展示类型
     * @retrun /multitype:array
     * @author dou 2022/6/9 10:30
     * |---------------------------------------------------------------------------------
     */
    public static function getAklTypeName ( $type = false ){
        $data = [['type'=>1,'name'=>'银行卡'],['type'=>2,'name'=>'支付宝'],['type'=>3,'name'=>'微信']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 结算单类型
     * @param string $type 数据展示类型
     * @retrun /multitype:array
     * @author dou 2022/6/9 10:30
     * |---------------------------------------------------------------------------------
     */
    public static function getWatType ( $type = false ){
        $data = [['type'=>'J3','name'=>'3M结算单'],['type'=>'J4','name'=>'石总线下结算']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

}
