<?php

namespace app\admin\controller;

use app\admin\model\DataGroup as DataGroupModel;
use app\admin\model\GoodLog;
use app\admin\model\GoodStockInfo;
use app\admin\model\ProcessOrder;
use think\Exception;
use think\facade\Db;
use think\App;
use app\admin\model\ActionLog;
use think\facade\Validate;

//销售单退货(售前退货)
class Reorder extends Base
{

    public function __construct(App $app)
    {
        parent::__construct($app);

    }

    //创建退货单(售前退货单)
    public function create()
    {
        $ordeCode = isset($this->post['orderCode']) && $this->post['orderCode'] != '' ? trim($this->post['orderCode']) : "";
        if ($ordeCode == '') return json_show(1004, "参数orderCode 不能为空");

        $order = Db::name("sale")->where(["orderCode" => $ordeCode, "is_del" => 0])->findOrEmpty();
        if (empty($order)) return json_show(1005, "未找到订单数据");

        $retrun = Db::name("sale_return")
            ->where(["orderCode" => $ordeCode, "is_del" => 0, "status" => [1, 9, 8, 10, 11, 12]])
            ->count('id');
        if ($retrun > 0) return json_show(1005, "存在未完成退货订单数据");

        if ($order['order_type'] == 3 || $order['order_type'] == 4) {
            $goon = Db::name("good_zixun")
                ->where(["spuCode" => $order['good_code'], "is_del" => 0])
                ->findOrEmpty();
        } else {
            $goon = Db::name('good_platform')
                ->alias('a')
                ->join('good b', 'b.spuCode=a.spuCode', 'left')
                ->where(['a.skuCode' => $order['skuCode']])
                ->field("b.creater,b.createrid,b.supplierNo")
                ->findOrEmpty();
        }
        if (empty($goon)) return json_show(1005, "未找到商品数据");

        $userCommon = \app\admin\common\User::getIns();
        $tmp = $userCommon->handle('sInfo', ['code' => $goon['supplierNo']]);
        if (!isset($tmp['code']) || $tmp['code'] != 0) return json_show($tmp['code'], $tmp['message'], $tmp['data']);
        $supplier = $tmp['data'];
        if (empty($supplier)) return json_show(1005, "未找到商品供应商数据");
//        $supplier =Db::name("supplier")->where(["code"=>$goon['supplierNo']])->find();
//        if($supplier==false){
//            return json_show(1005,"未找到商品供应商数据");
//        }
//        $names = $userCommon->handle('getCodeAndName',['code'=>[$order['supplierNo'],$order['customer_code']]]);

        $errorCode = isset($this->post['errorCode']) && $this->post['errorCode'] != '' ? trim($this->post['errorCode']) : "";
        if ($errorCode == '') return json_show(1004, "参数errorCode 不能为空");

        $error = Db::name('result_info')
            ->field('id')
            ->where(["result_code" => $errorCode, "is_del" => 0])
            ->findOrEmpty();
        if (empty($error)) return json_show(1005, "未找到退货原因数据");

        $remark = isset($this->post['remark']) && $this->post['remark'] != '' ? trim($this->post['remark']) : "";
        $thnum = isset($this->post['thnum']) && $this->post['thnum'] != '' ? intval($this->post['thnum']) : "";
//        $token = isset($this->post['token'])&&$this->post['token']!='' ? trim($this->post['token']):"";
//        if($token==''){
//            return json_show(105,"参数token不能为空");
//        }
//        $user =GetUserInfo($token);
//        if(empty($user)||$user['code']!=0){
//            return json_show(1002,"申请人数据不存在");
//        }
        $is_addr = 0;
        $rm = $this->uid;//isset($user["data"]['id']) ?  $user["data"]['id'] : "";
        $ri = $this->uname;//isset($user["data"]['nickname']) ?  $user["data"]['nickname'] : "";
        $returnadr = isset($this->post['returnAddr']) && !empty($this->post['returnAddr']) ? $this->post['returnAddr'] : "";
        if ($returnadr != '') {
            $thnum = array_sum(array_column($returnadr, "return_num"));
            $is_addr = 1;
        }

        //如果全退,且没有成功的售后申请单 提示使用'订单撤销功能'
        if ($order['good_num'] == $thnum) {
            $temp = Db::name("sale_return")
                ->where(["orderCode" => $ordeCode, "is_del" => 0, "status" => 4])
                ->count('id');
            if ($temp == 0) return json_show(1004, '');
        }

        $returnCode = makeNo("RN");
        Db::startTrans();
        try {
            $date = date('Y-m-d H:i:s');
            $in = [
                "returnCode" => $returnCode,
                "orderCode" => $ordeCode,
                "good_code" => $order['good_code'],
                "good_name" => $order['good_name'],
                "apply_id" => $rm,
                "apply_name" => $ri,
                "cgderid" => $goon['createrid'],
                "cgder" => $goon['creater'],
                "person" => $supplier['person'] ?? '',
                "person_id" => $supplier['personid'] ?? 0,
                "error_code" => $errorCode,
                "num" => $thnum,
                "total_fee" => round($order['sale_price'] * $thnum, 2),
                "good_price" => $order['sale_price'],
                "platform_id" => $order['platform_id'],
                "remark" => $remark,
                "order_type" => $order['order_type'],
                "is_addr" => $is_addr,
                "status" => $order['is_stock'] == 1 ? (Db::name('order_out_child')->where(['is_del' => 0, 'orderCode' => $ordeCode])->value('id', 0) ? 11 : 4) : 1,//库存品未分仓选4,分仓选11,非库存品选1
                "is_del" => 0,
                "addtime" => $date,
                "updatetime" => $date,
                'supplierNo' => $goon['supplierNo'],
                'supplierName' => $supplier['name'],
                'companyNo' => $order['supplierNo'],
                'companyName' => $order['supplierName'],//$names['data'][$order['supplierNo']] ?? '',
                'customer_code' => $order['customer_code'],
                'customer_name' => $order['customerName'],//$names['data'][$order['customer_code']] ?? '',
            ];
            $create = Db::name("sale_return")->insertGetId($in);
            if ($create > 0) {
                $stn = ["order_code" => $returnCode, "status" => 0, "action_remark" => '', "action_type" => "create"];
                ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], $stn, "XSTHD", $in['status'], $in);
                $process = ["order_code" => $returnCode, "order_id" => $create, "order_status" => $in['status'], "order_type" => 'XSTHD', "before_status" => 0, 'holder_id' => $in['apply_id']];
                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);
                //维护台账信息
                Db::execute("UPDATE `wsm_standing_book` SET `returnGoodCode`=CONCAT(IFNULL(`returnGoodCode`,''),',{$returnCode}'),`updatetime`='" . $date . "' WHERE `orderCode`='{$ordeCode}'");

                //如果有退货地址,那么可能有发货单,可能有发货工单
//                if ($returnadr != "") {
//                    $inf = [];
//                    foreach ($returnadr as $val) {
//
//                        if ($val['return_num'] == 0) continue;//当退货数量为0时,跳过
//
//                        $temp = [];
//                        $addrinfo = Db::name("order_addr")->where(['id' => $val['id'], "orderCode" => $ordeCode])->findOrEmpty();
//                        if ($addrinfo == false) throw new Exception("地址信息未找到");
//
//                        $send = Db::name('order_out')->where([["addrid", "=", $val['id']]])->findOrEmpty();
//                        if ($send['status'] >= 2) throw new Exception("地址已发货");
//
//                        if ($order['is_stock'] == 1) {
//                            if ($addrinfo['receipt_quantity'] < $val['return_num']) throw new Exception("地址发货数量不足");
//
//                            $addrinfo['receipt_quantity'] -= $val['return_num'];
//                            $addrinfo['is_del'] = $addrinfo['receipt_quantity'] <= 0 ? 1 : 0;
//                            $addrinfo['updatetime'] = $date;
//                            $addrup = Db::name("order_addr")->save($addrinfo);
//                            if ($addrup == false) throw new Exception("地址发货数量更新失败");
//
//                            $out = Db::name("order_out")->where(["addrid" => $val['id']])->findOrEmpty();
//                            if ($out == false) throw new Exception("地址发货单数据未找到");
//
////                                if ($send!=false) {
//                            if ($out['status'] >= 2) throw new Exception("地址发货单已发货");
//
//                            if ($out['send_num'] < $val['return_num']) throw new Exception("地址发货单发货数量不足");
//
//                            $out['send_num'] -= $val['return_num'];
//                            $out['is_del'] = $out['send_num'] == 0 ? 1 : 0;
//                            $out['updatetime'] = $date;
//                            $outup = Db::name("order_out")->save($out);
//                            if ($outup == false) throw new Exception("地址发货单更新失败");
//
//
////                                    $ordersend = Db::name("order_send")->where(["outCode" => $out['outCode']])->find();
////                                    if ($ordersend['send_num'] < $val['return_num']) {
////                                        Db::rollback();
////                                        return json_show(1004, "发货单发货数量不足");
////                                    }
////                                    $ordersend['send_num'] -= $val['return_num'];
////                                    $ordersend['status'] = $ordersend['send_num'] <= 0 ? 0 : 1;
////                                    $ordersend['updatetime'] = $date;
////                                    $sendip = Db::name("order_send")->save($ordersend);
////                                    if ($sendip == false) {
////                                        Db::rollback();
////                                        return json_show(1004, "发货单更新失败");
////                                    }
//
////                                }
//                        }
//                        $temp['returnCode'] = $returnCode;
//                        $temp['orderCode'] = $ordeCode;
//                        $temp['outCode'] = isset($send['outCode']) ? $send['outCode'] : "";
//                        $temp['addrid'] = $val['id'];
//                        $temp['send_num'] = $addrinfo['receipt_quantity'];
//                        $temp['return_num'] = $val['return_num'];
//                        $temp['is_del'] = 0;
//                        $temp['addtime'] = $date;
//                        $temp['updatetime'] = $date;
//                        $inf[] = $temp;
//                    }
//                    $inadd = Db::name("sale_returnaddr")->insertAll($inf);
//                    if ($inadd == 0) throw new Exception("退货单新建失败");
//                }

                if ($in['status'] == 4 && $order['is_stock'] == 1) {

                    //未发货数量要减去发货单上的发货数量
                    $out_send_num = Db::name('order_out')
                        ->where(['is_del' => 0, 'orderCode' => $ordeCode, 'status' => [0, 1]])
                        ->sum('send_num');

                    $order['wsend_num'] -= $out_send_num;

                    if ($order['wsend_num'] < $thnum) throw new Exception("销售单未发货数量不足退货");

                    $lor = $order['status'];
                    $order['wsend_num'] -= $thnum;
                    $order['send_num'] += $thnum;
                    $order['status'] = $order['wsend_num'] == 0 ? 2 : ($order['send_num'] == 0 ? 0 : 1);
                    $order['send_status'] = $order['wsend_num'] == 0 ? 3 : ($order['send_num'] == 0 ? 1 : 2);
                    $order['th_num'] += $thnum;
                    if ($order['th_num'] == $order['send_num'] && $order['wsend_num'] == 0) {
                        $order['status'] = 3;
                    }
                    $order['th_fee'] += round($thnum * $order['sale_price'], 2);
                    $order['updatetime'] = $date;
                    $uap = Db::name("sale")->save($order);
                    if ($uap == false) throw new Exception('销售单订单更新失败');

                    ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], [
                        "order_code" => $order["orderCode"],//出库单号
                        "status" => $lor,//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "status"//新建create,编辑edit,更改状态status
                    ], "XSQRD", $order['status'], $order);

                    ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
                        "order_type" => 'XSQRD',
                        "order_code" => $order["orderCode"],//出库单号
                        "order_id" => $order["id"],
                        "order_status" => $order['status'], "before_status" => $lor
                    ]);

