<?php
namespace App\Http\Controllers\DatasBase;
use App\Http\Controllers\BaseController;
use App\Services\BmmcService;
use App\Services\CommonService;
use Illuminate\Http\Request;
use DB;
use League\Flysystem\Exception;
use Excel;
/**
 * @name 价格维护
 * Class WptpriceController
 * @package App\Http\Controllers\Admin
 */
class WptpriceController extends BaseController
{
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param pt_name    平台名称
     * @param pt_zt      状态 1:启用; 2:停用
     * @param three_pd   0:自家; 1:第三方
     * @param p_paytype  开票公司
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function index (Request $request){
	    $clearlove = DB::table('pt_prices');
	    if($request->filled('creatData')){
	        $date = $request->input('creatData');
            $date[1] = $date[1]." 23:59:59";
		    $clearlove = $clearlove->whereBetween('pp_creactime',$date);
        }
        if($request->filled('pp_pid')){
            $clearlove = $clearlove->where('pp_pid',$request->input('pp_pid'));
        }
        if($request->filled('g_id')){
            $clearlove = $clearlove->where('pp_gid',$request->input('g_id'));
        }
        if(!$request->filled('g_id') && $request->filled('brand')){
            $clearlove = $clearlove->where('pp_gname','like','%'.$request->input('brand').'%');
        }
        $page_size = (int)$request->input('page_size',10);
        $page = (int)$request->input('page',1);
        if($page<1){
            $page = 1;
        }
        $offset = ($page-1)*$page_size;
        $count = $clearlove->count();
        $list = $clearlove->orderBy('pp_creactime','DESC')->offset($offset)->limit($page_size)->get();

        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $export = BmmcService::getTopButton('addEntry,goodExcel,getBland','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮

        if(!$list->isEmpty()){
	        $list = $list->toArray();
            $brand_ids = array_unique(array_column($list, 'pp_gid'));
            //获取商品品牌
            $brand_arr = DB::table('pj_goods')->whereIn('pg_id',$brand_ids)->pluck('brand_name','pg_id')->toArray();
            //dd($brand_arr);
            foreach ($list as $k=>$v){
                $buttonData = [];
                $buttonData[] = 'editEntry';
                $button = BmmcService::getListButton($buttonData,$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];
                if (isset($brand_arr[$v['pp_gid']])) {
                    $list[$k]['brand_name'] = $brand_arr[$v['pp_gid']];
                } else {
                    $list[$k]['brand_name'] = '';
                }
            }
            $data['list'] = $list;
            $data['count'] = [
                'page' => $page,
                'page_size' => $page_size,
                'allPage' => ceil($count/$page_size),
                'count' => $count,
            ];
            return response()->json(['Data'=>$data,'ErrorMessage'=>'返回成功','ErrorCode'=>1]);exit;
        }else{
	        $data['list'] = [];
            return response()->json(['Data'=>$data,'ErrorMessage'=>'暂无数据','ErrorCode'=>2]);exit;
        }
    }



    /*
     * @name 添加商品价格
     * @param pid  平台id
     * @param gid     商品id
     * @param pname     平台名称
     * @param gname     商品名称
     * @param price     商品价格
     * @param startime 生效时间
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2022/4/20
     */
    public function addEntry (Request $request)
    {
        $input = $request->only('pp_pid','pp_gid','pp_startime','pp_pname','pp_gname','pp_price','type');
        $now = date('Y-m-d');
        if(!$request->has('pp_pid')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'平台id必填']);exit;
        }
        if(!$request->has('pp_price')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'价格必填']);exit;
        }
        if(!$request->has('pp_gid')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'商品id必填']);exit;
        }
        if(!$request->has('pp_startime') ){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'生效时间必填']);exit;
        }
        if($request->input('pp_startime')< $now){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'生效时间有误']);exit;
        }
        if(!$request->has('pp_pname')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'平台名称必填']);exit;
        }
        if(!$request->has('pp_gname')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'商品名称必填']);exit;
        }
        $info = DB::table('pt_prices')->where('pp_pid',$input['pp_pid'])->where('pp_gid',$input['pp_gid'])->where('pp_startime','>=',$input['pp_startime'])->value('pp_id');
        if($info){
            return response()->json(['Data'=>'','ErrorCode'=>'9200','ErrorMessage'=>'已存在']);exit;
        }
        $type = $input['type']??0;
        $session_token = $request->get('session_token');
        $poss['pp_pid'] = $input['pp_pid'];
        $poss['pp_gid'] = $input['pp_gid'];
        $poss['pp_pname'] = $input['pp_pname'];
        $poss['pp_gname'] = $input['pp_gname'];
        $poss['pp_price'] = $input['pp_price'];
        $poss['pp_startime'] = $input['pp_startime'];
        $poss['pp_creactime'] = date("Y-m-d H:i:s");
        $poss['pp_creactor'] = $session_token['admin_acc'];
        $poss['pp_creactid'] = $session_token['id'];
        $res = DB::table('pt_prices')->insert($poss);
        if ($res){
            if($type==2){
                if ($res) {
                    $posst['pl_jg'] = 1;
                } else {
                    $posst['pl_jg'] = 2;
                }
                $posst['pl_pid'] = $input['pp_pid'];//平台id
                $posst['pl_pname'] = $input['pp_pname'];//平台名称
                $posst['pl_gid'] = $input['pp_gid'];//商品id
                $posst['pl_gname'] = $input['pp_gname'];//商品名称
                $posst['pl_price'] = $input['pp_price'];//商品价格
                $posst['pl_creactime'] = date("Y-m-d H:i:s");
                $posst['pl_adminid'] = $session_token['id'];
                $posst['pl_creactor'] = $session_token['admin_acc'];
                DB::table('pt_list')->insert($posst);
                $this->insertingLog("批量添加，","","添加平台：".$input['pp_pname']."；商品：".$input['pp_gname']."；价格：".$input['pp_price'],"平台价格维护",$request->ip(), $request->get('session_token')['admin_acc']);
            }else{
                $this->insertingLog("添加，","","添加平台：".$input['pp_pname']."；商品：".$input['pp_gname']."；价格：".$input['pp_price'],"平台价格维护",$request->ip(), $request->get('session_token')['admin_acc']);
            }
            return response()->json(['Data'=>'','ErrorMessage'=>'操作成功！','ErrorCode'=>1]);exit;
        }else{
            return response()->json(['Data'=>'','ErrorMessage'=>'操作失败！','ErrorCode'=>2]);exit;
        }

    }

    /**
     * @name 编辑商品价格
     * @param id  数据id
     * @param pname     平台名称
     * @param gname     商品名称
     * @param price     商品价格
     * @param startime 生效时间
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2022/4/20
     */
    public function editEntry (Request $request)
    {
        $input = $request->only('pp_id','pp_startime','pp_pname','pp_gname','pp_price');
        if(!$request->has('pp_id')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'数据id必填']);exit;
        }
        if(!$request->has('pp_price')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'价格必填']);exit;
        }
        if(!$request->has('pp_startime')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'生效时间必填']);exit;
        }
        if(!$request->has('pp_pname')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'平台名称必填']);exit;
        }
        if(!$request->has('pp_gname')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'商品名称必填']);exit;
        }
        $input['pp_pid'] = intval($input['pp_pid']);
        $info = DB::table('pt_prices')->where('pp_pid',$input['pp_pid'])->where('pp_gid',$input['pp_gid'])->where('pp_startime','>',$input['pp_startime'])->where('pp_id','!=',$input['pp_id'])->value('pp_id');
        if($info){
            return response()->json(['Data'=>'','ErrorCode'=>'9200','ErrorMessage'=>'已存在']);exit;
        }

        $poss['pp_price'] = $input['pp_price'];
        $poss['pp_startime'] = $input['pp_startime'];
        $res = DB::table('pt_prices')->where('pp_id',$input['pp_id'])->update($poss);
        if ($res){
            $this->insertingLog("编辑，","","编辑平台：".$input['pp_pname']."；商品：".$input['pp_gname']."；价格：".$input['pp_price'],"平台价格维护",$request->ip(), $request->get('session_token')['admin_acc']);
            return response()->json(['Data'=>'','ErrorMessage'=>'操作成功！','ErrorCode'=>1]);exit;
        }else{
            return response()->json(['Data'=>'','ErrorMessage'=>'操作失败！','ErrorCode'=>2]);exit;
        }

    }

    /**
     * @name 删除商品价格
     * @param id  数据id
     * @param pname     平台名称
     * @param gname     商品名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2022/4/20
     */
    public function delGoodsBrand (Request $request)
    {
        $input = $request->only('pp_id','pp_pname','pp_gname');
        if(!$request->has('pp_id')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'数据id必填']);exit;
        }
        if(!$request->has('pp_pname')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'平台名称必填']);exit;
        }
        if(!$request->has('pp_gname')){
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'商品名称必填']);exit;
        }
        $input['pp_pid'] = intval($input['pp_pid']);
        $poss['pp_delet'] = 2;
        $res = DB::table('pt_prices')->where('pp_id',$input['pp_id'])->update($poss);
        if ($res){
            $this->insertingLog("删除，","","删除平台：".$input['pp_pname']."；商品：".$input['pp_gname'],"平台价格维护",$request->ip(), $request->get('session_token')['admin_acc']);
            return response()->json(['Data'=>'','ErrorMessage'=>'操作成功！','ErrorCode'=>1]);exit;
        }else{
            return response()->json(['Data'=>'','ErrorMessage'=>'操作失败！','ErrorCode'=>2]);exit;
        }
    }

    /**
     * @name 回传商品价格导入
     * @param startime 生效时间
     * @param pid  平台id
     * @param file     表格数据
     * @param pname     平台名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2022/4/20
     */
    public function goodExcel (Request $request){
	    try {
		    //DB::beginTransaction();
            $input = $request->only('pp_pid','pp_startime','pp_pname');
            if (!$request->has('pp_pid')) {
                return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'平台id必填']);exit;
            }
            if (!$request->has('pp_startime')) {
                return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'生效时间必填']);exit;
            }
            if (!$request->has('pp_pname')) {
                return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'平台名称必填']);exit;
            }
            $input['pp_pid'] = intval($input['pp_pid']);
            $session_token = $request->get('session_token');
		    $file = $request->file('file');
		    if ($file) {
			    // 获取文件相关信息
                $ext = $file->getClientOriginalExtension();

                // 扩展名
                if (!in_array($ext,['xls','xlsx'])) {
                	throw new Exception("仅支持xls和xlsx结尾的excel文件");
                }
                //上传文件
                $file_name = date('YmdHis').rand(10,99).'.'.$ext;
                $urlname = public_path('excel');
                $file->move($urlname,$file_name);
                $filename = $urlname.'/'.$file_name;
                $array = [];

               Excel::load($filename,function($reader)use($input,$session_token,&$array){
            	    $reader = $reader->getSheet(0);
            	    $data = $reader->toArray();
            	    if (empty($data) || count($data)<2) {
            		    throw new Exception("导入失败,内容不能为空");
            	    }
            	    $arr = [];

            	    foreach ($data as $key => $val) {
                        if ($key == 0) {
                            if ($val[0] !== "商品id" || $val[1] !== "商品名称" || $val[2] !== "商品价格") {
                                throw new Exception("数据格式错误");
                            }
                        } else {
                            $arr[$key]['pp_pname'] = $input['pp_pname'];//平台名称
                            $arr[$key]['pp_pid'] = $input['pp_pid'];//平台id
                            $arr[$key]['pp_startime'] = $input['pp_startime'];//生效时间
                            $arr[$key]['pp_gid'] = $val[0];//商品id
                            $arr[$key]['pp_gname'] = $val[1];//商品名称
                            $arr[$key]['pp_price'] = $val[2];//商品价格
                           /* $arr[$key]['pp_creactime'] = date("Y-m-d H:i:s");
                            $arr[$key]['pp_creactor'] = $session_token['admin_acc'];
                            $arr[$key]['pp_creactid'] = $session_token['id'];
                            $res = DB::table('pt_prices')->insert($arr[$key]);
                            unset($arr[$key]);
                            if ($res) {
                                $poss[$key]['pl_jg'] = 1;
                            } else {
                                $poss[$key]['pl_jg'] = 2;
                            }
                            $poss[$key]['pl_pid'] = $input['pp_pid'];//平台id
                            $poss[$key]['pl_pname'] = $input['pp_pname'];//平台名称
                            $poss[$key]['pl_gid'] = $val[0];//商品id
                            $poss[$key]['pl_gname'] = $val[1];//商品名称
                            $poss[$key]['pl_price'] = $val[2];//商品价格
                            $poss[$key]['pl_creactime'] = date("Y-m-d H:i:s");
                            $poss[$key]['pl_adminid'] = $session_token['id'];
                            $poss[$key]['pl_creactor'] = $session_token['admin_acc'];
                            $res = DB::table('pt_list')->insert($poss[$key]);
                            unset($poss[$key]);*/
                        }
                        unset($data[$key]);
                    }
                    //print_r($arr);
                   $array = CommonService::resetListKey($arr);

            	});
            	//Db::commit();
            	// $this->insertingLog("批量添加，","","添加平台：".$input['pp_pname']."；文件：".$file_name."；",'价格维护',$request->ip(), $request->get('session_token')['admin_acc']);

                return response()->json(['Data'=>$array,'ErrorMessage'=>'操作成功！','ErrorCode'=>1]);exit;
		    } else {
				throw new Exception("文件上传失败");
			}
	    } catch (Exception $e) {
			//Db::rollBack();
			return response()->json(['ErrorCode'=>3,'ErrorMessage'=>$e->getMessage(),'Data'=>'']);
		}
    }

    /**
     * @name 回传模板下载
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2022/4/21
     */
    public function getBland (Request $request)
    {
        if (!$request->has('cd_id')) {
            return response()->json(['Data'=>'','ErrorCode'=>'3','ErrorMessage'=>'品类id必填']);exit;
        }
        $list = DB::table('pj_goods')->select('pg_id','brand_name','pg_series','version','pg_goodsname')
            ->where('cd_id',$request->input('cd_id'))
            ->get()->toArray();
        $cellData = [];
        foreach ($list as $k=>$v) {
            $cellData[$k]['pg_id'] = $v['pg_id'];
            if($v['pg_goodsname']!=''){
                $cellData[$k]['goods_name'] = $v['pg_goodsname'];
            }else{
                if ($v['pg_series'] =="") {
                    $cellData[$k]['goods_name'] = $v['brand_name'].'-'.$v['version'];
                } else {
                    $cellData[$k]['goods_name'] = $v['brand_name'].'-'.$v['pg_series'].'-'.$v['version'];
                }
            }

        }
        $name = 'ptprice';
        Excel::create($name, function ($excel) use ($cellData) {
            $excel->sheet('订单列表', function ($excel) use ($cellData) {
                $excel->cell('A1', function ($cell) {
                    $cell->setValue('商品id');
                });
                $excel->cell('B1', function ($cell) {
                    $cell->setValue('商品名称');
                });
                $excel->cell('C1', function ($cell) {
                    $cell->setValue('商品价格');
                });

                foreach ($cellData as $key => $value) {
                    $i = $key + 2;
                    $excel->cell('A' . $i, $value['pg_id']);
                    $excel->cell('B' . $i, $value['goods_name']);
                }
            });
        })->save('xls', public_path('excel'));
        $data = 'excel/' . $name . '.xls';
        return response()->json(['Data'=>$data,'ErrorCode'=>'1','ErrorMessage'=>'获取成功']);exit;
        //return $_SERVER["HTTP_HOST"] . '/excel/' . $name . '.xls';

        //return 'http://mo2o9s.sudianwang.com/excel/ptprice_bland.xls';
    }

}
