<?php

namespace App\Admin\Controllers;

use Dcat\Admin\Admin;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;

class DhController extends BaseController
{
    public function index(Content $content)
    {
        $username = Admin::user()->username;
        $sddm = Admin::user()->sddm;
        $db2=$this->db2;

        $kh=$db2->select("SELECT KHDM FROM KEHU WHERE (KHDM='{$sddm}' OR BZ='{$sddm}')");
        if (empty($kh)) {
            return $content->body(view('error', ['error' =>'当前账号角色不允许扫码订货！']));
        }
        $DJBH =  $db2->table('DHJRD_E')
                ->selectRaw('DJBH')
                ->whereRaw("DM1='{$sddm}' AND DJBH LIKE '%MX%'")
                ->first();
        if (empty($DJBH)) {
            // $db2->delete("DELETE FROM DHJRDMX_E WHERE DJBH IN(SELECT DJBH FROM DHJRD_E WHERE DM1='{$sddm}')");
            // $db2->delete("DELETE FROM DHJRD_E WHERE DM1='{$sddm}'");
            //创建主表
            $DJH =  $db2->table('DJBHWH')
                ->selectRaw('(DJH+1) DJH')
                ->whereRaw("DJMC='M' AND DM='{$sddm}'")
                ->first();
            if (empty($DJH)) {
                $XH=1;
                $db2->insert("INSERT INTO DJBHWH (BMFS,DJMC,DM,DJH) VALUES (0,'M','{$sddm}',1)");
            }else{
                $XH=$DJH->DJH;
                $db2->insert("UPDATE DJBHWH SET DJH='{$XH}' WHERE DM='{$sddm}'");
            }
            $djh='M_'.$sddm.'_MX_'.substr('0000'.$XH, -4);
            // 查出主表数据
            $z_sql = " INSERT INTO DHJRD_E (DJBH,RQ,ZDR,DM1,DM4_1,SL,JE,YS,SP,XC,JZ,YXRQ,RQ_4,BYZD6,BYZD15,DJXZ,DJSX) VALUES 
            ('{$djh}',CONVERT(VARCHAR(10),GETDATE(),120),'{$username}','{$sddm}','000','0','0','0','0','0','0',CONVERT(VARCHAR(10),GETDATE()+30,120),CONVERT(VARCHAR(10),GETDATE(),120),'',GETDATE(),'0','000') ";
            $db2->insert($z_sql);
        }else{
            $djh=$DJBH->DJBH;
        }
        return $content->body(view('dh', ['djh'=>$djh]));
    }
    public function getdjspmx(Request $request){
        $param=$request->input();
        $data = $this->db2->select("SELECT SPDM,CAST(CKJ AS INT) CKJ,CAST(SUM(SL) AS INT) SL,CAST(SUM(SL)*CKJ AS INT) JE 
        FROM DHJRDMX_E WHERE DJBH='{$param['djh']}' 
        GROUP BY SPDM,CKJ");
        return response()->json($data);
    }
    public function deldjspmx(Request $request){
        $param=$request->input();
        $res=$this->db2->delete("DELETE FROM DHJRDMX_E WHERE DJBH = '{$param['djh']}' AND SPDM='{$param['spdm']}'");
        if ($res) {
            return response()->json([
                'error' => 0,
                'msg' => '成功',
            ]);
        }else{
            return response()->json([
                'error' => 1,
                'msg' => '失败',
            ]);
        }
    }

    public function change(Request $request){
        $input      =   $request->input();
        $username   =   Admin::user()->username;
        $sddm       =   $input['sddm'];
        $db2        =   $this->db2;

        $DJBH =  $db2->table('DHJRD_E')
                ->selectRaw('DJBH')
                ->whereRaw("DM1='{$sddm}' AND DJBH LIKE '%MX%'")
                ->first();
        if (empty($DJBH)) {
            //创建主表
            $DJH =  $db2->table('DJBHWH')
                ->selectRaw('(DJH+1) DJH')
                ->whereRaw("DJMC='M' AND DM='{$sddm}'")
                ->first();
            if (empty($DJH)) {
                $XH=1;
                $db2->insert("INSERT INTO DJBHWH (BMFS,DJMC,DM,DJH) VALUES (0,'M','{$sddm}',1)");
            }else{
                $XH=$DJH->DJH;
                $db2->insert("UPDATE DJBHWH SET DJH='{$XH}' WHERE DM='{$sddm}'");
            }
            $djh='M_'.$sddm.'_MX_'.substr('0000'.$XH, -4);
            // 查出主表数据
            $z_sql = " INSERT INTO DHJRD_E (DJBH,RQ,ZDR,DM1,DM4_1,SL,JE,YS,SP,XC,JZ,YXRQ,RQ_4,BYZD6,BYZD15,DJXZ,DJSX) VALUES 
            ('{$djh}',CONVERT(VARCHAR(10),GETDATE(),120),'{$username}','{$sddm}','000','0','0','0','0','0','0',CONVERT(VARCHAR(10),GETDATE()+30,120),CONVERT(VARCHAR(10),GETDATE(),120),'',GETDATE(),'0','000') ";
            $db2->insert($z_sql);
        }else{
            $djh=$DJBH->DJBH;
        }

        return response()->json([
            'error' => 0,
            'djh' => $djh,
            'msg' => '成功',
        ]);
    }

    public function getsp(Request $request){
        $param=$request->input();
        $ID=$param['code'];
        
        if (is_numeric($ID)) {
            $data = $this->db2->select("SELECT id,spdm,xh FROM SHANGPINID WHERE xh='{$ID}' 
                    UNION ALL
                    SELECT id,spdm,xh FROM SHANGPINID WHERE SPDM LIKE '%{$param['code']}%'");
        }else{
            $data = $this->db2->select("SELECT id,spdm,xh FROM SHANGPINID WHERE SPDM LIKE '%{$param['code']}%'");
        }

        return response()->json($data);
    }

    public function searchYp(Request $request)
    {
        $username = Admin::user()->username;
        $sddm = Admin::user()->sddm;
        $param = $request->input();
        if(empty($param['code'])){
            return response()->json(['error' => 1,'msg' => '商品或ID不能为空!']);
        }

        $sddm=$param['sddm'];
        $djh=$param['djh'];
        $ID=$param['code'];
        
        if (is_numeric($ID)) {
            $where="AND (xh='{$ID}' OR spdm like '%{$param['code']}%')";
        }else{
            $where="AND spdm like '%{$param['code']}%'";
        }

        $data = $this->db2->select("SELECT SPDM FROM SHANGPINID WHERE 1=1 {$where}");
        if (empty($data)) {
            return response()->json(['error' => 1,'msg' => '当前会场无此货号！']);
        }
        $code=$data[0]->SPDM;

        $size_sql = "SELECT distinct GUIGE2.GGDM,GUIGE2.GGMC,GUIGE2.GGWZ1,GUIGE2.GGWZ2      
		FROM YPGG2,GUIGE2,YANGPIN
        where YANGPIN.YPDM = '{$code}' and YPGG2.GGID = GUIGE2.GGDM  AND YANGPIN.MID=YPGG2.PID
        order by GUIGE2.GGWZ1,GUIGE2.GGWZ2";
    

        $size_list = objectToArray($this->db2->select($size_sql));

        if(empty($size_list)){
            return response()->json(['error' => 1,'msg' => '商品未维护！']);
        }
        $strcol='';
        foreach ($size_list as $key => $value) {
            $strcol .= "CAST(SUM(CASE WHEN gg2.GGWZ2='{$value['GGWZ2']}' THEN mx.SL ELSE 0 END) AS INT) AS 'SL_{$value['GGWZ2']}',";
            $size_arr['list'][$value['GGWZ1']][$value['GGWZ2']] = $value['GGDM'];
            $ggwz2_arr[] = $value['GGWZ2'];
        }
        $ggwz2_arr = array_unique($ggwz2_arr);
        sort($ggwz2_arr);
        //列
        $size_arr['max_col'] = count($ggwz2_arr);
        $size_arr['ggwz2_arr'] = $ggwz2_arr;
        //行
        $size_arr['max_row'] = count($size_arr['list']);

        $strcol=trim($strcol,',');


        $fjsx =  $this->db2->table('TBL_YPFJSX')
        ->selectRaw('*')
        ->whereRaw("YPDM='{$code}'")
        ->first();

        $lsdh = $this->db3->select("SELECT yp.SPDM YPDM,yp.SPMC YPMC,yp.BZSJ CKJ,gg1.GGDM gg1dm,gg1.GGMC gg1mc,
        CAST(SUM(mx.SL) AS INT) AS HJ_SL,{$strcol}
        FROM SHANGPIN yp
        INNER JOIN SPGG1 ygg1 ON yp.SPDM = ygg1.SPDM
        INNER JOIN guige1 gg1 ON ygg1.GGDM = gg1.GGDM 
        INNER JOIN SPGG2 ygg2 ON yp.SPDM = ygg2.SPDM
        INNER JOIN GUIGE2 gg2 ON ygg2.GGDM = gg2.GGDM  
        LEFT JOIN PHJRDMX mx ON mx.SPDM=yp.SPDM AND mx.GG1DM=gg1.GGDM AND mx.GG2DM=gg2.GGDM 
        AND mx.DJBH IN (SELECT DJBH FROM PHJRD WHERE DM1='{$sddm}' AND RQ>=CONVERT(varchar(10),getdate()-120,120) AND SP=0)
        WHERE mx.SPDM = '{$code}'
        GROUP BY yp.SPDM,yp.SPMC,gg1.GGDM,gg1.GGMC,yp.BZSJ");

        $sp = $this->db2->select("SELECT yp.YPDM,yp.YPMC,yp.BZSJ CKJ,gg1.GGDM gg1dm,gg1.GGMC gg1mc,
        CAST(SUM(mx.SL) AS INT) AS HJ_SL,{$strcol}
        FROM YANGPIN yp 
        LEFT JOIN YPGG1 ygg1 ON yp.MID = ygg1.PID
        LEFT JOIN GUIGE1 gg1 ON ygg1.GGID = gg1.GGDM 
        LEFT JOIN YPGG2 ygg2 ON yp.MID = ygg2.PID
        LEFT JOIN GUIGE2 gg2 ON ygg2.GGID = gg2.GGDM  
        LEFT JOIN DHJRDMX_E mx ON mx.SPDM=yp.YPDM AND mx.GG1DM=gg1.GGDM AND mx.GG2DM=gg2.GGDM AND mx.DJBH='{$djh}'
        WHERE YPDM = '{$code}' AND yp.TZSY = 0 AND yp.DHH = '000'
        GROUP BY yp.YPDM,yp.YPMC,gg1.GGDM,gg1.GGMC,yp.BZSJ ");
        

        if(!$sp){
            return response()->json(['error' => 1,'msg' => '商品不存在！']);
        }
        return response()->json([
            'error' => 0,
            'msg' => '查询成功',
            'data' =>$sp,
            'lsdh' =>$lsdh,
            'fjsx' =>$fjsx,
            'size_arr' => $size_arr
        ]);
    }

    public function submit(Request $request)
    {
        $param = $request->input();
        $username = Admin::user()->username;
        $sddm = Admin::user()->sddm;

        
        $djh  = $param['djh'];
        $spdm = $param['code'];
        $ckj = $param['ckj'];

        $this->db2->beginTransaction();
        try {
            $this->db2->delete("DELETE FROM DHJRDMX_E WHERE DJBH = '{$djh}' AND SPDM='{$spdm}'");
            $f_sql = " INSERT INTO DHJRDMX_E (DJBH,SPDM,GG1DM,GG2DM,SL,CKJ,ZK,DJ,JE,BYZD14,BZ) VALUES ";
            $sum_sl = 0;
            foreach ($param['sp'] as $v){
                $arr = explode('_',array_key_first($v));
                $gg1 = $arr[0];
                $gg2 = $arr[1];
                $sl = (int)array_shift($v);
                $sum_sl += $sl;
                $mx_info = $this->db2->select(" SELECT * FROM DHJRDMX_E WHERE DJBH = '{$djh}' AND SPDM = '$spdm' AND GG1DM = '$gg1' AND GG2DM = '$gg2' ");
                if($mx_info){
                    $this->db2->update(" UPDATE DHJRDMX_E SET SL = {$sl} WHERE DJBH = '{$djh}' AND SPDM = '$spdm' AND GG1DM = '$gg1' AND GG2DM = '$gg2' ");
                }else{
                    $f_sql .= " ('{$djh}','{$spdm}','{$gg1}','{$gg2}','{$sl}','{$ckj}','1','0','0',GETDATE(),''),";
                }
            }
            // 判断最后一个是不是逗号
            if(preg_match('/,$/', $f_sql)){
                // 删除最后一个值的逗号
                $f_sql =  substr($f_sql,0,strlen($f_sql)-1);
                $this->db2->insert($f_sql);
            }
            $this->db2->update(" UPDATE DHJRD_E SET SL=(SELECT SUM(SL) FROM DHJRDMX_E WHERE DJBH='{$djh}') WHERE DJBH = '{$djh}' ");

            $this->db2->commit();
        }catch (\Exception $e){
            $this->db2->rollBack();
            return response()->json([
                'error' => 1,
                'msg' => '失败，'.$e->getMessage(),
            ]);
        }
        return response()->json([
            'error' => 0,
            'msg' => '成功',
            'data' => ''
        ]);
    }
}