//                    $ordernum = Db::name("order_num")->where(['orderCode' => $ordeCode])->find();
//                    if ($ordernum == false) {
//                        Db::rollback();
//                        return json_show(1005, '未找到关联采购单');
//                    }
//                    $ordernum['send_num'] -= $thnum;
//                    $orderup = Db::name("order_num")->save($ordernum);
//                    if ($orderup == false) {
//                        Db::rollback();
//                        return json_show(1005, '关联数据更新失败');
//                    }
//                    $cgd = Db::name("purchease_order")->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])->find();
//                    if ($cgd == false) {
//                        Db::rollback();
//                        return json_show(1005, '未找到采购单数据');
//                    }
//                    $cgd['th_fee'] += round($cgd['good_price'] * $thnum, 2);
//                    $cgd['th_num'] += $thnum;
//                    $cgd['updatetime'] = date("Y-m-d H:i:s");
//                    $cgdup = Db::name("purchease_order")->save($cgd);
//                    if ($cgdup == false) {
//                        Db::rollback();
//                        return json_show(1005, '采购单数据更新失败');
//                    }
//                    if ($cgd['bkcode'] != "") {
//                        $bk = Db::name("purchease_order")->where(["bkcode" => $cgd['bkcode'], "order_type" => 1, "order_source" =>0, "is_del" => 0])
//                            ->find();
//                        if ($bk == false) {
//                            Db::rollback();
//                            return json_show(1005, '未找到备库单数据');
//                        }
//                        $orderbk = Db::name("order_bk")->where(['cgdNo' => $bk['cgdNo'], "is_del" => 0])->find();
//                        if ($orderbk == false) {
//                            Db::rollback();
//                            return json_show(1005, '备库单未完全入库');
//                        }
//                        $merge_num = Db::name("purchease_order")->where(["bkcode" => $bk['bkcode'], "order_type" =>
//                                1, "is_del" => 0])->where("order_source","<>",0)->field("sum(send_num)-sum(th_num) as num")
//                            ->find();
//
//                        $orderbk['balance_num'] = $orderbk['total_num'] - $merge_num['num'];
//                        $orderbk['merge_num'] = $merge_num['num'];
//                        $orderbk['updatetime'] = date("Y-m-d H:i:s");
//                        $orderbkup = Db::name("order_bk")->save($orderbk);
//                        if ($orderbkup == false) {
//                            Db::rollback();
//                            return json_show(1005, '备库单库存数据释放失败');
//                        }
//                    }

//                    $saleinfo = Db::name("sale_info")
//                        ->where([["orderCode", "=", $ordeCode], ["num", ">", 0]])
//                        ->select()
//                        ->toArray();
//                    if (empty($saleinfo)) {
//                        $ordernum = Db::name("order_num")->where(['orderCode' => $ordeCode])->findOrEmpty();
//                        if (empty($ordernum)) throw new Exception('未找到关联采购单');
//
//                        $cgd = Db::name("purchease_order")->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])->findOrEmpty();
//                        if (empty($cgd)) throw new Exception('未找到采购单数据');
//
//                        $bn = makeNo("BN");
//                        $stock = Db::name("good_stock")
//                            ->where(["spuCode" => $order['good_code'], 'wsm_code' => $cgd['wsm_code'], "is_del" => 0, "status" => 1])
//                            ->findOrEmpty();
//                        if ($stock == false) throw new Exception('商品库存数据未找到');
//
//                        $stock['usable_stock'] += $thnum;
//                        $stock['wait_out_stock'] -= $thnum;
//                        $stock['updatetime'] = $date;
//                        $st_up = Db::name("good_stock")->save($stock);
//                        if ($st_up == false) throw new Exception('可售商品入库失败');
//
//                        $yp = GoodStockInfo::AddBn($stock['id'], $bn, $thnum, $cgd['good_price']);
//                        if ($yp == false) throw new Exception('商品批次退货入库失败');
//
//                    } else {
//                        $tempnum = $thnum;
//                        foreach ($saleinfo as $va) {
//                            if ($tempnum == 0) break;
//                            $stock = Db::name("good_stock")->where(["spuCode" => $order['good_code'], 'id' => $va['stockid']])
//                                ->findOrEmpty();
//                            if ($stock == false) throw new Exception('商品库存数据未找到');
//
//                            if ($va['num'] >= $tempnum) {
//                                $tnm = $tempnum;
//                                $va['num'] -= $tempnum;
//                                $va['th_num'] += $tempnum;
//                                $tempnum = 0;
//                            } else {
//                                $tnm = $va['num'];
//                                $tempnum -= $va['num'];
//                                $va['th_num'] += $va['num'];
//                                $va['num'] = 0;
//                            }
//                            $stock['usable_stock'] += $tnm;
//                            $stock['wait_out_stock'] -= $tnm;
//                            $stock['updatetime'] = $date;
//                            $st_up = Db::name("good_stock")->save($stock);
//                            if ($st_up == false) throw new Exception('可售商品入库失败');
//
//                            $ps = GoodStockInfo::AddBn($va['stockid'], $va['bnCode'], $tnm);
//                            if ($ps == false) throw new Exception('商品批次退货入库失败');
//
//                            $ret = GoodStockInfo::ReturnBn($returnCode, $va['id'], $tnm);
//                            if ($ret == false) throw new Exception('商品批次退货入库失败');
//
//                            $va['updatetime'] = $date;
//                            $sal = Db::name("sale_info")->save($va);
//                            if ($sal == false) throw new Exception('商品批次退货入库失败');
//
//                            $good_data[] = ['good_log_code' => $returnCode, "stock_id" => $va['stockid'], "type" => 1, 'stock' => $thnum, "stock_name" => "usable_stock"];
//                            $good_data[] = ['good_log_code' => $returnCode, "stock_id" => $va['stockid'], "type" => 2, 'stock' => $thnum, "stock_name" => "wait_out_stock"];
//                            GoodLog::LogAdd(['id' => $this->uid, 'nickname' => $this->uname], $good_data, 'XSTHD');
//                        }
//                    }


