<?php

namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\PjGoods;
use App\Models\RecycleGoods;
use App\Models\RecycleOrders;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use DB;
use App\Models\Admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use phpDocumentor\Reflection\Types\Self_;


class RecycleOrderService extends Service
{
    /**|---------------------------------------------------------------------------------
     * @name 添加回收单
     * @param array $input 添加回收单对应信息
     * @param array $session 操作人信息
     * @param string $ip 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/8/24 20:47
     * |---------------------------------------------------------------------------------
    */
    public static function creactRecycle ( $input , $session , $ip ){
        $recycle_num = 'H'.CommonService::creactNumber();
        /*--------------------------------------------添加回收单开始-------------------------------------------*/
        $recycle['recycle_num'] = $recycle_num;//回收单号
        $recycle['ro_sendnum'] = '';//发货单号
        $recycle['ro_sysnum'] = $input['sys_num'];//系统单号
        $recycle['courier_number'] = $input['courier_number']??'';//快递单号
        $recycle['is_opened'] = $input['is_opened']??'2';//快递单号
        $recycle['ro_ordernum'] = $input['order_num'];//订单单号
        $recycle['ro_type'] = $input['recycle_type'];//回收类型1门店回收  2 库房回收
        $recycle['ro_ctime'] = date("Y-m-d H:i:s");//创建时间
        $recycle['receiving_id'] = $input['store_id'];//收货部门编号
        $recycle['send_type'] = $input['send_type'];//发货类型1门店发回2客户发货
        $recycle['lable_id'] = $input['lable_id']??0;//申请标签
        $recycle['lable_name'] = $input['lable_name']??'';//申请原因
        $recycle['is_cfr'] = $input['is_cfr']??2    ;//是否为cfr
        if($recycle['send_type'] == '1'){
            if(!isset($input['send_id'])){
                return  ['Data' => '','ErrorMessage'=>'发货部门必选','ErrorCode'=>ErrorInc::INVALID_PARAM];
            }
            $recycle['send_id'] = $input['send_id'];//发货门店id
            //回收单明细表信息
            $regood['rog_sendid'] = $input['send_id'];//发货门店id
        }
        if($recycle['send_type'] == '2'){
            if(!isset($input['send_name']) || !isset($input['telephone'])){
                return  ['Data' => '','ErrorMessage'=>'发货人姓名/发货人电话必填','ErrorCode'=>ErrorInc::INVALID_PARAM];
            }
            $recycle['send_name'] = $input['send_name'];//发货人姓名
            $recycle['telephone'] = $input['telephone'];//发货人电话
            //回收单明细表信息
            $regood['rog_name'] = $input['send_name'];//发货人姓名
            $regood['rog_telephone'] = $input['telephone'];//发货人电话
        }

//        DB::beginTransaction();

        $recycle['creactor'] = $session['admin_acc'];//添加人
        $recycle['creact_id'] = $session['id'];//创建人id
        $recycle['afid'] = $input['after_id'];//售后id

        $recycle['ro_reason'] = $input['ro_reason']??1;// 2022-3-1 新增 回收原因：1换货回收（等于1补发必须填写） 2退款回收（等于2时必须填写退款单） 3只回收

        $res = RecycleOrders::insertGetId($recycle);
        /*--------------------------------------------添加回收单结束-------------------------------------------*/
        if($res){
            /*---------------------------------------添加回收单商品明细开始-------------------------------------*/
            $goodsArr = $input['goodsArr'];
            $msg = [];
            $goodsZhi = [];
            foreach($goodsArr as $k => $v){
                if($input['recycle_type'] == 3){
                    $goodsZhi[$k]['goods_number'] = $v['goods_id'];
                    $goodsZhi[$k]['goods_name'] = $v['goods_name'];
                    $goodsZhi[$k]['num'] = $v['goods_num'];
                    $goodsZhi[$k]['barcode'] = $v['bar_code'];//
                }
                if(isset($msg[$v['goods_id']])){
                    $msg[$v['goods_id']]['goods_num'] += $v['goods_num'];
                    $msg[$v['goods_id']]['msg_id'] .= ','.$v['msg_id'];
                }else{
                    $msg[$v['goods_id']] = $v;
                }
            }
            $regood['rog_rid'] = $res;//回收单id
            $regood['rog_ronum'] = $recycle_num;//回收单号
            $regood['courier_number'] = $input['courier_number']??'';//快递单号
            $regood['rog_ordernum'] = $input['order_num'];//订单单号
            $regood['rog_type'] = $input['recycle_type'];//回收类型1门店回收  2 库房回收
            $regood['receiving_id'] = $input['store_id'];//收货部门编号
            $regood['rog_sendtype'] = $input['send_type'];//发货类型1门店发回2客户发货
            $num = 0;
            foreach($msg as $k => $v){
                if($v['goods_id'] == '5912'){
                    return  ['Data' => '','ErrorMessage'=>'回收商品'.$v['goods_name'].'异常请删除商品后从新选择','ErrorCode'=>ErrorInc::INVALID_PARAM];
                }
                $regood['rog_goodsid'] = $v['goods_id'];
                $regood['rog_goodsname'] = $v['goods_name'];
                $regood['rog_goodsnum'] = $v['goods_num'];
                $regood['rog_msgid'] = $v['msg_id'];

                $goods[$k]['goods_num'] = $v['goods_num'];
                $goods[$k]['goods_id'] = PjGoods::where('pg_id',$v['goods_id'])->value('general_version');//'wj0001';


                $rea = RecycleGoods::insert($regood);
                if(!$rea){
//                    DB::rollback();
                    return  ['Data' => '','ErrorMessage'=>'操作失败rg','ErrorCode'=>ErrorInc::MYSQL_FAILED];
                }
            }

            if(isset($input['courier_number']) && $input['courier_number']!='') {
                if ($input['recycle_type'] == 3){
                    //同步智配 京仓回收 start
                    if($recycle['ro_reason'] == 1){
                        $is_barter = 2;
                    }else{
                        $is_barter = 1;
                    }
                    $zhipei['is_barter'] = $is_barter;
                    $zhipei['time'] = date('Y-m-d H:i:s');
                    $zhipei['signature'] = md5($zhipei['time'].'97e11cbcc29cbd8a538395abce85d569');
                    $zhipei['ware_id'] = 4;
                    $zhipei['company_id'] = 1;
                    $zhipei['pt_id'] = $input['pt_id'];
                    $zhipei['order_data']['ser_num'] = $recycle_num;
                    $zhipei['order_data']['number'] = $input['order_num'];//退货单号
                    $zhipei['order_data']['out_number'] = $input['sys_num'];//
                    $zhipei['order_data']['waybill'] = $input['courier_number'];//
                    //$zhipei['order_data']['barcode'] = $input['bar_code'];//
                    $zhipei['order_data']['purchaser'] = $input['Purchasing'];//

                    $zhipei['order_data']['goods'] = $goodsZhi;
                    $url = self::getErpUrl(false) . '/addJdwareRecycling';
                    $ret_zhipei = CommonService::requestPost($url, json_encode($zhipei), array('Content-Type: application/json'));

                   // $ret_zhipei['code'] = 200;
                    //$ret_zhipei['data'] = '测试';
                    $ret_zhipeir = json_decode($ret_zhipei,true);

                    $data = json_encode($zhipei) . '---' .$ret_zhipei;
                    CommonService::addLog('京仓回收', $data, $recycle_num, 'JD-recycle');
              if($ret_zhipeir['code']!=200){
                    return  ['Data' => '','ErrorMessage'=>'同步智配失败:'.$ret_zhipeir['data'],'ErrorCode'=>ErrorInc::TRANSFER_FAILED];
                }else{
                 // echo $ret_zhipeir['data']['recovery'];
                  if($ret_zhipeir['data']['recovery']==1){
                      $rea = RecycleOrders::where("ro_id",$res)->update(['ro_state'=>10,'ro_dealtype'=>10]);
                      if(!$rea){
                          $msgBody['pushtyep'] = 'saveRetrieve';//方法名
                          $msgBody['ro_id'] = $res;
                          //DB::rollBack();
                          BaseController::pushRecord($msgBody,date("Y-m-d H:i:s", strtotime('+1 minutes', time())),4,$recycle_num,1,1,0 );
                      }
                      $ree = RecycleGoods::where("rog_rid",$res)->update(['rog_dealtype'=>10]);
                  }
              }
                    //同步智配 京仓回收 end
                }

                //同步智配 回收 start
                if ($input['recycle_type'] == 2 || $input['recycle_type'] == 4) {
                    $p_id = OrderService::getOrderBy('order_num', $input['order_num'], ['p_id']);
                    if ($input['apply_type'] == 0) {
                        $refund_type = 1;
                    } elseif ($input['apply_type'] == 1) {
                        $refund_type = 3;
                    } else {
                        $refund_type = 2;
                    }
                    $dataState = OrderService::getDataState($input['goods_state']);
                    if(!$dataState){
                        $dataState['goods_state'] = 1;
                    }
                    $refund_price = $input['allprice'] ?? 0;
                    $p_id = PlatformService::getPtBy('id', $p_id, ['zp_id']);
                    if (!$p_id) {
                        return ['Data' => '', 'ErrorMessage' => '未匹配平台编号', 'ErrorCode' => ErrorInc::TRANSFER_FAILED];
                    }
                    $ware_id = $input['store_id'] ?? 4;
                    $order_num = SendGoodsService::getSendGoodBy(['order_num' => $input['order_num']], ['warehouse_num'], 'first');
                    if(!$order_num){
                        $order_num = $input['order_num'];
                    }
                    if($recycle['ro_reason'] == 1){
                        $is_barter = 2;
                    }else{
                        $is_barter = 1;
                    }
                    if($input['recycle_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' => $input['sys_num'], 'ser_num' => $recycle_num, 'user_name' => $input['send_name'], 'refund_type' => $refund_type, 'refund_price' => $refund_price, 'kd_number' => $recycle['courier_number'], 'refund_state' => $dataState['goods_state'],'recoveryReason'=>$recycle['lable_name'],'is_cfr'=>$recycle['is_cfr']];
                    $resa = CommonService::sysErpRetrieveInfor($orderInfo, $goods , true);
                    //$resa['code'] = 200;
                    $inputs['data']['zhipei'] = $orderInfo;
                    $inputs['data']['zhipeigood'] = $goods;
                    $inputs['return'] = $resa;
                    $data = json_encode($inputs);
                    CommonService::addLog('通知库发回收', $data, $recycle_num,'warehouse-recycle');
                    //                dump($res);
                    if ($resa['code'] != 200) {
                        return ['Data' => '', 'ErrorMessage' => '同步智配失败:' . $resa['data'], 'ErrorCode' => ErrorInc::TRANSFER_FAILED];
                        //                    DB::rollback();
                    }else{
                        $return = $resa['data'];
                        if(!is_array($return)) {
                            if ($resa['data'] == 1) {
                                $rea = RecycleOrders::where("ro_id", $res)->update(['ro_state' => 10, 'ro_dealtype' => 10]);
                                $ree = RecycleGoods::where("rog_rid", $res)->update(['rog_dealtype' => 10]);
                                self::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", $res)->update(['rog_dealtype' => 10]);
                                self::pushRecycle($order_num);
                            }
                            $rea = RecycleOrders::where("ro_id", $res)->update($poss);
                        }
                    }
                }
                //同步智配 end
            }


            $avtion = FunctionsService::getFunctionsBy('function_id', $input['Pri_id'], ['function_name'])??'新';
            $BaseController = new BaseController();
            $BaseController->insertingLog('锁定，', $input['sys_num'], "回收订单:" . $input['order_num'].",回收单号".$recycle_num, $avtion, $ip, $session['admin_acc']);//日志
//            DB::commit();
            $return['id'] = $res;
            $return['recycle_num'] = $recycle_num;
            return  ['Data' => $return,'ErrorMessage'=>'操作成功','ErrorCode'=>1];
            /*---------------------------------------添加回收单商品明细结束-------------------------------------*/
        }else{
//            DB::rollback();
            return  ['Data' => '','ErrorMessage'=>'操作失败ro','ErrorCode'=>ErrorInc::MYSQL_FAILED];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 同步推送回收消息
     * @param string ju_ordernum 订单单号
     * @retrun /multitype:array
     * @author dou 2022/2/17 9:41
     * |---------------------------------------------------------------------------------
    */
    public static function pushRecycle ( $order_num , $creater_id = 0 ){
        $msgBody['action'] = 'Ordersystem/noteList';
        $msgBody['pushtype'] = 5;
        $msgBody['time'] = date("H:i:s");
        $msgBody['s_type'] = 3;//'1' 新咨询 3：已回复;
        $msgBody['tittle'] = '您有新的回收通知';//新咨询
        $msgBody['msg'] = '单号：'.$order_num.'请前往查看';//'有新的咨询信息请及时处理';
        $BaseController = new BaseController();
        if($creater_id!=0) {
            $BaseController->pushRecord($msgBody, '', 6, '', $creater_id, 0, 0);
        }else{
            $group = self::getGroupIds();
            foreach ($group as $k=>$v){
                $BaseController->pushRecord($msgBody, '', 6, '', 0, 0, $v);
            }
        }
    }

    /**
     * 获取部门ＩＤ
     * @return multitype:
     * @author du 2021年7月29日上午11:27:01
     */
    public static function getGroupIds(){
        $result = DB::table('department')->whereRaw("FIND_IN_SET('80',bmmc_pids)")->pluck('id')->toarray();
        $groupIds = array_merge($result,[80,7]);

        return $groupIds;
    }

    /**|---------------------------------------------------------------------------------
     * @name 库房同步回收通知
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2022/2/17 10:10
     * |---------------------------------------------------------------------------------
    */
    public static function saveRetrieve($orderNO, $shippingCode, $shippingNO, $session = [],$recycle_num,$is_abnormal) {
        $ro_id = RecycleOrderService::getRecycleOrderBy('recycle_num',$recycle_num,['ro_id'],'first');
        if(!$ro_id){
            $data = RecycleOrderService::getRecycleOrderBy('ro_ordernum',$orderNO,['ro_id','courier_number']);
            if($data){
                foreach($data as $k => $v){
                    if($shippingNO == $v['courier_number']){
                        $ro_id = $v['ro_id'];
                    }
                }
            }else{
                return  ['Data' => '','ErrorMessage'=>'单号不存在','ErrorCode'=>ErrorInc::DATA_EMPTY];
            }
        }
        if($ro_id){
            DB::beginTransaction();
            if($is_abnormal == 1){
                $rea = RecycleOrders::where("ro_id", $ro_id)->update(['is_abnormal' => $is_abnormal]);
                $ree = true;
            }else {
                $rea = RecycleOrders::where("ro_id", $ro_id)->update(['ro_state' => 10, 'ro_dealtype' => 10]);
                $ree = RecycleGoods::where("rog_rid", $ro_id)->update(['rog_dealtype' => 10]);
            }
            if($rea && $ree){
                DB::commit();
                self::pushRecycle($orderNO);
                return ['Data' => '','ErrorMessage'=>'发货通知已接收','ErrorCode'=>1];
            }else{
                DB::rollback();
                return  ['Data' => '','ErrorMessage'=>'操作失败','ErrorCode'=>ErrorInc::MYSQL_FAILED];
            }
        }else{
            return  ['Data' => '','ErrorMessage'=>'单号不存在','ErrorCode'=>ErrorInc::DATA_EMPTY];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取列表信息
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/17 15:44
     * |---------------------------------------------------------------------------------
    */
    public static function getList ( $input , $session )
    {
        $page_size = $input['page_size'] ?? 10;
        $where = [];
        if(!in_array($input['state'], [0,1,5,10,15])){
            return ['Data' => [], 'ErrorMessage' => '参数错误state', 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }
        $status = self::getStatusWhere($input['state'] , $session);//获取状态查询条件
        if($status){
            foreach($status as $k => $v){
                $where[$k] = $v;
            }
        }
        if(isset($input['order_num'])){
            $where['ro_ordernum'] = $input['order_num'];
        }
        if(isset($input['lable_id'])){
            $where['lable_id'] = $input['lable_id'];
        }
        if(isset($input['is_cfr'])){
            $where['is_cfr'] = $input['is_cfr'];
        }
        if(isset($input['is_abnormal'])){
            $where['is_abnormal'] = $input['is_abnormal'];
        }
        if(isset($input['creact_id'])){
            $where['creact_id'] = $input['creact_id'];
        }
        if(isset($input['ro_type'])){
            $where['ro_type'] = $input['ro_type'];
        }
        if(isset($input['creatData'])){
            $input['creatData'][1] = date("Y-m-d", strtotime($input['creatData'][1] . " +1 day"));
            $where['ro_ctime_between'] = $input['creatData'];
        }
        $db = new RecycleOrders();
        if($where) {
            $where = CommonService::jointWhere($where);
            $db = $db->whereRaw($where);
        }
        $data['is_cfr'] = self::getCfrName(false);//cfr类型
        $data['is_abnormal'] = self::getAbnormalName(false);//商品异常类型
        $data['showcount'] = self::getStatusBar($session);//获取操作权限可展示订单状态栏
        if(isset($input['orderBy'])){
            foreach($input['orderBy'] as $k => $v){
                $db = $db->orderBy($k,$v);
            }
        }else{
            $db = $db->orderBy('ro_ctime','ASC');
        }
        if($input['is_excel']==1){
            DB::connection()->enableQueryLog();#开启执行日志
            $db = $db->Rightjoin('recycle_goods', 'recycle_goods.rog_rid', '=', 'recycle_orders.ro_id')->Leftjoin('orders','recycle_goods.rog_ordernum', '=', 'orders.order_num');;
            $paginate = $db->select('recycle_orders.*','recycle_goods.rog_goodsname','recycle_goods.rog_goodsname','recycle_goods.rog_goodsnum','recycle_goods.rog_dealtype','orders.p_id','recycle_goods.rog_id','is_cfr','is_abnormal','lable_name')->paginate($page_size);
        }else{
            $paginate = $db->paginate($page_size);
        }

//导出所需语句
        $data['sqls'] = DB::getQueryLog()[1];

        $data['recycletype'] = Self::getRecycleType();
        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
        $export = BmmcService::getTopButton('export','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $list = CommonService::dataToArray($paginate->items());
        if($list) {
            $data['list'] = self::jointListData($input, $session, $list, $all_button);//获取列表信息明细说明
        }else{
            $data['list'] = [];
        }
        $data['page'] = [
            'count' => $paginate->total(),
            'page' => $paginate->currentPage(),
            'page_size' => $page_size,
            'allPage' => $paginate->lastPage()
        ];
        return ['Data' => $data, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
    }

    /**|---------------------------------------------------------------------------------
     * @name 状态查询条件
     * @param array $session 操作人信息
     * @param string $status 查询状态
     * @retrun /multitype:array
     * @author dou 2021/9/17 15:46
     * |---------------------------------------------------------------------------------
    */
    public static function getStatusWhere ( $status , $session ){
        $where = [];
        if(in_array($status, [1,5,10,15])){
            $where['ro_dealtype'] = $status;
        }
        return $where;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取操作的状态栏信息
     * @param array $session 操作人信息
     * @param int $type 是否展示数量信息1是
     * @retrun /multitype:array
     * @author dou 2021/9/17 16:58
     * |---------------------------------------------------------------------------------
    */
    public static function getStatusBar ( $session , $type = ''){
        $bmmc_pids=BmmcService::searchPids($session['admin_groupnew']);
        if(in_array('104',$bmmc_pids)){
        }else{
            $waitNum = RecycleOrders::where('ro_dealtype',1)->count();
            $finishNum = RecycleOrders::where('ro_dealtype',5)->count();
            $showcount = [
                ['show_name'=>"全部",'shownum'=>'--','status'=>0],
                ['show_name'=>"未处理",'shownum'=>$waitNum,'status'=>1],
                ['show_name'=>"处理中",'shownum'=>$finishNum,'status'=>5],
                ['show_name'=>"已处理",'shownum'=>'--','status'=>10],
                ['show_name'=>"已驳回",'shownum'=>'--','status'=>15],
            ];
        }
        if( $type == '1'){
            foreach( $showcount as $k => $v ){
                $showcount[$k]['shownum'] = self::getStatusNum($v['status'],$session);
            }
        }
        return $showcount;
    }

    /**|---------------------------------------------------------------------------------
     * 拼接列表数据
     * @param string $session 用户信息
     * @param array $input 请求数据
     * @param array $list 订单数据
     * @param array $all_button 按钮信息
     * @retrun /multitype:array
     * @author dou 2021/9/17 18:33
     * |---------------------------------------------------------------------------------
    */
    public static function jointListData ( $input , $session , $list , $all_button ){
        $DealType = self::getDealType('',1);
        $SendType = self::getSendType('',1);
        $RecycleType = Self::getRecycleType('',1);
        $warehouse = CommonService::getWarehouse();
        $warehouse = array_column($warehouse, 'name' ,'type');
        /*----------------------------------------------获取订单门店信息开始----------------------------------------------*/
        $receiving_id = array_column($list, 'receiving_id');
        $send_id = array_column($list, 'send_id');
        if($send_id){
            $send_id = array_unique($send_id);
            $receiving_id = array_merge($receiving_id,$send_id);
        }
        $store = AdminsService::getAdmins(['id_searchin'=>$receiving_id],['id','company_name']);
        $store = array_column($store, 'company_name' ,'id');
        /*----------------------------------------------获取订单门店信息结束----------------------------------------------*/
        /*----------------------------------------------获取订单商品信息开始----------------------------------------------*/
        $recycle_num = array_column($list, 'recycle_num');
        $gooddetail = self::getRecycleGoods($recycle_num);
        $getCfrName = self::getCfrName();//cfr类型
        $getAbnormalName = self::getAbnormalName();//商品异常类型
        /*----------------------------------------------获取订单商品信息结束----------------------------------------------*/
        foreach($list as $k => $v){
            $list[$k]['cfrName'] = $getCfrName[$v['is_cfr']]??'未设定';
            $list[$k]['abnormalName'] = $getAbnormalName[$v['is_abnormal']]??'未设定';
            $list[$k]['dealtypeName'] = $DealType[$v['ro_dealtype']];
            $list[$k]['SendTypeName'] = $SendType[$v['send_type']];
            $list[$k]['RecycleTypeName'] = $RecycleType[$v['ro_type']];
            if($v['ro_type'] == 1){
                $list[$k]['storename'] = $store[$v['receiving_id']];
            }else{
                $list[$k]['storename'] = $warehouse[$v['receiving_id']];
            }
            if($v['send_id']>0){
                $list[$k]['sendstorename'] = $store[$v['send_id']];
            }
            $goodlist = $gooddetail[$v['recycle_num']];
            foreach($goodlist as $ka => $va){
                $goodlist[$ka]['dealtypeName'] = $DealType[$va['rog_dealtype']];
                $goodlist[$ka]['SendTypeName'] = $SendType[$va['rog_sendtype']];
            }
            $list[$k]['gooddetail'] = $goodlist;
            /*----------------------------------------------获取列表按钮开始--------------------------------------------*/
            $buttonData = [];
            $buttonData[] = "remark";
//            if(!$v['courier_number']){
            if($v['ro_dealtype'] == '1' || $v['ro_dealtype'] == '5'){
                $buttonData[] = "editCourier";
            }
            if($v['ro_type']==2){
                $buttonData[] = "editPrice";
            }
            if($v['ro_dealtype'] == '1'){
                $buttonData[] = "rejectedData,dealData";
            }if($v['ro_dealtype'] == '5'){
                $buttonData[] = "dealData,showPic";
            }if($v['ro_dealtype'] == '10'){
                $buttonData[] = "showPic";
            }if($v['ro_dealtype'] == '15'){
                $buttonData[] = "restoreData";
            }
            $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']??[];
            /*----------------------------------------------获取列表按钮结束--------------------------------------------*/
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 处理类型
     * @retrun /multitype:array
     * @author dou 2021/9/17 18:54
     * |---------------------------------------------------------------------------------
    */
    public static function getDealType ( $group = '' , $type = ''  ){
        if(!$group){
            $show = [];
        }else{
            $show = [];
        }
        $showdata = array(array("type"=>1,"name"=>'未处理'),array("type"=>5,"name"=>'处理中'),array("type"=>10,"name"=>'已处理'),array("type"=>15,"name"=>'已驳回'));
        if($show){
            foreach( $showdata as $k => $v ){
                if(in_array($k,$show)){
                    $data[] = $v;
                }
            }
        }else{
            $data = $showdata;
        }
        if( $type =='1'){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 发货类型
     * @retrun /multitype:array
     * @author dou 2021/9/17 19:21
     * |---------------------------------------------------------------------------------
    */
    public static function getSendType ( $group = '' , $type = '' ){
        if(!$group){
            $show = [];
        }else{
            $show = [];
        }
        $showdata = array(array("type"=>1,"name"=>'门店发货'),array("type"=>2,"name"=>'客户发货'));
        if($show){
            foreach( $showdata as $k => $v ){
                if(in_array($k,$show)){
                    $data[] = $v;
                }
            }
        }else{
            $data = $showdata;
        }
        if( $type =='1'){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 回收类型
     * @retrun /multitype:array
     * @author dou 2021/9/17 19:21
     * |---------------------------------------------------------------------------------
     */
    public static function getRecycleType ( $group = '' , $type = '' ){
        if(!$group){
            $show = [];
        }else{
            $show = [];
        }
        $showdata = array(array("type"=>1,"name"=>'门店回收'),array("type"=>2,"name"=>'库房回收'));
        if($show){
            foreach( $showdata as $k => $v ){
                if(in_array($k,$show)){
                    $data[] = $v;
                }
            }
        }else{
            $data = $showdata;
        }
        if( $type =='1'){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }


    /**|---------------------------------------------------------------------------------
     * @name cfr
     * @param string $type 展示类型
     * @retrun /multitype:array
     * @author dou 2022-08-19 019 下午 4:00:49
     * |---------------------------------------------------------------------------------
     */
    public static function getCfrName ( $type = true ){
        $data = [["type"=>1,"name"=>'CFR回收'],["type"=>2,"name"=>'非CFR回收']];//array(array("type"=>1,"name"=>'门店回收'),array("type"=>2,"name"=>'库房回收'));
        if( $type ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name abnormal
     * @param string $type 展示类型
     * @retrun /multitype:array
     * @author dou 2022-08-19 019 下午 4:00:49
     * |---------------------------------------------------------------------------------
     */
    public static function getAbnormalName ( $type = true ){
        $data = [["type"=>1,"name"=>'回收商品异常'],["type"=>2,"name"=>'回收商品正常']];//array(array("type"=>1,"name"=>'门店回收'),array("type"=>2,"name"=>'库房回收'));
        if( $type ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取回收单详细商品
     * @param array $rog_ronum 回收单号
     * @retrun /multitype:array
     * @author dou 2021/9/17 19:57
     * |---------------------------------------------------------------------------------
    */
    public static function getRecycleGoods ( $rog_ronum ){
        $db = new RecycleGoods();
        $list = CommonService::getMysqlData($db, ['rog_ronum_searchin'=>$rog_ronum]);
        if(is_array($list)){
            $list = CommonService::jointArrayKey($list, 'rog_ronum' , 2);
        }else{
            $list = CommonService::jointArrayKey($list, 'rog_ronum');
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 驳回/恢复回收单
     * @param array $input 请求参数
     * @param int $dealtype 修改状态
     * @param string $action 操作模块
     * @param string $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2021/9/18 15:49
     * |---------------------------------------------------------------------------------
    */
    public static function rejOrResData ( $input , $dealtype , $action , $session , $ip ){
        $checkKey=CommonService::checkKey(['id', 'remark','ro_sysnum','recycle_num','ro_type'],$input);
        if($checkKey['code']!=1){
            return ['Data' => [], 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
        }
        $poss['ro_dealtype'] = $dealtype;
        $posa['rog_dealtype'] = $dealtype;
        DB::beginTransaction(); //开启事务
        $rea = RecycleOrders::where("ro_id",$input['id'])->update($poss);
        $res = RecycleGoods::where("rog_rid",$input['id'])->update($posa);
        $BaseController = new BaseController();
        $not = CommonService::accMe($input['ro_sysnum'], '回收商品管理', $input['remark'], '', 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
        if($rea && $res && $not){

            //同步智配 start
            $courier_number = self::getRecycleOrderBy('recycle_num', $input['recycle_num'],['courier_number']);
            if($input['ro_type']==2 && $courier_number!=''){
                $res = \BlueCity\Data\Service\ZhiPei\OrderService::retrieveCancel($input['recycle_num']);
                $data = json_encode($input['recycle_num']).'---'.json_encode($res);
                CommonService::addLog('通知库发驳回回收', $data, $input['recycle_num'],'warehouse-recycle');
                if($res['code']!=200){
                    DB::rollback();
                    return ['Data' => [], 'ErrorMessage' => '同步失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];exit;
                }
            }
            //同步智配 end

            DB::commit();
            $BaseController->insertinglog($action,$input['recycle_num'],"回收单号：".$input['recycle_num'],"回收商品管理",$ip, $session['admin_acc']);
            return ['Data' => [], 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
        }else{
            DB::rollback();
            return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取回收单信息
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @param int $type 查询类型
     * @retrun /multitype:array
     * @author dou 2021/9/24 19:22
     * |---------------------------------------------------------------------------------
    */
    public static function getRecycleOrderBy ( $key , $value , $select = [] , $type ='get' ){
        $db = new RecycleOrders();
        if(in_array($key, ['ro_id','recycle_num'])) {
            $type = 'first';
        }
        if($type == 'first') {
            if (count($select) == 1) {
                $type = 'value';
            }
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单详情
     * @param string $order_num 订单单号
     * @retrun /multitype:array
     * @author dou 2021/9/24 19:16
     * |---------------------------------------------------------------------------------
    */
    public static function getDetailByOrder ( $order_num ){
        $list = Self::getRecycleOrderBy('ro_ordernum', $order_num);
        if($list) {
            $DealType = self::getDealType('', 1);
            $SendType = self::getSendType('', 1);
            $RecycleType = Self::getRecycleType('', 1);
            $warehouse = CommonService::getWarehouse();
            $warehouse = array_column($warehouse, 'name', 'type');
            /*----------------------------------------------获取订单门店信息开始----------------------------------------------*/
            $receiving_id = array_column($list, 'receiving_id');
            $send_id = array_column($list, 'send_id');
            if ($send_id) {
                $send_id = array_unique($send_id);
                $receiving_id = array_merge($receiving_id, $send_id);
            }
            $store = AdminsService::getAdmins(['id_searchin' => $receiving_id], ['id', 'company_name']);
            $store = array_column($store, 'company_name', 'id');
            /*----------------------------------------------获取订单门店信息结束----------------------------------------------*/
            /*----------------------------------------------获取订单商品信息开始----------------------------------------------*/
            $recycle_num = array_column($list, 'recycle_num');
            $gooddetail = self::getRecycleGoods($recycle_num);
            /*----------------------------------------------获取订单商品信息结束----------------------------------------------*/
            foreach ($list as $k => $v) {
                $list[$k]['dealtypeName'] = $DealType[$v['ro_dealtype']];
                $list[$k]['SendTypeName'] = $SendType[$v['send_type']];
                $list[$k]['RecycleTypeName'] = $RecycleType[$v['ro_type']];
                if ($v['ro_type'] == 1) {
                    $list[$k]['storename'] = $store[$v['receiving_id']];
                } else {
                    $list[$k]['storename'] = $warehouse[$v['receiving_id']];
                }
                if ($v['send_id'] > 0) {
                    $list[$k]['sendstorename'] = $store[$v['send_id']];
                }
                $goodlist = $gooddetail[$v['recycle_num']];
                foreach ($goodlist as $ka => $va) {
                    $goodlist[$ka]['dealtypeName'] = $DealType[$va['rog_dealtype']];
                    $goodlist[$ka]['SendTypeName'] = $SendType[$va['rog_sendtype']];
                }
                $list[$k]['gooddetail'] = $goodlist;
            }
        }
        return $list;
    }


}
