<?php

namespace App\Http\Controllers\DataSyn;
use App\Http\Controllers\BaseController;
use App\Models\JdBound;
use App\Models\JdBoundLead;
use App\Models\PjGoods;
use App\Services\CommonService;
use App\Services\JdBoundService;
use App\Services\PlatformService;
use Illuminate\Http\Request;
use BlueCity\Core\Inc\ErrorInc;
use Excel;
use DB;

class JdBoundController extends BaseController
{

	/**
	 * @name  列表页
     * @param sku_id     sku
     * @param jd_goodn   平台名称
     * @param brand_name 商品品牌
     * @param version    商品型号
	 * @param  $request
	 * @author du 2021年8月20日下午17:28:06
	 */
	public function index(Request $request){
		$input = $request->all();
        $session = $request->get('session_token');
        $input['status'] = $input['status']??3;
        if(!in_array($input['status'], [1,2,3,4])){
            return $this->error('查询状态错误', ErrorInc::INVALID_PARAM);exit;
        }
    	$list = JdBoundService::getList($input,$session);
    	if($list['list']){
	    	return $this->success('获取成功', $list); exit;
    	}else{
	    	return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$list);exit;
    	}
	}

	/**|---------------------------------------------------------------------------------
	 * @name  添加
     * @param is_long  1:绑定  2:临时绑定
     * @param sku_id   商品sku
     * @param jd_goodn 平台商品sku名
     * @param goods_id 系统商品id
	 * @retrun \Illuminate\Http\JsonResponse /multitype:array
	 * @author du 2021/8/23 9:34
	 * |---------------------------------------------------------------------------------
	*/
	public function addBound(Request $request){
        if (!$request->filled('goods_id')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
		//平台id
		$pt_id = intval($request->input('pt_id'));
		if (empty($pt_id)){
            return $this->error('请选择平台', ErrorInc::MYSQL_FAILED);exit;
		}
        $company_id = PlatformService::getPtBy('id', $pt_id, ['company_id'], 'first');
		$is_long = (int)$request->input('is_long',1);
		$goods_id = intval($request->input('goods_id'));
		if($request->filled('sku_id') && $request->filled('jd_goodn') && $request->filled('goods_id')){

			$sku_id = $request->input('sku_id');
			$jd_goodn = $request->input('jd_goodn');

            $old_sku = JdBoundService::getInfoBy('sku_id', $sku_id,['id']);
            if (!empty($old_sku)){
                return $this->error('该sku已绑定', ErrorInc::MYSQL_FAILED);exit;
            }
            $info = PjGoods::where(["pg_id"=>$goods_id])->select('brand_name','pg_series','version')->first();
            if ($info['pg_series'] != ""){
                $good_name = $info['brand_name'].'-'.$info['pg_series'].'-'.$info['version'];
            }else{
                $good_name = $info['brand_name'].'-'.$info['version'];
            }
			if($goods_id){
				if($is_long!=1){
					$bding = "临时绑定商品，";
				}else{
					$bding = "永久绑定商品，";
				}
				$res = JdBoundService::createjdBound($sku_id, $jd_goodn, $pt_id, $goods_id, $is_long, '', $good_name,$company_id,$request->get('session_token')['admin_acc']);

				if($res){
					 $this->insertingLog($bding,'','商品sku：'.$sku_id,'京东商品绑定',$request->ip(), $request->get('session_token')['admin_acc']);//日志
                    return $this->success('绑定成功'); exit;
                }else{
                    return $this->error('绑定失败', ErrorInc::DATA_EMPTY);exit;
                }
			}else{
                return $this->error('未找到该系统商品', ErrorInc::DATA_EMPTY);exit;
			}
		}else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
		}
	}

    /**|---------------------------------------------------------------------------------
     * @name  编辑
     * @param id       数据id
     * @param is_long  1:绑定 2:临时绑定
     * @param sku_id   sku
     * @param goods_id 商品id
     * @param goods_name 商品名
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author du 2021/8/23 9:41
     * |---------------------------------------------------------------------------------
    */
	public function editBound(Request $request){

        $input = $request->only('id','goods_id','sku_id');
        $checkKey = CommonService::checkKey(['id','goods_id','sku_id'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }

        $is_long = (int)$request->input('is_long',1);
		$id = (int)$request->input('id',0);
        $ext = JdBoundService::getInfoBy('id', $id,['id']);
        if(!$ext){
            return $this->error('无此数据', ErrorInc::FAILED_PARAM, []);exit;
        }
		$sku_id = (int)$request->input('sku_id',0);
		$goods_id = (int)$request->input('goods_id');
		if($goods_id>0 && $id > 0 && $sku_id > 0){
			$good_name = $request->input('goods_name');
			$good_id = PjGoods::where(["pg_id"=>$goods_id])->value('pg_id');
			if($good_id){
				$poss['goods_id'] = $good_id;
				$poss['goods_name'] = $good_name;
				$poss['is_long'] = $is_long;
				$res = JdBound::where("id",$id)->update($poss);
				if($res){
                    $this->insertingLog('编辑，','','商品sku：'.$sku_id,'京东商品绑定',$request->ip(), $request->get('session_token')['admin_acc']);//日志
                    return $this->success('编辑成功'); exit;
                }else{
                    return $this->error('编辑失败', ErrorInc::DATA_EMPTY);exit;
                }
			}else{
                return $this->error('未找到该系统商品', ErrorInc::DATA_EMPTY);exit;
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
	}

	/**|---------------------------------------------------------------------------------
	 *  @name  删除
     * @param id 数据id
	 * @retrun \Illuminate\Http\JsonResponse /multitype:array
	 * @author du 2021/8/23 9:52
	 * |---------------------------------------------------------------------------------
	*/
	public function deleteBound(Request $request){
        if (!$request->filled('id')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
		$id = (int)$request->input('id');
        $sku_id = JdBoundService::getInfoBy('id', $id,['sku_id']);
        if(!$sku_id){
            return $this->error('无此数据', ErrorInc::FAILED_PARAM, []);exit;
        }
		$res = JdBound::where(['id'=>$id])->delete();
		if($res){
            $this->insertingLog('删除，','','删除，sku：'.$sku_id,'京东商品绑定',$request->ip(), $request->get('session_token')['admin_acc']);//日志
            return $this->success('删除成功'); exit;
        }else{
            return $this->error('删除失败', ErrorInc::DATA_EMPTY);exit;
        }
	}

    /**|---------------------------------------------------------------------------------
     * @name 上传excel导入
     * @param file 文件名
     * @param p_id 平台id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/12/31 11:57
     * |---------------------------------------------------------------------------------
     */
    public function uploadExcelImport ( Request $request ){
        try {
            $file = $request->file('file');

            $p_id = $request->input('p_id');//平台id
            $session = $request->get('session_token');
            $admin_acc = $session['admin_acc'];

            if ($session['admin_groupnew'] != 7) {//管理员可以看全部
                $company_id = $session['company_id'];
            }else{
                $company_id = $request->input('company_id')??1;
            }

            if (!$file){
                throw new ApiException("请选择文件");
            }
            $ext = $file->getClientOriginalExtension();// 获取扩展名
            if(!in_array($ext,['xls','xlsx','csv'])){//判断格式
                throw new ApiException("仅支持xls和xlsx结尾的excel文件");
            }
            //上传文件
            $file_name = date('YmdHis').rand(10,99).'.'.$ext;
            $urlname = public_path('excel');
            $file->move($urlname,$file_name);
            $filename = $urlname.'/'.$file_name;
            Excel::load($filename,function($reader)use($admin_acc,$p_id,$company_id){
                $reader = $reader->getSheet(0);

                $data = $reader->toArray();
                if($data[0][0]!='系统编号' && $data[0][1]!='品牌' && $data[0][2]!='系列' && $data[0][3]!='型号名称' && $data[0][4]!='商品全称' && $data[0][5]!='统一商品编码（请勿重复）' && $data[0][6]!='质保时间' && $data[0][7]!='统一结算服务费' && $data[0][8]!='平台' && $data[0][9]!='sku' && $data[0][10]!='平台销售名称'){
                    throw new \Exception("excel格式错误,请检验表格");
                }
                unset($data['0']);
                $sql = "INSERT IGNORE INTO gone_jd_bound_lead (goods_id,sku_id,is_long,jd_goodn,pt_id,goods_name,company_id,is_state,creactor,state_explain,creact_time,update_time) VALUES ";
                foreach ($data as $key => $val){
                    if($this->restrict($data[$key]['0'])!='' && $this->restrict($data[$key]['9'])!='') {
                        $sqls[] = "('" . $this->restrict($data[$key]['0']) . "','" . $this->restrict($data[$key]['9']) . "','1','" . $this->restrict($data[$key]['10']) . "','" . $p_id . "','" . $this->restrict($data[$key]['4']) . "','" . $company_id . "','1','" . $admin_acc . "','未处理','" . date("Y-m-d H:i:s") . "','" . date("Y-m-d H:i:s") . "')";
                    }
                }
                $sql.=implode(',',$sqls);
                DB::insert($sql);
            });
            if (file_exists($filename)){
                //echo 11;
                unlink($filename);
            }
            unset($data);
            $content = '导入了文件'.$filename;
            $this->insertingLog('导入，','',$content,'绑定sku',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('导入成功1');
        }catch(\Exception $e){
            return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);
        }
    }
    //去除空格
    function restrict($str){
        $is_str=array(" ","　","\t","\n","\r","	");
        $is_str_er=array("","","","","","");
        return str_replace($is_str,$is_str_er,$str);
    }

    /**|---------------------------------------------------------------------------------
     * @name 同步绑定
     * @param string is_type 同步类型1指定同步2批量同步
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2025/4/10 18:13
     * |---------------------------------------------------------------------------------
    */
	public function sysLeadBound ( Request $request ){
	    $session = $request->get('session_token');
	    $input = $request->all();
        if (!$request->filled('is_type') || !in_array($input['is_type'], [1,2])){
            return $this->error('操作类型错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        if($input['is_type'] == 1) {
            if (!$request->filled('id')) {
                return $this->error('缺少数据id', ErrorInc::FAILED_PARAM, []);
            }
            $data = JdBoundLead::where('id',$input['id'])->where('is_state',1)->where('company_id',$session['company_id'])->first();
            if(empty($data)){
                return $this->error('数据状态错误', ErrorInc::REQUEST_FORBIDDEN);
            }
        }else{
            $data = JdBoundLead::where('is_state',1)->where('company_id',$session['company_id'])->orderBy('id')->first();
            if(empty($data)){
                return $this->error('无更多数据', ErrorInc::DATA_EMPTY);
            }
        }
        $data = CommonService::dataToArray($data);
        $list = JdBound::where('sku_id',$data['sku_id'])->first();
        $poss['goods_id'] = $data['goods_id'];
        $poss['jd_goodn'] = $data['jd_goodn'];
        $poss['pt_id'] = $data['pt_id'];
        $poss['goods_name'] = $data['goods_name'];
        $poss['goods_number'] = PjGoods::where("pg_id",$data['goods_id'])->value("version");
        $poss['company_id'] = $data['company_id'];
        DB::beginTransaction();
        if($list){
            $res = JdBound::where('sku_id',$data['sku_id'])->update($poss);
            $content = '绑定编辑sku:'.$data['sku_id'].';id='.$data['id'];
        }else{
            $poss['is_long'] = $data['is_long'];
            $poss['sku_id'] = $data['sku_id'];
            $res = JdBound::insert($poss);
            $content = '绑定添加sku:'.$data['sku_id'].';id='.$data['id'];
        }
        if($res){
            $rea = JdBoundLead::where('id',$data['id'])->update(['is_state'=>3,'state_explain'=>'绑定成功','update_time'=>date("Y-m-d H:i:s")]);
            if($rea){
                $this->insertingLog("绑定，",$data['sku_id'],$content,"平台商品绑定",$request->ip(),$request->get('session_token')['admin_acc']);//日志
                DB::commit();
                return $this->success('操作成功'); exit;
            }else{
                DB::rollback();
                return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED, []);
            }
        }else{
            DB::rollback();
            $rea = JdBoundLead::where('id',$data['id'])->update(['is_state'=>2,'state_explain'=>'同步失败','update_time'=>date("Y-m-d H:i:s")]);
            return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED, []);
        }
	}

	/**|---------------------------------------------------------------------------------
	 * @name 忽略数据
	 * @param string id 数据id
	 * @retrun \Illuminate\Http\JsonResponse
	 * @author dou 2025/4/10 18:59
	 * |---------------------------------------------------------------------------------
	*/
	public function deleteLeadBound ( Request $request ){
        $input = $request->all();
        if (!$request->filled('id')) {
            return $this->error('缺少数据id', ErrorInc::FAILED_PARAM, []);
        }
        $data = JdBoundLead::where('id',$input['id'])->where('is_state',2)->first();
        $data = CommonService::dataToArray($data);
        if(empty($data) || $data['is_state']!=2){
            return $this->error('数据状态错误', ErrorInc::REQUEST_FORBIDDEN);
        }
        $rea = JdBoundLead::where('id',$data['id'])->update(['is_state'=>4,'state_explain'=>'已忽略','update_time'=>date("Y-m-d H:i:s")]);
        if($rea){
            $content = '忽略数据sku:'.$data['sku_id'].';id='.$data['id'];
            $this->insertingLog("忽略，",$data['sku_id'],$content,"平台商品绑定",$request->ip(),$request->get('session_token')['admin_acc']);//日志
            return $this->success('操作成功');
        }else{
            return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED, []);
        }
	}
}