//                    $data=[
//                        "orderCode"=>$ordeCode,
//                        "th_type"=>1,
//                        "th_num"=>$thnum,
//                        "th_fee"=>round($order['sale_price']*$thnum,2),
//                        "thCode"=>$returnCode,
//                        "spuCode"=>$order['good_code'],
//                        "good_name"=>$order['good_name'],
//                        "cat_id"=>$order['cat_id'],
//                        "apply_id"=>$rm,
//                        "apply_name"=>$ri,
//                        "addtime"=>$date,
//                        "status"=>1,
//                        "is_del"=>0
//                    ];
//                    $inse=Db::name("th_data")->insert($data);
//                    if($inse==false){
//                        Db::rollback();
//                        return json_show(1004,"退货单更新失败");
//                    }
                }

                Db::commit();
                return json_show(0, "退货单新建成功", ["returnCode" => $returnCode]);

            }
            Db::rollback();
            return json_show(1005, "退货单新建失败");
        } catch (\Exception $e) {
            Db::rollback();
            return json_show(1005, $e->getMessage());
        }
    }

    //退货单列表
    public function list()
    {
        $page = isset($this->post['page']) && $this->post['page'] !== "" ? intval($this->post['page']) : "1";
        $size = isset($this->post['size']) && $this->post['size'] !== "" ? intval($this->post['size']) : "10";
        $where = [['sr.is_del', "=", 0]];
        $bkcode = isset($this->post['returnCode']) && $this->post['returnCode'] != "" ? trim($this->post['returnCode']) : "";
        if ($bkcode != "") {
            $where[] = ['sr.returnCode', "like", "%{$bkcode}%"];
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "";
        if ($status !== "") {
            $where[] = ['sr.status', "=", $status];
        }
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] != "" ? trim($this->post['orderCode']) : "";
        if ($orderCode != "") {
            $where[] = ['sr.orderCode', "like", "%{$orderCode}%"];
        }
        $apply_name = isset($this->post['apply_name']) && $this->post['apply_name'] != "" ? trim($this->post['apply_name']) : "";
        if ($apply_name != "") {
            $where[] = ['sr.apply_name', "like", "%{$apply_name}%"];
        }
        $start = isset($this->post['start']) && $this->post['start'] != '' ? $this->post['start'] : "";
        if ($start !== "") {
            $where[] = ['sr.addtime', ">=", $start . ' 00:00:00'];
        }
        $end = isset($this->post['end']) && $this->post['end'] != '' ? $this->post['end'] : "";
        if ($end !== "") {
            $where[] = ['sr.addtime', "<=", $end . ' 23:59:59'];
        }
        //商品成本编码搜索
        $good_code = isset($this->post['good_code']) && $this->post['good_code'] != "" ? trim($this->post['good_code']) : "";
        if ($good_code != "") {
            $where[] = ['sr.good_code', "like", "%{$good_code}%"];
        }
        //商品上线编码搜索
        $skuCode = isset($this->post['skuCode']) && $this->post['skuCode'] != "" ? trim($this->post['skuCode']) : "";
        if ($skuCode != "") {
            $where[] = ['b.skuCode', "like", "%{$skuCode}%"];
        }

        $relaComNo = isset($this->post['relaComNo']) && $this->post['relaComNo'] != "" ? trim($this->post['relaComNo']) : "";
        if ($relaComNo != "") $where[] = ['sr.companyNo', '=', $relaComNo];

        $supplierNo = isset($this->post['supplierNo']) && $this->post['supplierNo'] != "" ? trim($this->post['supplierNo']) : "";
        if ($supplierNo !== "") $where[] = ['sr.supplierNo', "like", '%' . $supplierNo . '%'];

        $companyNo = isset($this->post['companyNo']) && $this->post['companyNo'] != "" ? trim($this->post['companyNo']) : "";
        if ($companyNo !== "") $where[] = ['sr.companyNo', "like", '%' . $companyNo . '%'];

        $customer_code = isset($this->post['customer_code']) && $this->post['customer_code'] != "" ? trim($this->post['customer_code']) : "";
        if ($customer_code !== "") $where[] = ['sr.customer_code', "like", '%' . $customer_code . '%'];

        $order_source = $order_source = isset($this->post['order_source']) && $this->post['order_source'] != "" ? trim($this->post['order_source']) : "";
        if ($order_source !== "") $where[] = ['b.order_source', "=", $order_source];


        $condition = [];
//        $role=$this->checkRole();
//        if(!empty($role['write']) && $this->uid!=""){
//            // $where[]=["sr.apply_id","in",$role['write']];
//            $condition .="sr.cgderid = {$this->uid} or sr.apply_id in (".implode(',',$role['write']).")";
//        }

        //只有level2的账号过滤数据权限
        if ($this->level == 2) {
            $role = $this->checkDataShare();
            $hand = resign_hand_user($this->uid, 0);
            if (!empty($role[DataGroupModel::$type_全部])) {
                $arr = array_unique(array_merge($hand, $role[DataGroupModel::$type_全部]));
//        	$uidim =implode(",",$hand);
//			$condition .= "sr.cgderid in ($uidim) or sr.person_id in ($uidim) or sr.apply_id in (" . implode(',',$arr) .
//			 ")";
                $condition[] = ["sr.apply_id", "in", $arr];
                $condition[] = ["sr.cgderid", "in", $hand];
                $condition[] = ["sr.person_id", "in", $hand];
            }
        }

        //供应商账号不允许看到库存品数据
        if ($this->level == 3) $where[] = ['b.is_stock', '<>', 1];
//        $role = $this->checkDataShare();
//        if (!empty($role[DataGroupModel::$type_全部])) $condition .= "sr.cgderid = {$this->uid} or sr.person_id = {$this->uid} or sr.apply_id in (" . implode(',', $role[DataGroupModel::$type_全部]) . ")";
        if (in_array($this->roleid, config('app.wsm_cgder_role'))) {
            $where[] = ["b.order_type", "=", 1];
        }
        $company_name = isset($this->post['company_name']) && $this->post['company_name'] !== "" ? trim($this->post['company_name']) : "";
        if ($company_name !== "") $where[] = ["sr.apply_id", 'in', get_company_item_user_by_name($company_name)];

//        $customer_code = trim($this->post['customer_code']??'');
//        $where[]=['b.customer_code', "like", "%{$customer_code}%"];

        $count = Db::name("sale_return")
            ->alias('sr')
            ->leftJoin("sale b", "b.orderCode=sr.orderCode AND b.is_del=0")
            ->leftJoin('result_info c', 'c.result_code=sr.error_code')
            ->where($where)
            ->where(function ($query) use ($condition) {
                $query->whereOr($condition);
            })
            ->count('sr.id');
        $total = ceil($count / $size);
        $page = $total >= $page ? $page : $total;
        $list = Db::name("sale_return")
            ->alias('sr')
            ->field('sr.*,b.skuCode,b.sale_price,b.good_num total_num,b.order_source,c.result error_msg')
            ->leftJoin("sale b", "b.orderCode=sr.orderCode AND b.is_del=0")
            ->leftJoin('result_info c', 'c.result_code=sr.error_code')
            ->where($where)
            ->where(function ($query) use ($condition) {
                $query->whereOr($condition);
            })
            ->order("sr.addtime desc")
            ->page($page, $size)
            ->select()
            ->toArray();
        // echo Db::name("sale_return")->getLastSql();

        $all_createrid = array_column($list, 'apply_id');
        $item = get_company_name_by_uid($all_createrid);
//		 $userCommon = \app\admin\common\User::getIns();
//        $names = $userCommon->handle('getCodeAndName',['code'=>array_merge(array_column($list,'supplierNo'),array_column($list,'customer_code'))]);

        //校验是否开通了供应商账号
        $supp_account = checkHasAccountBySupplierNos(array_unique(array_column($list,'supplierNo')));

        $data = [];
        foreach ($list as $value) {
//            $value['error_msg']='';
//            if($value['error_code']!=''){
//                $error = Db::name("result_info")->where(["result_code"=>$value['error_code']])->find();
//                $value['error_msg']= isset($error['result'])?$error['result']:"";
//            }
//            $order =Db::name("sale")->where(["orderCode"=>$value['orderCode'],"is_del"=>0])->find();
//            $value['sale_price'] = isset($order['sale_price']) ?$order['sale_price']:0;
            $value['return_total'] = $value['sale_price'] * $value['num'];
//            $value['total_num'] =$order['good_num'] ;
            $value['company_name'] = $item[$value['apply_id']] ?? '';
//			$value['supplierName'] = $names['data'][$value['supplierNo']] ?? '';//isset($wsm['company']) ? $wsm['company'] : "";
//            $value['customerName'] = $names['data'][$value['customer_code']] ?? '';//isset($wsm['company']) ? $wsm['company'] : "";
            //是否具有编辑权限
//            $value['is_allow_update'] = 0;
//            if (in_array($this->roleid, [1, 33]) || in_array($value['apply_id'], $role[DataGroupModel::$type_可编辑])) $value['is_allow_update'] = 1;
            $value['has_account'] = (int)isset($supp_account[$value['supplierNo']]);

            $data[] = $value;
        }
        return json_show(0, "获取成功", ["count" => $count, 'list' => $data]);
    }

    public function info()
    {
        $code = isset($this->post['returnCode']) && $this->post['returnCode'] !== "" ? trim($this->post['returnCode']) : "";
        if ($code == "") {
            return json_show(1004, "参数returnCode不能为空");
        }
        $info = Db::name("sale_return")->where(["returnCode" => $code, "is_del" => 0])->find();
        if (empty($info)) {
            return json_show(1004, "未找到退货数据");
        }
        $orderinfo = Db::name("sale")->where(["orderCode" => $info["orderCode"]])->find();
        if ($orderinfo['order_type'] == 3 || $orderinfo['order_type'] == 4) {
            $goon = Db::name("good_zixun")
                ->field('cat_id,0 is_stock')
                ->where(["spuCode" => $orderinfo['good_code'], "is_del" => 0])
                ->findOrEmpty();

        } else {
            $goon = Db::name('good_platform')
                ->field('b.cat_id,b.is_stock')
                ->alias('a')
                ->leftJoin('good b', 'b.spuCode=a.spuCode')
                ->where(['a.skuCode' => $orderinfo['skuCode']])
                ->findOrEmpty();
        }
        if ($goon == false) {
            return json_show(1003, "未找到商品数据");
        }
        $int = isset($goon['cat_id']) && $goon['cat_id'] != 0 ? made($goon['cat_id']) : [];
        $info['is_stock'] = isset($goon['is_stock']) ? $goon['is_stock'] : '0';
        $info['good_code'] = isset($orderinfo['good_code']) ? $orderinfo['good_code'] : '';
        $info['send_type'] = isset($orderinfo['send_type']) ? $orderinfo['send_type'] : '';
        $info['skuCode'] = isset($orderinfo['skuCode']) ? $orderinfo['skuCode'] : '';
        $info['good_name'] = isset($orderinfo['good_name']) ? $orderinfo['good_name'] : '';
        $info['good_num'] = isset($orderinfo['good_num']) ? $orderinfo['good_num'] : '';
        $info['sale_price'] = isset($orderinfo['sale_price']) ? $orderinfo['sale_price'] : '0';
        $info['origin_price'] = isset($orderinfo['origin_price']) ? $orderinfo['origin_price'] : '0';
        $info['return_total'] = $info['sale_price'] * $info['num'];
        $info['send_num'] = isset($orderinfo['send_num']) ? $orderinfo['send_num'] : '0';
        $info['wsend_num'] = isset($orderinfo['wsend_num']) ? $orderinfo['wsend_num'] : '0';
        $info['send_status'] = isset($orderinfo['send_status']) ? $orderinfo['send_status'] : '';
        $info['total_price'] = isset($orderinfo['total_price']) ? $orderinfo['total_price'] : '0';
        $info['post_fee'] = isset($orderinfo['post_fee']) ? $orderinfo['post_fee'] : '0';
//       $info['customer_code'] = isset($orderinfo['customer_code'])?$orderinfo['customer_code']:'';

//        $userCommon = \app\admin\common\User::getIns();
        if ($info['return_wsm'] != "") {
            $wsmcode = Db::name("warehouse_info")
                ->alias("a")
//                ->leftJoin("supplier b","a.supplierNo=b.code")
                ->where(["a.wsm_code" => $info['return_wsm']])
                ->field("a.name as wsm_name,a.supplierNo,a.supplierName")
                ->findOrEmpty();
//            $tmp = $userCommon->handle('getCodeAndName', ['code' => [
//            $orderinfo['supplierNo'],
//            $orderinfo['customer_code'],
//                $wsmcode['supplierNo']??'',
//            ]]);
            $info['wsm_name'] = isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name'] : "";
            $info['wsm_supplier'] = $wsmcode['supplierName'];//isset($wsmcode['name']) ? $wsmcode['name']:"";
            $info['wsm_supplierNo'] = $wsmcode['supplierNo'] ?? '';//isset($wsmcode['code']) ? $wsmcode['code']:"";
        }


//        if(!empty($wsmcode['supplierNo'])){
//            $info['wsm_supplier'] =$tmp['data'][$wsmcode['supplierNo']]??'';//isset($wsmcode['name']) ? $wsmcode['name']:"";
//            $info['wsm_supplierNo'] =$wsmcode['supplierNo']??'';//isset($wsmcode['code']) ? $wsmcode['code']:"";
//        }

//        $info['customer_name']='';
//        if(isset($orderinfo['customer_code'])&&$orderinfo['customer_code']!=''){
//            $customerinfo = Db::name("customer_info")->where(['companyNo'=>$orderinfo['customer_code']])->find();
//            $info['customer_name'] = $tmp['data'][$orderinfo['customer_code']]??'';//isset($customerinfo['companyName']) ? $customerinfo['companyName']:"";
//        }
//        $info['supplierNo'] = isset($orderinfo['supplierNo'])?$orderinfo['supplierNo']:'';
//        $info['supplier_name']='';
//        if(isset($orderinfo['supplierNo'])&&$orderinfo['supplierNo']!=''){
////            $customerinfo = Db::name("business")->where(['companyNo'=>$orderinfo['supplierNo']])->find();
////            $info['supplier_name'] = isset($customerinfo['company']) ? $customerinfo['company']:"";
//            $info['supplier_name'] = $tmp['data'][$orderinfo['supplierNo']] ?? '';
//
//        }
        $info['platform_name'] = '';
        $info['platform_id'] = $orderinfo['platform_id'];
        if ($orderinfo['platform_id'] != 0) {
            $plat = Db::name("platform")->field('platform_name')->where(['id' => $orderinfo['platform_id']])->find();
            $info['platform_name'] = isset($plat['platform_name']) ? $plat['platform_name'] : "";
        }
        $info['cgd_wsend'] = "";
        $info['cgd_send'] = "";
        $info['cgd_total'] = "";
        if ($orderinfo['order_type'] == 2) {
            $cgd = Db::name("purchease_order")->where(["bkcode" => $info["orderCode"], "order_type" => 2])->find();
            $info['cgd_wsend'] = isset($cgd['wsend_num']) ? $cgd['wsend_num'] : 0;
            $info['cgd_send'] = isset($cgd['send_num']) ? $cgd['send_num'] : 0;
            $info['cgd_total'] = isset($cgd['good_num']) ? $cgd['good_num'] : 0;
        }
        $info['error_msg'] = '';
        if ($info['error_code'] != '') {
            $error = Db::name("result_info")->where(["result_code" => $info['error_code']])->find();
            $info['error_msg'] = isset($error['result']) ? $error['result'] : "";
        }

        $wsm_return = Db::name("sale_returninfo")->where(["returnCode" => $info["returnCode"], "is_del" => 0])->select()->toArray();

        $all_wsm_code = array_column($wsm_return, 'wsm_code');
        $all_wsmcode_info = Db::name("warehouse_info")
            ->where(["wsm_code" => $all_wsm_code])
            ->column("name,supplierNo,supplierName", 'wsm_code');

//        $userCommon = \app\admin\common\User::getIns();
//        $all_supplier_name = $userCommon->handle('getCodeAndName', ['code' => array_unique(array_column($all_wsmcode_info, 'supplierNo'))]);
        $wsm = [];
        if (!empty($wsm_return)) {

            foreach ($wsm_return as $value) {
                $value['wsm_name'] = "";
                $value['wsm_supplier'] = "";
                $value['wsm_supplierNo'] = "";
                if ($value['wsm_code'] != "") {
//                    $wsmcode = Db::name("warehouse_info")
//                        ->alias("a")
////                        ->leftJoin("supplier b","a.supplierNo=b.code")
//                        ->where(["a.wsm_code"=>$value['wsm_code']])
//                        ->field("a.name as wsm_name,b.name,b.code")
//                        ->find();
                    $value['wsm_name'] = $all_wsmcode_info[$value['wsm_code']]['name'] ?? '';//isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name']:"";
                    $value['wsm_supplier'] = $all_wsmcode_info[$value['wsm_code']]['supplierName'] ?? '';//isset($wsmcode['name']) ? $wsmcode['name']:"";
                    $value['wsm_supplierNo'] = $all_wsmcode_info[$value['wsm_code']]['supplierNo'] ?? '';//isset($wsmcode['code']) ? $wsmcode['code']:"";
                }
                $orderwsm = Db::name("sale_info")->where(["orderCode" => $info["orderCode"], "wsm_code" => $value["wsm_code"]])->find();
                $value["wsm_total"] = isset($orderwsm["num"]) ? $orderwsm["num"] : 0;
                $send = Db::name("order_out")->where(["wsm_code" => $value['wsm_code'], 'orderCode' => $info['orderCode']])->sum("send_num");
                $value['wsm_send'] = $send ?? 0;
                $value['wsm_wsend'] = $value['wsm_total'] - $value['wsm_send'];
                $wsm[] = $value;
            }
        }
        $info['wsminfo'] = $wsm;
        $addr = Db::name("sale_returnaddr")
            ->alias('a')
            ->field('a.*,b.addr,b.addr_code,b.contactor,b.mobile,b.post_fee,b.arrive_time,b.customer_code,b.receipt_quantity,b.orderCode')
            ->leftJoin('order_addr b', 'b.id=a.addrid')
            ->where(["a.returnCode" => $info["returnCode"], "a.is_del" => 0])
            ->select()
            ->toArray();
        $addrinfo = [];
        if (!empty($addr)) {

            $userCommon = \app\admin\common\User::getIns();
            $customer_name = $userCommon->handle('getCodeAndName', ['code' => array_unique(array_column($addr, 'customer_code'))]);

            foreach ($addr as $value) {
//                $addrlist = Db::name("order_addr")->where(["id"=>$value["addrid"]])->find();
                $value['addr'] = isset($value['addr']) ? $value['addr'] : "";
                $value['addr_code'] = isset($value['addr_code']) ? $value['addr_code'] : "";
                $value['contactor'] = isset($value['contactor']) ? $value['contactor'] : "";
                $value['mobile'] = isset($value['mobile']) ? $value['mobile'] : "";
                $value['post_fee'] = isset($value['post_fee']) ? $value['post_fee'] : "";
                $value['addive_time'] = isset($value['addive_time']) ? $value['addive_time'] : "";
                $value['customer_code'] = isset($value['customer_code']) ? $value['customer_code'] : "";
                $value['receipt_quantity'] = isset($value['receipt_quantity']) ? $value['receipt_quantity'] : "";
                $send = Db::name("order_out")->where(['addrid' => $value['addrid'], 'orderCode' => $value['orderCode'], "is_del" => 0])->where("status", ">=", 2)->sum("send_num");
                $value['addr_send'] = $send ?? 0;
                $value['addr_wsend'] = $value['receipt_quantity'] - $value['addr_send'];
//                $customer = Db::name("customer_info")->where(['companyNo'=>$addrlist['customer_code']])->find();
                $value['customer_name'] = $customer_name['data'][$value['customer_code']] ?? '';//isset($customer['companyName']) ? $customer['companyName']:"";
                $addrinfo[] = $value;
            }

        }
        $info['addrinfo'] = $addrinfo;
        $info['can'] = $int;
        return json_show(0, "获取成功", $info);
    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete()
    {
        $code = isset($this->post['returnCode']) && $this->post['returnCode'] !== "" ? trim($this->post['returnCode']) : "";
        if ($code == "") {
            return json_show(1004, "参数returnCode不能为空");
        }
        $info = Db::name("sale_return")->where(["returnCode" => $code, "is_del" => 0])->find();
        if (empty($info)) {
            return json_show(1004, "未找到退货数据");
        }
        $info["is_del"] = 1;
        $info["updatetime"] = date("Y-m-d H:i:s");
        $del = Db::name("sale_return")->save($info);
        if ($del) {
            $ste = ["order_code" => $code, "status" => 0, "action_remark" => '', "action_type" => "delete"];
            ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], $ste, "XSTHD", 0, $ste);
            $process = ["order_code" => $code, "order_id" => $info['id'], "order_status" => 0, "order_type" => "XSTHD"];
            ProcessOrder::workdel($process);
            return json_show(0, "删除成功");
        } else {
            return json_show(1004, "删除失败");
        }
    }

    /**审核
     * 1待业务审批
     * 2待专员审批(该节点废除)
     * 3待主管审批(该节点废除)
     * 4退货完成
     * 5业务驳回
     * 6采购驳回(该节点废除)
     * 7专员审批不通过(该节点废除)
     * 9待供应商审核
     * 8供应商已驳回待采购审核
     * 10业务公司修改待供应商确认
     * 11待设置退货工单
     * 12待库管发货
     */
    public function exam()
    {
        $param = $this->request->only(['returnCode', 'status', 'remark' => '', 'return_wsm' => ''], 'post', 'trim');

        $val = Validate::rule([
            'returnCode|退货单编号' => 'require',
            'status|状态' => 'require|in:5,9,8,10,4,11',
            'remark|备注' => 'requireIf:status,5|requireIf:status,8|requireIf:status,10',
        ]);

        if ($val->check($param) == false) return json_show(1004, $val->getError());

        $code = $param['returnCode'];
        $status = $param['status'];
        $remark = $param['remark'];

//        $code =  isset($this->post['returnCode']) && $this->post['returnCode'] !=="" ? trim($this->post['returnCode']):"";
//        if($code==""){
//            return json_show(1004,"参数returnCode不能为空");
//        }
        $info = Db::name("sale_return")->where(["returnCode" => $code, "is_del" => 0])->findOrEmpty();
        if (empty($info)) return json_show(1004, "未找到退货数据");

        switch ($info['status']) {
            case 1:
                if (in_array($param['status'], [5, 9]) == false) return json_show(1004, '选项错误');
                break;
            case 9:
                if (in_array($param['status'], [4, 8]) == false) return json_show(1004, '选项错误');
                break;
            case 8:
                if (in_array($param['status'], [11, 10]) == false) return json_show(1004, '选项错误');
//                if ($param['status'] == 4) {
//                    if ($param['return_wsm'] == '') return json_show(1004, '仓库编码不能为空');
//                    $tmp = Db::name("warehouse_info")
//                        ->field('id')
//                        ->where(['wsm_code' => $param['return_wsm']])
//                        ->findOrEmpty();
//                    if (empty($tmp)) return json_show(1004, '未找到仓库数据');
//                    else $info['return_wsm'] = $param['return_wsm'];
//
//                }
                break;
            case 10:
                if (in_array($param['status'], [4, 8]) == false) return json_show(1004, '选项错误');
                break;
        }

        //当处于以下节点时,level2账号必须是供应商负责人操作,level3账号不做限制
        if (in_array($info['status'], [9, 10]) && ($this->level == 2) && ($this->uid != $info['person_id'])) return json_show(1004, '您不是供应商负责人,此时无权操作');

        if ($param['status'] == 10) $info['loop_total'] += 1;//只要走到节点10(业务公司修改,待供应商确认),就增加次数

//        $status =  isset($this->post['status']) && $this->post['status'] !=="" ? intval($this->post['status']):"";
//        if($status===""){
//            return json_show(1004,"参数status不能为空");
//        }
//        $remark =  isset($this->post['remark']) && $this->post['remark'] !="" ? trim($this->post['remark']) :"";
        $var = $info['status'];
        $orderinfo = Db::name("sale")->where(["orderCode" => $info["orderCode"]])->findOrEmpty();
        if (empty($orderinfo)) return json_show(1004, "未找到订单数据");

//        if ($status == 4) {
//            if ($info['is_addr'] == 1) {
//                $addr = Db::name("sale_returnaddr")
//                    ->where(['returnCode' => $info['returnCode'], "is_del" => 0])
//                    ->select()
//                    ->toArray();
//                if (empty($addr)) return json_show(1004, "未找到发货单地址数据");
//
//            }
//        }
//        if($status==3){
//            $is_th =isset($this->post['is_th'])&&$this->post['is_th']!=="" ? intval($this->post['is_th']):"";
//            if($is_th===""){
//                return json_show(1004,"参数is_th不能为空");
//            }
//            $return_wsm =isset($this->post['return_wsm'])&&$this->post['return_wsm']!=="" ? trim($this->post['return_wsm']):"";
//            if($is_th==0){
//                if($return_wsm===""){
//                    return json_show(1004,"参数return_wsm 不能为空");
//                }
//                $wsmcode = Db::name("warehouse_info")->where(['wsm_code'=>$return_wsm])->find();
//                if($wsmcode==false){
//                    return json_show(1004,"为找到仓库数据");
//                }
//            }
//            $info['return_wsm'] =$return_wsm ;
//            $info['is_th'] =$is_th ;
//        }

        if ( in_array($info['status'],[9,10]) && $param['status'] == 4) $info['is_th'] = 1;//除了8-11-12-4之外,其余9-4和10-4都属于供应商同意退货

        Db::startTrans();
        try {

            $date = date("Y-m-d H:i:s");

            $userCommon = \app\admin\common\User::getIns();

            $temp = $info['status'];
            $info['status'] = $status;
            $remark != "" ? $info['remark'] = $remark : "";
            $info["updatetime"] = $date;
            $up = Db::name("sale_return")->save($info);
            if ($up) {

                //如果是节点2(待专员审核),要将待办数据推给供应商负责人
                if ($info['status'] == 2) $process = ["order_code" => $code, "order_id" => $info['id'], "order_status" => $status, "order_type" => "XSTHD", 'before_status' => $temp, 'wait_id' => $info['person_id'], 'wait_name' => $info['person']];
                else $process = ["order_code" => $code, "order_id" => $info['id'], "order_status" => $status, "order_type" => "XSTHD", 'before_status' => $temp, 'holder_id' => $info['apply_id']];

                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);

                $ste = ["order_code" => $code, "status" => $temp, "action_remark" => '', "action_type" => "status"];
                ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], $ste, "XSTHD", $status, $info);
                if ($status == 4) {
//                    if ($info['is_addr'] == 1) {
//                        if (isset($addr) && !empty($addr)) {
//                            foreach ($addr as $value) {
//                                $addrinfo = Db::name("order_addr")
//                                    ->where(['id' => $value['addrid'], "is_del" => 0])
//                                    ->findOrEmpty();
//                                if (empty($addrinfo)) throw new Exception("地址数据未找到");
//
//                                if ($addrinfo['receipt_quantity'] < $value['return_num']) throw new Exception("地址发货数量不足");
//
//                                $addrinfo['receipt_quantity'] -= $value['return_num'];
//                                $addrinfo['is_del'] = $addrinfo['receipt_quantity'] <= 0 ? 1 : 0;
//                                $addrinfo['updatetime'] = $date;
//                                $addrup = Db::name("order_addr")->save($addrinfo);
//                                if ($addrup == false) throw new Exception('地址发货数量更新失败');
//
//                                if ($value['outCode'] != "") {
//                                    $out = Db::name("order_out")->where(["outCode" => $value['outCode']])->findOrEmpty();
//                                    if (empty($out)) throw new Exception('地址发货单数据未找到');
//
//                                    if ($out['status'] >= 2) throw new Exception('地址发货单已发货');
//
//                                    if ($out['send_num'] < $value['return_num']) throw new Exception('地址发货单发货数量不足');
//
//                                    $out['send_num'] -= $value['return_num'];
//                                    $out['is_del'] = $out['send_num'] <= 0 ? 1 : 0;
//                                    $out['updatetime'] = $date;
//                                    $outup = Db::name("order_out")->save($out);
//                                    if ($outup == false) throw new Exception('地址发货单更新失败');
//
//                                }
//                            }
//                        }
//                    }

                    if ($orderinfo['wsend_num'] < $info['num']) throw new Exception('销售单未发货数量不足退货');

                    $lor = $orderinfo['status'];
                    $orderinfo['wsend_num'] -= $info['num'];
                    $orderinfo['send_num'] += $info['num'];
                    $orderinfo['status'] = $orderinfo['wsend_num'] == 0 ? 2 : ($orderinfo['send_num'] == 0 ? 0 : 1);
                    $orderinfo['send_status'] = $orderinfo['wsend_num'] == 0 ? 3 : ($orderinfo['send_num'] == 0 ? 1 : 2);
                    if ($orderinfo['is_stock'] == 1) {
                        $orderinfo['th_num'] += $info['num'];
                        if ($orderinfo['th_num'] == $orderinfo['send_num'] && $orderinfo['wsend_num'] == 0) {
                            $orderinfo['status'] = 3;
                        }
                        $orderinfo['th_fee'] += round($info['num'] * $orderinfo['sale_price'], 2);
                        $orderinfo['updatetime'] = $date;
                        $uap = Db::name("sale")->save($orderinfo);
                        if ($uap == false) throw new Exception('销售单订单更新失败');

                    } else {
                        if ($info['is_th'] == 1) {
                            $orderinfo['th_num'] += $info['num'];
                            if ($orderinfo['th_num'] == $orderinfo['send_num'] && $orderinfo['wsend_num'] == 0) {
                                $orderinfo['status'] = 3;
                            }
                            $orderinfo['th_fee'] += round($info['num'] * $orderinfo['sale_price'], 2);
                            $orderinfo['updatetime'] = $date;
                            $uap = Db::name("sale")->save($orderinfo);
                            if ($uap == false) throw new Exception('销售单订单更新失败');

                            $ordernum = Db::name("order_num")
                                ->where(['orderCode' => $orderinfo['orderCode']])
                                ->findOrEmpty();
                            if (empty($ordernum)) throw new Exception('未找到关联采购单');

                            $ordernum['send_num'] -= $info['num'];
                            $orderup = Db::name("order_num")->save($ordernum);
                            if ($orderup == false) throw new Exception('关联数据更新失败');

                            $cgd = Db::name("purchease_order")
                                ->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])
                                ->findOrEmpty();
                            if ($cgd == false) throw new Exception('未找到采购单数据');

                            if ($info['is_all'] == 1 && $cgd['send_status'] != 1) throw new Exception('采购单已入库无法全部退货');

                            $lor = $cgd['status'];
                            if ($cgd['wsend_num'] < $info['num']) {
                                $cgd['send_num'] += $cgd['wsend_num'] == 0 ? 0 : ($info['num'] - $cgd['wsend_num']);
                                $cgd['wsend_num'] = 0;
                            } else {
                                $cgd['wsend_num'] -= $info['num'];
                                $cgd['send_num'] += $info['num'];
                            }
                            $cgd['status'] = $cgd['wsend_num'] == 0 ? 2 : ($cgd['send_num'] == 0 ? 0 : 1);
                            $cgd['send_status'] = $cgd['wsend_num'] == 0 ? 3 : ($cgd['send_num'] == 0 ? 1 : 2);
                            $cgd['th_num'] += $info['num'];
                            if ($cgd['th_num'] == $cgd['send_num'] && $cgd['wsend_num'] == 0) {
                                $cgd['status'] = 4;
                            }
                            $cgd['th_fee'] += round($info['num'] * $cgd['good_price'], 2);
                            $cgd['updatetime'] = $date;
                            $cgdup = Db::name("purchease_order")->save($cgd);
                            if ($cgdup == false) throw new Exception('采购单数据更新失败');

                            $stock = Db::name("good_stock")
                                ->where(['is_del' => 0, "spuCode" => $info['good_code'], 'wsm_code' => $cgd['wsm_code']])
                                ->findOrEmpty();
                            if (empty($stock)) throw new Exception('商品仓库未找到');

                            if ($stock['wait_in_stock'] < $info['num']) {
                                $stock['wait_in_stock'] = 0;
                                if ($stock['usable_stock'] > $info['num'] - $stock['wait_in_stock']) {
                                    $stock['usable_stock'] -= $info['num'] - $stock['wait_in_stock'];
                                } else {
                                    $stock['usable_stock'] = 0;
                                    $stock['wait_out_stock'] -= $info['num'] - $stock['wait_in_stock'] - $stock['usable_stock'];
                                }

                                $stock['total_stock'] = $stock['usable_stock'] + $stock['wait_out_stock'];
                            } else {
                                $stock['wait_in_stock'] -= $info['num'];
                            }
                            $stock['updatetime'] = $date;
                            $st_up = Db::name("good_stock")->save($stock);
                            if ($st_up == false) throw new Exception('可售商品入库失败');


                        } else {
                            $orderinfo['th_num'] += $info['num'];
                            if ($orderinfo['th_num'] == $orderinfo['send_num'] && $orderinfo['wsend_num'] == 0) {
                                $orderinfo['status'] = 3;
                            }
                            $orderinfo['th_fee'] += round($info['num'] * $orderinfo['sale_price'], 2);
                            $orderinfo['updatetime'] = $date;
                            $uap = Db::name("sale")->save($orderinfo);
                            if ($uap == false) throw new Exception('销售单订单更新失败');

                            $ordernum = Db::name("order_num")
                                ->where(['orderCode' => $orderinfo['orderCode']])
                                ->findOrEmpty();
                            if (empty($ordernum)) throw new Exception('未找到关联采购单');

                            $ordernum['send_num'] -= $info['num'];
                            $ordernum['wsend_num'] = $info['num'];
                            $orderup = Db::name("order_num")->save($ordernum);
                            if ($orderup == false) throw new Exception('关联数据更新失败');

                            $cgd = Db::name("purchease_order")
                                ->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])
                                ->findOrEmpty();
                            if (empty($cgd)) throw new Exception('未找到采购单数据');

                            $stock = Db::name("good_stock")
                                ->where(['is_del' => 0, "spuCode" => $orderinfo['good_code'], 'wsm_code' => $cgd['wsm_code']])
                                ->findOrEmpty();
                            if (empty($stock)) throw new Exception('商品仓库未找到');

                            if ($info['is_all'] == 1) {
                                if ($stock['wait_in_stock'] < $info['num']) throw new Exception('商品可用库存不足退回数量');
                                else $stock['wait_in_stock'] -= $info['num'];

                            } else {

                                if ($stock['usable_stock'] + $stock['wait_out_stock'] < $info['num']) throw new Exception('商品可用库存不足退回数量');
                                else {

                                    if ($stock['usable_stock'] > $info['num']) {
                                        $stock['usable_stock'] -= $info['num'];
                                    } else {
                                        $stock['usable_stock'] = 0;
                                        $stock['wait_out_stock'] -= $info['num'] - $stock['usable_stock'];
                                    }
                                    $stock['total_stock'] = $stock['usable_stock'] + $stock['wait_out_stock'];
                                }
                            }

                            $stock['updatetime'] = $date;
                            $st_up = Db::name("good_stock")->save($stock);
                            if ($st_up == false) throw new Exception('可售商品入库失败');

                        }

                    }
                    ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], [
                        "order_code" => $orderinfo["orderCode"],//出库单号
                        "status" => $lor,//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "status"//新建create,编辑edit,更改状态status
                    ], "XSQRD", $orderinfo['status'], $orderinfo);

                    ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
                        "order_type" => 'XSQRD',
                        "order_code" => $orderinfo["orderCode"],//出库单号
                        "order_id" => $orderinfo["id"],
                        "order_status" => $orderinfo['status'], "before_status" => $lor
                    ]);

                    //对应采购单也要处理
