<?php
/**
 * 文件名称（回收订单管理）
 * 文件简单描述（订单回收相应操作以及信息展示）
 * @author DouBin
 * @Date: 2021/9/17
 * @Time: 15:00
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Http\Controllers\orders;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Models\PjGoods;
use App\Models\RecycleGoods;
use App\Models\RecycleOrders;
use App\Models\Refund;
use App\Models\SubmitPlease;
use App\Services\CommonService;
use App\Services\OrderService;
use App\Services\PlatformService;
use App\Services\RecycleOrderService;
use App\Services\RefundService;
use App\Services\SendGoodsService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use DB;

class RecycleOrderController extends BaseController{
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param int state 处理状态 0全部1未处理 5回收失败/未回收 10回收成功
     * @param string order_num 订单单号
     * @param int creact_id 创建人id
     * @param int ro_type 回收类型
     * @param array creatData 创建时间
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/17 15:06
     * |---------------------------------------------------------------------------------
    */
    public function index ( Request $request ){
        if($request->filled('state')){
            $data = RecycleOrderService::getList($request->all(), $request->get("session_token"));
            if($data['ErrorCode']!=1){
                return $data;
            }else {
                $list = $data['Data'];

                //导出 start
                if ($request->input('is_excel') == 1) {
                    $sqls = $list['sqls'];
                    $excel = new CommonController();
                    return $excel->getExcelOut($request->input('Pri_id'), $sqls, $request->get("session_token"));
                }
                unset($list['sqls']);
                //导出 end
                if ($list['list']) {
                    return $this->success('获取成功', $list);
                    exit;
                } else {
                    return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $list);
                    exit;
                }
            }
        }else{
            return $this->error('缺少参数state', ErrorInc::INVALID_PARAM);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 驳回回收申请
     * @param int id 数据id
     * @param sting remark 操作备注
     * @param sting recycle_num 回收单号
     * @param sting ro_sysnum 系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/18 15:04
     * |---------------------------------------------------------------------------------
    */
    public function rejectedData ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        $return = RecycleOrderService::rejOrResData($input, 15, '驳回，', $session, $request->ip());
        return $return;
    }

    /**|---------------------------------------------------------------------------------
     * @name 恢复回收申请
     * @param int id 数据id
     * @param sting remark 操作备注
     * @param sting recycle_num 回收单号
     * @param sting ro_sysnum 系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/18 15:04
     * |---------------------------------------------------------------------------------
     */
    public function restoreData ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        if($input['ro_type']==2){
            return $this->error('库房发货不可恢复', ErrorInc::MYSQL_FAILED);
        }
        $return = RecycleOrderService::rejOrResData($input, 1, '恢复，', $session, $request->ip());
        return $return;
    }

    /**|---------------------------------------------------------------------------------
     * @name 处理回收
     * @param int org_id 回收单商品表id
     * @param int type 处理状态，1完成处理，2部分处理
     * @param string normal_num 正常数量
     * @param string defect_num 残损数量
     * @param string detection_num 检测数量
     * @param string lossof_num 快递丢失
     * @param string accept_num 客户收货
     * @param string courier_number 快递单号
     * @param int mandatory 强制完成 1正常完成2强制完成
     * @param int remark 强制完成备注
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/18 16:26
     * |---------------------------------------------------------------------------------
    */
    public function dealData ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey=CommonService::checkKey(['org_id', 'type', 'normal_num','defect_num','detection_num','lossof_num','accept_num','mandatory'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if($input['mandatory'] == 2 && !isset($input['remark'])){
            return $this->error('强制完成必须填写备注', ErrorInc::INVALID_PARAM);exit;
        }
        $db = new RecycleGoods();
        $RecycleGoods = CommonService::getMysqlData($db, ['rog_id'=>$input['org_id']],['rog_goodsnum','rog_rid','rog_goodsname','rog_ronum'],[],'first');
        if($RecycleGoods){
            $num = $input['normal_num']+$input['defect_num']+$input['detection_num']+$input['lossof_num']+$input['accept_num'];
            if(($num < $RecycleGoods['rog_goodsnum'] && $input['type']==1 && $input['mandatory']==1) || $num > $RecycleGoods['rog_goodsnum']){
                return $this->error('商品处理数量异常请核实', ErrorInc::FAILED_PARAM);exit;
            }else{
                $remaerk = '';
                if(isset($input['remark'])){
                    $remaerk = $input['remark'].';';
                }
                $remaerk .=$RecycleGoods['rog_goodsname']."(".$input['normal_num'].",".$input['defect_num'].",".$input['detection_num'].",".$input['lossof_num'].",".$input['accept_num'].")";
                if($input['type']==1 || $num == $RecycleGoods['rog_goodsnum']){
                    $poss['rog_dealtype'] = 10;
                    $goodsstate ='完成';
                }else{
                    $poss['rog_dealtype'] = 5;
                    $goodsstate ='处理中';
                }
                $poss['courier_number'] = $input['courier_number'];
                $poss['normal_num'] = $input['normal_num'];
                $poss['defect_num'] = $input['defect_num'];
                $poss['detection_num'] = $input['detection_num'];
                $poss['lossof_num'] = $input['lossof_num'];
                $poss['accept_num'] = $input['accept_num'];
                DB::beginTransaction(); //开启事务
                $rea = RecycleGoods::where("rog_id",$input['org_id'])->update($poss);
                $rog_dealtype = RecycleGoods::where("rog_rid",$RecycleGoods['rog_rid'])->where("rog_dealtype",'!=','10')->value('rog_id');
                if($rog_dealtype){
                    $posa['ro_dealtype'] = 5;
                    $orderstate ='处理中';
                }else{
                    $posa['ro_dealtype'] = 10;
                    $orderstate ='完成';
                }
                $ree = RecycleOrders::where("ro_id",$RecycleGoods['rog_rid'])->update($posa);
                if($rog_dealtype){
                    $ree = true;
                }
                if($rea && $ree){
                    DB::commit();
                    $this->insertinglog('处理回收单',$RecycleGoods['rog_ronum'],"回收单号：".$RecycleGoods['rog_ronum'].';'.$remaerk."(".$goodsstate.")","回收商品管理",$request->ip(), $session['admin_acc']);
                    $this->insertinglog('处理回收单',$RecycleGoods['rog_ronum'],"回收单号：".$RecycleGoods['rog_ronum'].';('.$orderstate.')',"回收商品管理",$request->ip(), $session['admin_acc']);
                    return $this->success('操作成功');

                }else{
                    DB::rollback();
                    return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
                }
            }
        }else{
            return $this->error('无对应数据信息', ErrorInc::DATA_EMPTY);exit;
        }
    }

    /**
     * 编辑快递信息
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/14
     */
    public function editCourier(Request $request){
        if(!$request->filled('courier_number')||!$request->filled('courier_company')||!$request->filled('ro_id')){
            return $this->error('参数错误请填写快递单号或快递公司', ErrorInc::FAILED_PARAM, []);exit;
        }
        $courier_number = $request->input('courier_number');
        $courier_company = $request->input('courier_company');
        $id = intval($request->input('ro_id'));
//        $r = RecycleOrders::where('ro_id',$id)->value('ro_ordernum');
        $data = RecycleOrderService::getRecycleOrderBy('ro_id', $id);
        if(!$data){
            return $this->error('不存在', ErrorInc::FAILED_PARAM, []);exit;
        }
        $ret = RecycleOrders::where('ro_id','!=',$id)->where('courier_number',$courier_number)->where('courier_company',$courier_company)->value('ro_id');
        if($ret){
            return $this->error('已存在快递信息', ErrorInc::FAILED_PARAM, []);exit;
        }
        DB::beginTransaction();
//        DB::rollBack();
//        DB::commit();
        $res = RecycleOrders::where('ro_id',$id)->update(['courier_number'=>$courier_number,'courier_company'=>$courier_company]);
        if($res){
            if($data['ro_type']==2 || $data['ro_type']==4) {
                if($data['courier_number']!='' && $data['courier_number']!=null){
                    $zhipei['time'] = date('Y-m-d H:i:s');
                    $zhipei['signature'] = md5($zhipei['time'] . '97e11cbcc29cbd8a538395abce85d569');
                    $zhipei['ser_num'] = $data['recycle_num'];
                    $zhipei['kd_number'] = $courier_number;
                    $res = CommonService::requestPost('http://jx.bluearp.com/m/index.php/PartyIrderInterfaceThree/ModifyExpress', json_encode($zhipei), array('Content-Type: application/json'));
                    $datas = json_encode($zhipei) . '---' . $res;
                    CommonService::addLog('编辑快递单号', $datas, $data['recycle_num'], 'warehouse-editkdnumber');
                    $res = json_decode($res, true);
                    if($res['code']!=200){
                        DB::rollBack();
                        return $this->error('同步智配失败', ErrorInc::TRANSFER_FAILED);
                        exit;
                    }
                }else {
                    $p_id = OrderService::getOrderBy('order_num', $data['ro_ordernum'], ['p_id']);
                    $refund = RefundService::getInfoByKeyValue('recycle_id', $id, ['goods_price', 'apply_type', 'goods_state'], 'first');
                    if ($refund) {
                        if ($refund['apply_type'] == '1') {
                            $refund_type = 3;
                        } else {
                            $refund_type = 2;
                        }
                        $refund_price = $refund['goods_price'];
                    } else {
                        $refund_type = 1;
                        $refund_price = 0;
                        $refund['goods_state'] = 0;
                    }
                    $p_id = PlatformService::getPtBy('id', $p_id, ['zp_id']);
                    if (!$p_id) {
                        return $this->error('未匹配平台编号', ErrorInc::TRANSFER_FAILED, []);
                        exit;
                    }
                    $ware_id = $data['receiving_id'] ?? 4;
                    $order_num = SendGoodsService::getSendGoodBy(['order_num' => $data['order_num']], ['warehouse_num'], 'first');
                    if (!$order_num) {
                        $order_num = $data['ro_ordernum'];
                    }
                    $dataState = OrderService::getDataState($refund['goods_state']);
                    if (!$dataState) {
                        $dataState['goods_state'] = 1;
                    }
                    if ($data['ro_reason'] == 1) {
                        $is_barter = 2;
                    } else {
                        $is_barter = 1;
                    }
                    if($data['ro_type']==4){
                        $is_barter = 3;
                    }
                    $orderInfo = ['pt_id' => $p_id, 'is_barter' => $is_barter, 'company_id' => '1', 'ware_id' => $ware_id, 'order_num' => $order_num, 'sys_num' => $data['ro_sysnum'], 'ser_num' => $data['recycle_num'], 'user_name' => $data['send_name'], 'refund_type' => $refund_type, 'refund_price' => $refund_price, 'kd_number' => $courier_number, 'refund_state' => $dataState['goods_state'],'recoveryReason'=>$data['lable_name'],'is_cfr'=>$data['is_cfr']];
                    $recygood = RecycleOrderService::getRecycleGoods([$data['recycle_num']]);
                    $recygood = $recygood[$data['recycle_num']];
                    foreach ($recygood as $k => $v) {
                        $goods[$k]['goods_num'] = $v['rog_goodsnum'];
                        $goods[$k]['goods_id'] = 'wj0001';//PjGoods::where('pg_id', $v['rog_goodsid'])->value('general_version');//'wj0001';
                    }
                    $res = CommonService::sysErpRetrieveInfor($orderInfo, $goods , true);
                    $res = json_decode($res,true);
                    $inputs['data']['zhipei'] = $orderInfo;
                    $inputs['data']['zhipeigood'] = $goods;
                    $inputs['return'] = $res;
                    CommonService::addLog('通知库发回收', json_encode($inputs), $data['recycle_num'], 'warehouse-recycle');
                    if ($res['code'] != 200) {
                        DB::rollBack();
                        return $this->error('同步智配失败', ErrorInc::TRANSFER_FAILED);
                        exit;
                    }else{
                        $return = $res['data'];
                        if(!is_array($return)) {
                            if ($return['data'] == 1) {
                                $rea = RecycleOrders::where("ro_id", $id)->update(['ro_state' => 10, 'ro_dealtype' => 10]);
                                $ree = RecycleGoods::where("rog_rid", $id)->update(['rog_dealtype' => 10]);
                                RecycleOrderService::pushRecycle($order_num);
                            }
                        }else{
                            $poss['is_abnormal'] = $return['is_abnormal']??'2';
                            if (isset($return['recovery']) && $return['recovery'] == 1) {
                                $poss['ro_state'] = 10;
                                $poss['ro_dealtype'] = 10;
                                $ree = RecycleGoods::where("rog_rid", $id)->update(['rog_dealtype' => 10]);
                                RecycleOrderService::pushRecycle($order_num);
                            }
                            $rea = RecycleOrders::where("ro_id", $id)->update($poss);
                        }
                    }
                }
            }
            DB::commit();
            $this->insertingLog("编辑快递信息",$data['ro_ordernum'], "编辑快递信息：" .$courier_company."-". $courier_number, "回收商品管理", $request->ip(), $request->get('session_token')['admin_acc']);//日志
            return $this->success('操作成功',$res);exit;
        }else{
            DB::rollBack();
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 编辑回收金额
     * @param int id 数据id
     * @param string price 退货价格
     * @param string recycle_num 回收单号
     * @param string sys_num 系统单号
     * @param string content 备注
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/4/2 15:49
     * |---------------------------------------------------------------------------------
    */
    public function editPrice ( Request $request ){
        $input = $request->all();
        $checkKey = CommonService::checkKey(['id', 'price', 'content','recycle_num','sys_num'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
        }
        $refund_price = RecycleOrderService::getRecycleOrderBy('ro_id', $input['id'],['refund_price']);
        if($refund_price == $input['price']){
            return $this->success('操作成功');exit;
        }else{
            DB::beginTransaction();
            $refund_id = RefundService::getInfoByKeyValue('recycle_id', $input['id'],['id','goods_state'],'first');
            if(!$refund_id){
                return $this->error('回收未绑定退款请联系管理员核实', ErrorInc::INVALID_PARAM, []);
            }if(!$refund_id['goods_state']==4){
                return $this->error('财务退款不可修改金额', ErrorInc::INVALID_PARAM, []);
            }
            Refund::where('recycle_id',$input['id'])->update(['goods_price'=>$input['price']]);
            SubmitPlease::where('refund_id',$refund_id['id'])->update(['submit_money'=>$input['price']]);
            $res = RecycleOrders::where('ro_id',$input['id'])->update(['refund_price'=>$input['price']]);
            $this->accMe($input['sys_num'],'回收管理',"编辑回收金额(".$input['recycle_num'].")：".$input['content'],'','',$request->get('session_token')['admin_groupnew'],$request->get('session_token')['admin_acc'],$request->get('session_token')['id']);
            if($res){
                $zhipei['time'] = date('Y-m-d H:i:s');
                $zhipei['signature'] = md5($zhipei['time'] . '97e11cbcc29cbd8a538395abce85d569');
                $zhipei['ser_num'] = $input['recycle_num'];
                $zhipei['refund_price'] = $input['price'];
                $res = CommonService::requestPost('http://jx.bluearp.com/m/index.php/PartyIrderInterfaceThree/ModifyRefund', json_encode($zhipei), array('Content-Type: application/json'));
                $res = json_decode($res, true);
                $data = json_encode($zhipei) . '---' . json_encode($res);
                CommonService::addLog('修改退款金额', $data, $input['recycle_num'], 'warehouse-refund');
                if($res['code']!=200){
                    return  ['Data' => '','ErrorMessage'=>'同步智配失败:'.$res['data'],'ErrorCode'=>ErrorInc::TRANSFER_FAILED];exit;
                }
                DB::commit();
                $this->insertingLog("编辑回收金额",$input['sys_num'], "编辑金额：" .$refund_price."-". $input['price']."(".$input['recycle_num'].")", "回收商品管理", $request->ip(), $request->get('session_token')['admin_acc']);//日志
                return $this->success('操作成功',$res);exit;
            }else{
                DB::rollBack();
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }
    }

}
