<?php
namespace App\Http\Controllers\DatasBase;
use App\Http\Controllers\BaseController;
use App\Models\PtOrder;
use App\Models\PtPhistory;
use App\Models\SettlementThree;
use App\Services\CommonService;
use App\Services\PtPhistoryService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use DB;
use League\Flysystem\Exception;
use Excel;
/**
 * @name 平台回传价格
 * Class PtPhistoryController
 * @package App\Http\Controllers\DatasBase
 */
class PtPhistoryController extends BaseController{
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2022/6/16 21:08
     * |---------------------------------------------------------------------------------
    */
    public function index ( Request $request ){
        if (!$request->filled('state')) {
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM, []);
        }
        $input = $request->all();
        if(!in_array($input['state'],[0,1,5,10,15])){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }
        $list = PtPhistoryService::getList($input,$request->get('session_token'));
        if($list['list']){
            return $this->success('获取成功', $list); exit;
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$list);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 导入数据
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2022/6/15 19:40
     * |---------------------------------------------------------------------------------
    */
    public function uploadExcelImport ( Request $request ){
        try {
            $file = $request->file('file');

            $p_id = $request->input('p_id');//平台id
            $ph_mounth = $request->input('ph_mounth');//账期时间
            $admin_acc = $request->get('session_token')['admin_acc'];
            $admin_id = $request->get('session_token')['id'];
            if (!$file){
                throw new \Exception("请选择文件");
            }
            $ext = $file->getClientOriginalExtension();// 获取扩展名
            if(!in_array($ext,['xls','xlsx','csv'])){//判断格式
                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;
            Excel::load($filename,function($reader)use($admin_acc,$p_id,$ph_mounth,$admin_id){
                $reader = $reader->getSheet(0);

                $data = $reader->toArray();
                if($data[0][0]!='平台编号' && $data[0][1]!='1结款单2退款单' && $data[0][2]!='平台价格' && $data[0][3]!='商品信息'){
                    throw new \Exception("excel格式错误");
                }
                unset($data['0']);
                $sql = "INSERT IGNORE INTO gone_pt_order (ph_pid,ph_odnum,ph_type,ph_state,ph_creactime,ph_craectid,ph_craector,ph_price,ph_goods,ph_mounth) VALUES ";
                foreach ($data as $key => $val){
                    $sqls[]="('".$p_id."','".$this->restrict($data[$key]['0'])."','".$this->restrict($data[$key]['1'])."','1','".date("Y-m-d H:i:s")."','".$admin_id."','".$admin_acc."','".$this->restrict($data[$key]['2'])."','".$this->restrict($data[$key]['3'])."','".$ph_mounth."')";
                }
                $sql.=implode(',',$sqls);
                DB::insert($sql);
            });
            if (file_exists($filename)){
                //echo 11;
                unlink($filename);
            }
            unset($data);
            $content = '导入了文件'.$filename;
            $this->insertingLog('添加，','',$content,'平台价格回传',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('导入成功1');
            //return response()->json(['Data' => '','ErrorCode' => 1, 'ErrorMessage' => '导入成功1']);exit;
            exit;
        }catch(\Exception $e){
            return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);
            //return response()->json(['Data' => '', 'ErrorCode' => 3, 'ErrorMessage' => $e->getMessage()]);
            exit;
        }
    }
    //去除空格
    function restrict($str){
        $is_str=array(" ","　","\t","\n","\r","	");
        $is_str_er=array("","","","","","");
        return str_replace($is_str,$is_str_er,$str);
    }
    /**|---------------------------------------------------------------------------------
     * @name 执行数据
     * @param int state 数据状态
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/6/15 20:41
     * |---------------------------------------------------------------------------------
    */
    public function deal ( Request $request ){
        $input = $request->only('state');
        $checkKey = CommonService::checkKey(['state'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::FAILED_PARAM, []);
        }else{
            if(in_array($input['state'], ['1','5'])){
                if($input['state'] == 1){
                    $return = PtPhistoryService::dealPtOrder($input['state']);
                }else{
                    $return = PtPhistoryService::dealPtPhistory($input['state']);
                }
                if($return['ErrorCode'] == 4000) {
                    return $this->error($return['ErrorMessage'], $return['ErrorCode'], $return['Data']);
                }else{
                    return $this->error($return['ErrorMessage'], 1, $return['Data']);
                }
            }else{
                return $this->error('数据状态错误', ErrorInc::INVALID_PARAM);
            }
        }exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 单条执行数据
     * @param int state 数据状态
     * @param int ph_id 数据id
     * @param string ph_centent 手动核销备注
     * @param int type 执行类型1普通执行2强制执行
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/6/15 20:41
     * |---------------------------------------------------------------------------------
     */
    public function dealOne ( Request $request ){
        $input = $request->only('state','ph_id','ph_centent','type');
        $checkKey = CommonService::checkKey(['state','ph_id'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::FAILED_PARAM, []);
        }else{
            if(in_array($input['state'], ['5'])){
                if($input['type'] == 1){
                    $return = PtPhistoryService::dealPtPhistory($input['state'],$input['ph_id']);
                    return $this->error($return['ErrorMessage'], $return['ErrorCode'], $return['Data']);
                }else{
                    if($request->filled('ph_centent')) {
                        $data = PtPhistoryService::getDataBy(['ph_id' => $input['ph_id']], 'first',[]);
                        if($data) {
                            $ree = PtPhistory::where('ph_id', $input['ph_id'])->update(['ph_state' => 15, 'ph_updatetime' => date("Y-m-d H:i:s"), 'ph_centent' => $input['ph_centent']]);
                            SettlementThree::where("order_num", $data['ph_odnum'])->update(["is_verify" => 2]);
                            if ($ree) {
                                return $this->success('操作成功');
                            } else {
                                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
                            }
                        }else{
                            return $this->error('数据不存在', ErrorInc::DATA_EMPTY);
                        }
                    }else{
                        return $this->error('请填写备注', ErrorInc::FAILED_PARAM, []);
                    }
                }
            }else{
                return $this->error('数据状态错误', ErrorInc::INVALID_PARAM);
            }
        }exit;
    }
}