//                    $holder_id = Db::name('supplier')->where(['code' => $cgd['supplierNo'], 'is_del' => 0])->value('personid', 0);
                    $holder = $userCommon->handle('sInfo', ['code' => $cgd['supplierNo']]);
                    if (!isset($holder['code']) || $holder['code'] != 0) throw new Exception($holder['message']);
                    $holder_id = $holder['data']['personid'];
                    if (in_array($cgd['status'], [4])) {
                        if ($orderinfo['is_stock'] == 1) {
                            //库存品,推给31库管人员、41库管-张凯旋
                            $uid = Db::name('user_role')
                                ->where([
                                    ['is_del', '=', 0],
                                    ['roleid', 'in', [31, 41]],
                                    ['status', '=', 1]
                                ])->column('uid');
//                            if(!in_array($this->uid,$uid)) throw new Exception('库存品订单只能由库管人员操作');
                            ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
                                "order_type" => 'CGD',
                                "order_code" => $cgd['cgdNo'],
                                "order_id" => $cgd["id"],
                                "order_status" => $cgd['status'],
                                "before_status" => $lor,
                                'holder_id' => $holder_id,
                                'handle_user_list' => implode(',', $uid),
                            ]);
                        } else {
//                            if($this->uid != $holder_id)throw new Exception('非库存品和采返商品只能由供应商负责人操作');
                            //非库存品和采返商品,推给供应商负责人
                            ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
                                "order_type" => 'CGD',
                                "order_code" => $cgd['cgdNo'],
                                "order_id" => $cgd["id"],
                                "order_status" => $cgd['status'],
                                "before_status" => $lor,
                                'holder_id' => $holder_id,
                                'handle_user_list' => $orderinfo['cgderid'],
                            ]);
                        }
                    }

//                    ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
//                        "order_type" => 'CGD',
//                        "order_code" => $cgd['cgdNo'],
//                        "order_id" => $cgd["id"],
//                        "order_status" => $cgd['status'],
//                        "before_status" => $lor,
//                        'holder_id' => $holder_id
//                    ]);

                    //以下判断是当供应商不同意要退回到业务公司的时候触发的,在3.0系统中不需要了2023-02-09@by武
//                    if ($orderinfo['is_stock'] == 1 || $info['is_th'] == 0) {
//
//                        if ($orderinfo['order_type'] != 1) {
//                            if ($orderinfo['order_type'] == 3) {
//                                $goon = Db::name("good_zixun")
//                                    ->where(["spuCode" => $orderinfo['good_code'], "is_del" => 0])
//                                    ->findOrEmpty();
//                                $isZx = 1;
//                            } else {
//                                $goon = Db::name('good_basic')
//                                    ->where(['spuCode' => $orderinfo['good_code']])
//                                    ->findOrEmpty();
//                                $isZx = 2;
//                            }
//                            $spuCode = $this->CheckGoodZx($goon, $isZx, $code);
//                            $wsmcode = $info['return_wsm'];
//                            if ($wsmcode == "") throw new Exception('未找到退货仓库');
//
//                            $stock = Db::name("good_stock")
//                                ->where(['is_del' => 0, "spuCode" => $spuCode, 'wsm_code' => $wsmcode])
//                                ->findOrEmpty();
//                            if (empty($stock)) {
//                                $stock = [
//                                    "spuCode" => $spuCode,
//                                    "wsm_code" => $wsmcode,
//                                    "usable_stock" => 0,
//                                    "wait_out_stock" => 0,
//                                    "wait_in_stock" => 0,
//                                    "total_stock" => 0,
//                                    "addtime" => $date,
//                                    "updatetime" => $date,
//                                ];
//                            }
//                            $stock['usable_stock'] += $info['num'];
//                            $stock['updatetime'] = $date;
//                            $st_up = Db::name("good_stock")->save($stock);
//                            if ($st_up == false) throw new Exception('可售商品入库失败');
//
//                            $stockid = isset($stock['id']) ? $stock['id'] : Db::name("good_stock")->getLastInsID();
//                            $sabebn = Db::name("sale_info")
//                                ->where(["orderCode" => $orderinfo["orderCode"]])
//                                ->select()
//                                ->toArray();
//                            if (!empty($sabebn)) {
//                                $total_num = $info['num'];
//                                foreach ($sabebn as $ve) {
//                                    $tempnum = 0;
//                                    if ($total_num == 0) break;
//                                    if ($total_num >= $ve['num']) {
//                                        $tempnum = $ve['num'];
//                                        $total_num -= $ve['num'];
//                                        $ve['th_num'] += $ve['num'];
//                                        $ve['num'] = 0;
//                                    } else {
//                                        $tempnum = $total_num;
//                                        $ve['num'] -= $total_num;
//                                        $ve['th_num'] += $total_num;
//                                        $total_num = 0;
//                                    }
//                                    $bnin = GoodStockInfo::AddBn($stockid, $ve['bnCode'], $tempnum, $ve['origin_price']);
//                                    if ($bnin == false) throw new Exception('可售商品Bn库存数入库失败');
//
//                                    $ve['updatetime'] = $date;
//                                    $up = Db::name("sale_info")->save($ve);
//                                    if ($up == false) throw new Exception('可售商品Bn库存数入库失败');
//
//                                    $bnin = GoodStockInfo::ReturnBn($info['returnCode'], $ve['id'], $tempnum);
//                                    if ($bnin == false) throw new Exception('可售商品Bn库存数入库失败');
//
//                                }
//                            } else {
//                                $bn = makeNo("BN");
//                                $bnin = GoodStockInfo::AddBn($stockid, $bn, $info['num'], $cgd['good_price'] ?? 0);
//                                if ($bnin == false) throw new Exception('可售商品Bn库存数入库失败');
//
//                            }
//                            $good_data = ['good_log_code' => $info['returnCode'], "stock_id" => $stockid, "type" => 1, 'stock' => $info['num'], "stock_name" => "usable_stock"];
//                            GoodLog::LogAdd(['id' => $this->uid, 'nickname' => $this->uname], $good_data, 'XSTHD');
//                        } else {
//                            $sabebn = Db::name("sale_info")
//                                ->where(["orderCode" => $orderinfo["orderCode"]])
//                                ->select()
//                                ->toArray();
//                            if (!empty($sabebn)) {
//                                $total_num = $info['num'];
//                                foreach ($sabebn as $ve) {
//                                    $stock = Db::name("good_stock")
//                                        ->where(['is_del' => 0, "spuCode" => $orderinfo['good_code'], 'id' => $ve['stockid']])
//                                        ->findOrEmpty();
//                                    if ($stock == false) throw new Exception('商品库存数据未找到');
//
//                                    $tempnum = 0;
//                                    if ($total_num == 0) break;
//                                    if ($total_num >= $ve['num']) {
//                                        $tempnum = $ve['num'];
//                                        $total_num -= $ve['num'];
//                                        $ve['th_num'] += $ve['num'];
//                                        $ve['num'] = 0;
//                                    } else {
//                                        $tempnum = $total_num;
//                                        $ve['num'] -= $total_num;
//                                        $ve['th_num'] += $total_num;
//                                        $total_num = 0;
//                                    }
//                                    $stock['usable_stock'] += $tempnum;
//                                    $stock['wait_out_stock'] -= $tempnum;
//                                    $stock['updatetime'] = $date;
//                                    $st_up = Db::name("good_stock")->save($stock);
//                                    if ($st_up == false) throw new Exception('可售商品入库失败');
//
//
//                                    $bnin = GoodStockInfo::AddBn($ve['stock_id'], $ve['bnCode'], $tempnum, $ve['origin_price']);
//                                    if ($bnin == false) throw new Exception('可售商品Bn库存数入库失败');
//
//                                    $ve['updatetime'] = $date;
//                                    $up = Db::name("sale_info")->save($ve);
//                                    if ($up == false) throw new Exception('可售商品Bn库存数入库失败');
//
//                                    $bnin = GoodStockInfo::ReturnBn($info['returnCode'], $ve['id'], $tempnum);
//                                    if ($bnin == false) throw new Exception('可售商品Bn库存数入库失败');
//
//                                }
//                            } else {
//
//                                $ordernum = Db::name("order_num")->where(['orderCode' => $orderinfo["orderCode"]])->findOrEmpty();
//                                if ($ordernum == false) throw new Exception('未找到关联采购单');
//
//                                $cgd = Db::name("purchease_order")
//                                    ->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])
//                                    ->findOrEmpty();
//                                if ($cgd == false) throw new Exception('未找到采购单数据');
//
//                                $bn = makeNo("BN");
//                                $stock = Db::name("good_stock")
//                                    ->where(["spuCode" => $orderinfo['good_code'], 'wsm_code' => $cgd['wsm_code'], "is_del" => 0, "status" => 1])
//                                    ->findOrEmpty();
//                                if ($stock == false) throw new Exception('商品库存数据未找到');
//
//                                $stock['usable_stock'] += $info['num'];
//                                $stock['wait_out_stock'] -= $info['num'];
//                                $stock['updatetime'] = $date;
//                                $st_up = Db::name("good_stock")->save($stock);
//                                if ($st_up == false) throw new Exception('可售商品入库失败');
//
//                                $yp = GoodStockInfo::AddBn($stock['id'], $bn, $info['num'], $cgd['good_price']);
//                                if ($yp == false) throw new Exception('商品批次退货入库失败');
//
//                            }
//                        }
//                    }


//                    $data = [
//                        "orderCode" => $info['orderCode'],
//                        "th_type" => 1,
//                        "th_num" => $info['num'],
//                        "th_fee" => round($info['num'] * $orderinfo['sale_price'], 2),
//                        "thCode" => $info['returnCode'],
//                        "spuCode" => $orderinfo['good_code'],
//                        "good_name" => $orderinfo['good_name'],
//                        "cat_id" => $orderinfo['cat_id'],
//                        "apply_id" => $info['apply_id'],
//                        "apply_name" => $info['apply_name'],
//                        "addtime" => $date,
//                        "status" => 1,
//                        "is_del" => 0
//                    ];
//                    $inse = Db::name("th_data")->insert($data);
//                    if ($inse == false) throw new Exception('退货单更新失败');

                }
            }
            Db::commit();
            return json_show(0, "更新成功");

        } catch (Exception $e) {
            Db::rollback();
            return json_show(1004, $e->getMessage() . '|' . $e->getFile() . ':' . $e->getLine());
        }

    }

    public function zxcreate()
    {
        $ordeCode = isset($this->post['orderCode']) && $this->post['orderCode'] != '' ? trim($this->post['orderCode']) : "";
        if ($ordeCode == '') {
            return json_show(1004, "参数orderCode 不能为空");
        }
        $order = Db::name("sale")->where(["orderCode" => $ordeCode, "is_del" => 0])->find();
        if (empty($order)) {
            return json_show(1005, "未找到订单数据");
        }
        $errorCode = isset($this->post['errorCode']) && $this->post['errorCode'] != '' ? trim($this->post['errorCode']) : "";
        if ($errorCode == '') {
            return json_show(1004, "参数errorCode 不能为空");
        }
        $error = Db::name('result_info')->where(["result_code" => $errorCode, "is_del" => 0])->find();
        if (empty($error)) {
            return json_show(1005, "未找到退货原因数据");
        }
        $remark = isset($this->post['remark']) && $this->post['remark'] != '' ? trim($this->post['remark']) : "";
//        $token = isset($this->post['token'])&&$this->post['token']!='' ? trim($this->post['token']):"";
//        if($token==''){
//            return json_show(105,"参数token不能为空");
//        }
//        $user =GetUserInfo($token);
//        if(empty($user)||$user['code']!=0){
//            return json_show(1002,"申请人数据不存在");
//        }
        $rm = $this->uid;//isset($user["data"]['id']) ?  $user["data"]['id'] : "";
        $ri = $this->uname;//isset($user["data"]['nickname']) ?  $user["data"]['nickname'] : "";
        $num = isset($this->post['num']) && $this->post['num'] != '' ? intval($this->post['num']) : "";
        if ($num == '') {
            return json_show(1005, "参数num不能为空");
        }
        if ($order['wsend_num'] < $num) {
            return json_show(1002, "仓库未发货数量不足退货");
        }

        if ($order['order_type'] == 3 || $order['order_type'] == 4) $goon = Db::name("good_zixun")->field('supplierNo')->where(["spuCode" => $order['good_code'], "is_del" => 0])->findOrEmpty();
        else  $goon = Db::name('good_basic')
            ->where(['spuCode' => $order['good_code']])->findOrEmpty();
        if (empty($goon)) return json_show(1004, '该商品不存在');

        $userCommon = \app\admin\common\User::getIns();
        $names = $userCommon->handle('getCodeAndName', ['code' => [$order['supplierNo'], $order['customer_code'], $goon['supplierNo']]]);

        $returnCode = makeNo("RS");
        Db::startTrans();
        try {
            $in = [
                "returnCode" => $returnCode,
                "orderCode" => $ordeCode,
                "good_code" => $order['good_code'],
                "good_name" => $order['good_name'],
                "apply_id" => $rm,
                "apply_name" => $ri,
                "error_code" => $errorCode,
                "num" => $num,
                "remark" => $remark,
                "order_type" => 2,
                "status" => 0,
                "is_del" => 0,
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s"),
                'supplierNo' => $goon['supplierNo'],
                'supplierName' => $names['data'][$goon['supplierNo']] ?? '',
                'companyNo' => $order['supplierNo'],
                'companyName' => $names['data'][$order['supplierNo']] ?? '',
                'customer_code' => $order['customer_code'],
                'customer_name' => $names['data'][$order['customer_code']] ?? '',
            ];
            $create = Db::name("sale_return")->insert($in, true);
            if ($create > 0) {
                $process = ["order_code" => $returnCode, "order_id" => $create, "order_status" => 0, "order_type" => 'XSTHD', "before_status" => 0, 'holder_id' => $in['apply_id']];
                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);
                $ste = ["order_code" => $returnCode, "status" => 0, "action_remark" => '',
                    "action_type" => "create"];
                ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], $ste, "XSTHD", 3, $in);

                //维护台账记录
//                Db::name('standing_book')
//                    ->where('ordeCode', $ordeCode)
//                    ->update([
//                        'returnGoodCode' => $returnCode,
//                        'updatetime' => date("Y-m-d H:i:s")
//                    ]);
                Db::execute("UPDATE `wsm_standing_book` SET `returnGoodCode`=CONCAT(IFNULL(`returnGoodCode`,''),',{$returnCode}'),`updatetime`='" . date('Y-m-d H:i:s') . "' WHERE `orderCode`='{$ordeCode}'");

                if ($order['send_type'] == 1) {
                    $wsend = Db::name("order_out")->where(['orderCode' => $ordeCode, "status" => 1, "order_type" => 2])->select();
                    // ->save(["status" => 0, "updatetime" => date("Y-m-d H:i:s")]);
                    if (!empty($wsend)) {
                        foreach ($wsend as $value) {
                            $tt = $value['status'];
                            $value['status'] = 0;
                            $value['updatetime'] = date("Y-m-d H:i:s");
                            $up = Db::name("order_out")->save($value);
                            if ($up) {
                                $process = ["order_code" => $value['outCode'], "order_id" => $value['id'], "order_status" => 0, "order_type" => 'CKD', "before_status" => $tt, 'holder_id' => $value['apply_id']];
                                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);
                                $ste = ["order_code" => $value['outCode'], "status" => $tt, "action_remark" => '', "action_type" => "status"];
                                ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], $ste, "CKD", 0, $value);
                            } else {
                                Db::rollback();
                                return json_show(1005, "退货单新建失败");
                            }
                        }
                    }
                }
                Db::commit();
                return json_show(0, "退货单新建成功");
            }
            Db::rollback();
            return json_show(1005, "退货单新建失败");
        } catch (\Exception $e) {
            Db::rollback();
            return json_show(1005, $e->getMessage());
        }
    }

    //全部退货
    public function allReturn()
    {
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] != '' ? trim($this->post['orderCode']) : "";
        if ($orderCode == '') {
            return json_show(1004, "参数orderCode 不能为空");
        }
        $order = Db::name("sale")->where(["orderCode" => $orderCode, "is_del" => 0])->find();
        if (empty($order)) {
            return json_show(1005, "未找到订单数据");
        }
        if ($order['wsend_num'] != $order['good_num']) {
            return json_show(1005, "订单未发货数量与总数不等,无法全退");
        }
        $retrun = Db::name("sale_return")->where(["orderCode" => $orderCode, "is_del" => 0, "status" => [1, 9, 8, 10, 11, 12]])->count('id');

        if ($retrun > 0) {
            return json_show(1005, "存在退货订单数据");
        }
        if ($order['order_type'] == 3 || $order['order_type'] == 4) {
            $goon = Db::name("good_zixun")
                ->where(["spuCode" => $order['good_code'], "is_del" => 0])
                ->findOrEmpty();
        } else {
            $goon = Db::name('good_platform')
                ->alias('a')
                ->join('good b', 'b.spuCode=a.spuCode', 'left')
                ->where(['a.skuCode' => $order['skuCode']])
                ->field("b.creater,b.createrid,b.supplierNo")
                ->findOrEmpty();
        }
        if (empty($goon)) {
            return json_show(1005, "未找到商品数据");
        }
//         $supplier =Db::name("supplier")->where(["code"=>$goon['supplierNo']])->find();
//        if($supplier==false){
//            return json_show(1005,"未找到商品供应商数据");
//        }
        $userCommon = \app\admin\common\User::getIns();
        $tmp = $userCommon->handle('sInfo', ['code' => $goon['supplierNo']]);
        $supplier = $tmp['data'];
        if (empty($supplier)) return json_show(1005, "未找到商品供应商数据");

        $errorCode = isset($this->post['errorCode']) && $this->post['errorCode'] != '' ? trim($this->post['errorCode']) : "";
        if ($errorCode == '') return json_show(1004, "参数errorCode 不能为空");

        $error = Db::name('result_info')->where(["result_code" => $errorCode, "is_del" => 0])->find();
        if (empty($error)) return json_show(1005, "未找到退货原因数据");

        $remark = isset($this->post['remark']) && $this->post['remark'] != '' ? trim($this->post['remark']) : "";
        $addr = Db::name("order_addr")->where([["orderCode", "=", $orderCode], ["is_del", "=", 0]])->select()->toArray();
        if ($order['is_stock'] == 0) {
            $ordernum = Db::name("order_num")->where(['orderCode' => $orderCode])->findOrEmpty();
            if (empty($ordernum)) return json_show(1005, '未找到关联采购单');

            $cgd = Db::name("purchease_order")->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])->findOrEmpty();
            if (empty($cgd)) return json_show(1005, '未找到采购单数据');

        }

        if ($order['is_stock'] == 0 && $cgd['send_status'] != 1) return json_show(1005, '采购单已发起入库');


//        $userCommon = \app\admin\common\User::getIns();
//        $names = $userCommon->handle('getCodeAndName',['code'=>[$order['supplierNo'],$order['customer_code']]]);


        $returnCode = makeNo("RN");
        Db::startTrans();
        try {
            $in = [
                "returnCode" => $returnCode,
                "orderCode" => $orderCode,
                "good_code" => $order['good_code'],
                "good_name" => $order['good_name'],
                "apply_id" => $this->uid,
                "apply_name" => $this->uname,
                "cgderid" => $goon['createrid'],
                "cgder" => $goon['creater'],
                "person" => $supplier['person'] ?? '',
                "person_id" => $supplier['personid'] ?? 0,
                "error_code" => $errorCode,
                "num" => $order['wsend_num'],
                "total_fee" => round($order['sale_price'] * $order['wsend_num'], 2),
                "good_price" => $order['sale_price'],
                "platform_id" => $order['platform_id'],
                "remark" => $remark,
                "order_type" => $order['order_type'],
                "is_addr" => count($addr) > 0 ? 1 : 0,
//                "status"=>$order['is_stock']==1?4:1,
                "status" => $order['is_stock'] == 1 ? (Db::name('order_out_child')->where(['is_del' => 0, 'orderCode' => $orderCode])->value('id', 0) ? 11 : 4) : 1,//库存品未分仓选4,分仓选11,非库存品选1"is_del"=>0,
                "is_all" => 1,
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s"),
                'supplierNo' => $supplier['code'],
                'supplierName' => $supplier['name'],
                'companyNo' => $order['supplierNo'],
                'companyName' => $order['supplierName'],
                'customer_code' => $order['customer_code'],
                'customer_name' => $order['customerName']
            ];
            $create = Db::name("sale_return")->insert($in, true);
            if ($create > 0) {
                $stn = ["order_code" => $returnCode, "status" => 0, "action_remark" => '', "action_type" => "create"];
                ActionLog::logAdd(["id" => $this->uid, "nickname" => $this->uname], $stn, "XSTHD", $in['status'], $in);
                $process = ["order_code" => $returnCode, "order_id" => $create, "order_status" => $in['status'], "order_type" => 'XSTHD', "before_status" => 0, 'holder_id' => $in['apply_id']];
                ProcessOrder::AddProcess(["id" => $this->uid, "nickname" => $this->uname], $process);
                //维护台账信息
                Db::execute("UPDATE `wsm_standing_book` SET `returnGoodCode`=CONCAT(IFNULL(`returnGoodCode`,''),',{$returnCode}'),`updatetime`='" . date('Y-m-d H:i:s') . "' WHERE `orderCode`='{$orderCode}'");
//                if (count($addr) != 0) {
//                    $inf = [];
//                    foreach ($addr as $val) {
//                        if ($val['receipt_quantity'] == 0) continue;//当退货数量为0时,跳过
//
//                        $temp = [];
//                        $send = Db::name('order_out')->where([["addrid", "=", $val['id']]])->find();
//                        if ($send == false) throw new Exception("地址发货单未找到");
//
//                        if ($send['status'] >= 2) throw new Exception("地址已发货");
//
//
//                        if ($order['is_stock'] == 1) {
//
//                            $val['is_del'] = 1;
//                            $val['updatetime'] = date("Y-m-d H:i:s");
//                            $addrup = Db::name("order_addr")->save($val);
//                            if ($addrup == false) throw new Exception("地址更新失败");
//
//
//                            $send['is_del'] = 1;
//                            $send['remark'] = '全退';
//                            $send['updatetime'] = date("Y-m-d H:i:s");
//                            $outup = Db::name("order_out")->save($send);
//                            if ($outup == false) throw new Exception("地址发货单更新失败");
//
//
//                            //处理发货申请单流程
//                            ProcessOrder::AddProcess(["id" => $this->uid, "nickname" => $this->uname], [
//                                "order_type" => 'CKD',
//                                "order_code" => $send["outCode"],//出库单号
//                                "order_id" => $send["id"],
//                                "order_status" => 4,//全部退货
//                                "before_status" => $send['status'],
//                                'holder_id=' => $send['apply_id']
//                            ]);
////                                    $ordersend = Db::name("order_send")->where(["outCode" => $send['outCode']])->find();
////                                    if($ordersend==false){
////                                    	Db::rollback();
////                                        return json_show(1004, "发货单关联数据未找到");
////                                    }
////                                    $ordersend['status'] = 0;
////                                    $ordersend['updatetime'] = date("Y-m-d H:i:s");
////                                    $sendip = Db::name("order_send")->save($ordersend);
////                                    if ($sendip == false) {
////                                        Db::rollback();
////                                        return json_show(1004, "发货单更新失败");
////                                    }
//                        }
//                        $temp['returnCode'] = $returnCode;
//                        $temp['orderCode'] = $orderCode;
//                        $temp['outCode'] = isset($send['outCode']) ? $send['outCode'] : "";
//                        $temp['addrid'] = $val['id'];
//                        $temp['send_num'] = $val['receipt_quantity'];
//                        $temp['return_num'] = $val['receipt_quantity'];
//                        $temp['is_del'] = 0;
//                        $temp['addtime'] = date("Y-m-d H:i:s");
//                        $temp['updatetime'] = date("Y-m-d H:i:s");
//                        $inf[] = $temp;
//                    }
//                    $inadd = Db::name("sale_returnaddr")->insertAll($inf);
//                    if ($inadd == 0) throw new Exception("退货单新建失败");
//
//                }

                if ($in['status'] == 4 && $order['is_stock'] == 1) {
                    $lor = $order['status'];
                    $thnum = $order['wsend_num'];
                    $order['send_num'] += $thnum;
                    $order['th_num'] += $thnum;
                    $order['wsend_num'] = 0;
                    $order['status'] = 3;
                    $order['send_status'] = 3;
                    $order['th_fee'] += round($thnum * $order['sale_price'], 2);
                    $order['updatetime'] = date("Y-m-d H:i:s");
                    $uap = Db::name("sale")->save($order);
                    if ($uap == false) throw new Exception('销售单订单更新失败');

                    ActionLog::logAdd(["id" => $this->uid, "nickname" => $this->uname], [
                        "order_code" => $order["orderCode"],//出库单号
                        "status" => $lor,//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "status"//新建create,编辑edit,更改状态status
                    ], "XSQRD", $order['status'], $order);

                    ProcessOrder::AddProcess(["id" => $this->uid, "nickname" => $this->uname], [
                        "order_type" => 'XSQRD',
                        "order_code" => $order["orderCode"],//出库单号
                        "order_id" => $order["id"],
                        "order_status" => $order['status'],
                        "before_status" => $lor,
                        'holder_id=' => $order['apply_id']
                    ]);

//                    $saleinfo = Db::name("sale_info")->where([["orderCode", "=", $orderCode], ["num", ">", 0]])->select()->toArray();
//                    if (empty($saleinfo)) {
//                        $ordernum = Db::name("order_num")->where(['orderCode' => $orderCode])->findOrEmpty();
//                        if (empty($ordernum)) throw new Exception('未找到关联采购单');
//
//                        $cgd = Db::name("purchease_order")->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])->findOrEmpty();
//                        if (empty($cgd)) throw new Exception('未找到采购单数据');
//
//                        $bn = makeNo("BN");
//                        $stock = Db::name("good_stock")->where(["spuCode" => $order['good_code'], 'wsm_code' => $cgd['wsm_code'], "is_del" => 0, "status" => 1])->find();
//                        if ($stock == false) throw new Exception('商品库存数据未找到');
//
//                        $stock['usable_stock'] += $thnum;
//                        $stock['wait_out_stock'] -= $thnum;
//                        $stock['updatetime'] = date("Y-m-d H:i:s");
//                        $st_up = Db::name("good_stock")->save($stock);
//                        if ($st_up == false) throw new Exception('可售商品入库失败');
//
//                        $yp = GoodStockInfo::AddBn($stock['id'], $bn, $thnum, $cgd['good_price']);
//                        if ($yp == false) throw new Exception('商品批次退货入库失败');
//
//
//                    } else {
//                        $tempnum = $thnum;
//                        foreach ($saleinfo as $va) {
//                            if ($tempnum == 0) break;
//                            $stock = Db::name("good_stock")->where(["spuCode" => $order['good_code'], 'id' => $va['stockid']])->findOrEmpty();
//                            if ($stock == false) throw new Exception('商品库存数据未找到');
//
//                            if ($va['num'] >= $tempnum) {
//                                $tnm = $tempnum;
//                                $va['num'] -= $tempnum;
//                                $va['th_num'] += $tempnum;
//                                $tempnum = 0;
//                            } else {
//                                $tnm = $va['num'];
//                                $tempnum -= $va['num'];
//                                $va['th_num'] += $va['num'];
//                                $va['num'] = 0;
//                            }
//                            $stock['usable_stock'] += $tnm;
//                            $stock['wait_out_stock'] -= $tnm;
//                            $stock['updatetime'] = date("Y-m-d H:i:s");
//                            $st_up = Db::name("good_stock")->save($stock);
//                            if ($st_up == false) throw new Exception('可售商品入库失败');
//
//                            $ps = GoodStockInfo::AddBn($va['stockid'], $va['bnCode'], $tnm);
//                            if ($ps == false) throw new Exception('商品批次退货入库失败');
//
//                            $ret = GoodStockInfo::ReturnBn($returnCode, $va['id'], $tnm);
//                            if ($ret == false) throw new Exception('商品批次退货入库失败');
//
//                            $va['updatetime'] = date("Y-m-d H:i:s");
//                            $sal = Db::name("sale_info")->save($va);
//                            if ($sal == false) throw new Exception('商品批次退货入库失败');
//
//                            $good_data[] = ['good_log_code' => $returnCode, "stock_id" => $va['stockid'], "type" => 1, 'stock' => $tnm, "stock_name" => "usable_stock"];
//                            $good_data[] = ['good_log_code' => $returnCode, "stock_id" => $va['stockid'], "type" => 2, 'stock' => $tnm, "stock_name" => "wait_out_stock"];
//                            GoodLog::LogAdd(['id' => $this->uid, 'nickname' => $this->uname], $good_data, 'XSTHD');
//                        }
//                    }

//                    $data=[
//                        "orderCode"=>$orderCode,
//                        "th_type"=>1,
//                        "th_num"=>$thnum,
//                        "th_fee"=>round($order['sale_price']*$thnum,2),
//                        "thCode"=>$returnCode,
//                        "spuCode"=>$order['good_code'],
//                        "good_name"=>$order['good_name'],
//                        "cat_id"=>$order['cat_id'],
//                        "apply_id"=>$this->uid,
//                        "apply_name"=>$this->uname,
//                        "addtime"=>date("Y-m-d H:i:s"),
//                        "status"=>1,
//                        "is_del"=>0
//                    ];
//                    $inse=Db::name("th_data")->insert($data);
//                    if($inse==false) throw new Exception("退货单更新失败");

                }
                Db::commit();
                return json_show(0, "退货单新建成功", ["returnCode" => $returnCode]);
            }
            Db::rollback();
            return json_show(1005, "退货单新建失败");
        } catch (\Exception $e) {
            Db::rollback();
            return json_show(1005, $e->getMessage());
        }


    }

    //导出
    public function export()
    {
        $param = $this->request->only([
            'returnCode' => '',
            'status' => '',
            'orderCode' => '',
            'apply_name' => '',
            'start' => '',
            'end' => '',
            'good_code' => '',
            'skuCode' => '',
            'relaComNo' => '',
            'order_source' => '',
            'supplierNo' => '',
            'customer_code' => '',
            'companyNo' => '',
            'company_name' => '',//部门名称
        ], 'post', 'trim');
        $where = [['sr.is_del', "=", 0]];
        if (!empty($param['returnCode'])) $where[] = ['sr.returnCode', "in", $param['returnCode']];
        if ($param['status'] !== "") $where[] = ['sr.status', "=", $param['status']];
        if ($param['orderCode'] != "") $where[] = ['sr.orderCode', "like", "%{$param['orderCode']}%"];
        if ($param['apply_name'] != "") $where[] = ['sr.apply_name', "like", "%{$param['apply_name']}%"];
        if ($param['start'] !== "") $where[] = ['sr.addtime', ">=", $param['start'] . ' 00:00:00'];
        if ($param['end'] !== "") $where[] = ['sr.addtime', "<=", $param['end'] . ' 23:59:59'];
        if ($param['good_code'] != "") $where[] = ['sr.good_code', "like", "%{$param['good_code']}%"]; //商品成本编码搜索
        if ($param['skuCode'] != "") $where[] = ['b.skuCode', "like", "%{$param['skuCode']}%"];//商品上线编码搜索
        if ($param['relaComNo'] != "") $where[] = ['a.supplierNo', '=', $param['relaComNo']];
        if ($param['company_name'] !== "") $where[] = ["sr.apply_id", 'in', get_company_item_user_by_name($param['company_name'])];
        if ($param['order_source'] !== "") $where[] = ["b.order_source", '=', $param['order_source']];
        if ($param['supplierNo'] != "") $where[] = ['a.supplierNo', 'like', '%' . $param['supplierNo'] . '%'];
        if ($param['customer_code'] != "") $where[] = ['a.customer_code', "like", '%' . $param['customer_code'] . '%'];//商品上线编码搜索
        if ($param['companyNo'] != "") $where[] = ['a.companyNo', "like", '%' . $param['companyNo'] . '%'];//商品上线编码搜索

        $condition = [];

        //只有level2的账号过滤数据权限
        if ($this->level == 2) {
            $role = $this->checkDataShare();
            $hand = resign_hand_user($this->uid, 0);
            if (!empty($role[DataGroupModel::$type_全部])) {
                $arr = array_unique(array_merge($hand, $role[DataGroupModel::$type_全部]));
                $condition[] = ["sr.apply_id", "in", $arr];
                $condition[] = ["sr.cgderid", "in", $hand];
                $condition[] = ["sr.person_id", "in", $hand];
            }
        }

        //供应商账号不允许看到库存品数据
        if ($this->level == 3) $where[] = ['b.is_stock', '<>', 1];

        if (in_array($this->roleid, config('app.wsm_cgder_role'))) $where[] = ["b.order_type", "=", 1];

        $list = Db::name("sale_return")
            ->alias('sr')
            ->field('sr.returnCode 退货单编号,sr.orderCode 销售订单编号,sr.apply_id,sr.apply_name 申请人,"" 申请人部门,sr.cgder 采购员,sr.person 供应商负责人,c.result 错误原因,sr.good_code 商品成本编码,b.skuCode 上线商品编码,sr.good_name 商品名称,sr.good_price 单价,sr.num 退货数量,sr.total_fee 退货金额,d.platform_name 平台,sr.remark 备注,sr.order_type 退货单类型,sr.status 状态,sr.is_all 是否全退货,sr.is_th 供应商是否同意退货,sr.is_addr,e.addr_code,e.addr 发货地址,sr.return_wsm 退货仓库,sr.loop_total 循环次数')
            ->leftJoin("sale b", "b.orderCode=sr.orderCode AND b.is_del=0")
            ->leftJoin("result_info c", "c.result_code=sr.error_code")
            ->leftJoin("platform d", "d.id=sr.platform_id")
            ->leftJoin("order_addr e", "e.id=sr.is_addr")
            ->where($where)
            ->where(function ($query) use ($condition) {
                $query->whereOr($condition);
            })
            ->order("sr.addtime desc")
            ->select()
            ->toArray();

        $all_createrid = array_column($list, 'apply_id');
        $item = get_company_name_by_uid($all_createrid);

        $order_type = [1 => '直接下单', 2 => '咨询', 3 => '项目', 4 => '平台', 5 => '有赞', 6 => '售后补换货', 7 => '报备转单', 8 => '支付渠道'];
        $bool = [0 => '否', 1 => '是'];
        $status = [1 => '待业务审批', 4 => '退货完成', 5 => '业务驳回', 9 => '待供应商审核', 8 => '供应商已驳回待采购审核', 10 => '业务公司修改待供应商确认', 11 => '待设置退货工单', 12 => '待库管发货'];

        foreach ($list as &$value) {
//            $value['退货金额'] = round($value['sale_price'] * $value['退货数量'],2);
            $value['申请人部门'] = $item[$value['apply_id']] ?? '';

            $value['是否全退货'] = $bool[$value['是否全退货']] ?? '';
            $value['供应商是否同意退货'] = $bool[$value['供应商是否同意退货']] ?? '';
            $value['退货单类型'] = $order_type[$value['退货单类型']] ?? '';
            $value['状态'] = $status[$value['状态']] ?? '';

            if ($value['is_addr'] == 0) $value['发货地址'] = '无地址';
            else $value['发货地址'] = GetAddr($value['addr_code']) . $value['发货地址'];

            unset($value['apply_id']);
            unset($value['good_price']);
            unset($value['addr_code']);
            unset($value['is_addr']);
        }

        if (empty($list)) $list[] = ['没有相关可导出的数据'];

        excelSave('退货单' . date('YmdHis'), array_keys($list[0]), $list);

    }

    //获取退货单对应的发货单列表
    public function getOrderOutList()
    {
        $param = $this->request->only(['returnCode', 'page' => 1, 'size' => 10], 'post', 'trim');

        $val = Validate::rule([
            'returnCode|售前退货单号' => 'require',
            'page|页码' => 'require|number|gt:0',
            'size|每页数量' => 'require|number|gt:0|max:200',
        ]);

        if ($val->check($param) == false) return json_show(1004, $val->getError());

        $where = ['a.is_del' => 0, 'a.returnCode' => $param['returnCode']];
        $count = Db::name('sale_returnaddr')
            ->alias('a')
            ->leftJoin('order_addr b', 'b.id=a.addrid and b.is_del=0')
            ->where($where)
            ->count('a.id');

        $list = Db::name('sale_returnaddr')
            ->alias('a')
            ->field('a.id,a.outCode,a.send_num,a.return_num,b.contactor,b.mobile,b.addr_code,b.addr,"" addr_code_cn')
            ->leftJoin('order_addr b', 'b.id=a.addrid and b.is_del=0')
            ->where($where)
            ->order(['a.addtime' => 'desc', 'a.id' => 'desc'])
            ->page($param['page'], $param['size'])
            ->select()
            ->toArray();

        foreach ($list as &$value) {
            if ($value['addr_code'] != '') {
                $temp = explode(',', $value['addr_code']);
                $value['addr_code_cn'] = GetAddr(json_encode(['provice_code' => $temp[0], 'city_code' => $temp[1], 'area_code' => $temp[2]]));
            }
        }

        return json_show(0, '获取列表成功', ['count' => $count, 'list' => $list]);

    }

    //取消
    public function cancel()
    {
        $param = $this->request->only(['returnCode'], 'post', 'trim');

        $val = Validate::rule([
            'returnCode|售前退货申请单号' => 'require|array|max:100',
        ]);

        if ($val->check($param) == false) return json_show(1004, $val->getError());

        $temp = Db::name('sale_return')
            ->field('returnCode')
            ->where(['is_del' => 0, 'returnCode' => $param['returnCode'], 'status' => [11, 12, 4, 5, 13]])
            ->findOrEmpty();
        if (!empty($temp)) return json_show(1004, $temp['returnCode'] . '状态有误,不允许取消');

        $rs = Db::name('sale_return')
            ->where(['is_del' => 0, 'returnCode' => $param['returnCode'], 'status' => [1, 8, 9, 10]])
            ->update([
                'status' => 13,
                'updatetime' => date('Y-m-d H:i:s')
            ]);

        return $rs ? json_show(0, '售前退货申请单取消成功') : json_show(1004, '售前退货申请单取消失败');

    }

}