<?php

namespace app\admin\controller;

//销售单退货工单
use app\admin\model\ActionLog;
use app\admin\model\DataGroup as DataGroupModel;
use app\admin\model\ProcessOrder;
use think\Exception;
use think\facade\Db;
use think\facade\Validate;

class ReorderChild extends Base
{

    //退货工单创建
    public function add()
    {

        $param = $this->request->only(['returnCode', 'outCode' => '', 'list'], 'post', 'trim');

        $val = Validate::rule([
            'returnCode|退货单编号' => 'require',
//            'outCode|发货单编号' => 'require',
            'list|退货工单集合' => 'require|array|max:100',
        ]);
        if ($val->check($param) == false) return json_show(1004, $val->getError());

        $saleReturn = Db::name('sale_return')
            ->field('id,orderCode,status,companyNo,companyName,customer_code,customer_name,num,apply_id')
            ->where(['is_del' => 0, 'returnCode' => $param['returnCode']])
            ->findOrEmpty();
        if (empty($saleReturn)) return json_show(1004, '该退货单不存在');
        if ($saleReturn['status'] != 11) return json_show(1004, '退货单状态有误');

        $sale = Db::name('sale')
            ->field('id,sale_price,good_num,total_price,is_stock')
            ->where(['is_del' => 0, 'orderCode' => $saleReturn['orderCode']])
            ->findOrEmpty();
        if (empty($sale)) return json_show(1004, '销售单不存在');

        if ($param['outCode'] != '') {
            //所有发货工单
            $orderOutChild = Db::name('order_out_child')
                ->where(['is_del' => 0, 'outChildCode' => array_unique(array_column($param['list'], 'outChildCode'))])
                ->column('id,outCode,wsm_code,num,status,is_del', 'outChildCode');

            $saleReturnAddr = Db::name('sale_returnaddr')
                ->field('id,return_num,is_sale_return_child')
                ->where(['is_del' => 0, 'returnCode' => $param['returnCode'], 'outCode' => $param['outCode']])
                ->findOrEmpty();
            if (empty($saleReturnAddr)) return json_show(1004, '该退货地址不存在');
            if ($saleReturnAddr['is_sale_return_child'] == 1) return json_show(1004, '该退货地址不能重复设置退货工单');
            if ($saleReturnAddr['return_num'] != array_sum(array_column($param['list'], 'return_num'))) return json_show(1004, '数量错误');

            $out_code_info = Db::name('order_out')
                ->where(['is_del' => 0, 'outCode' => $param['outCode']])
                ->findOrEmpty();
            if (empty($out_code_info)) return json_show(1004, '发货申请单不存在');

        }
        $val_child = Validate::rule([
            'outChildCode|发货工单号' => 'max:255',
            'return_num|退货数量' => 'require|number|gt:0|max:999999999999',
            'return_wsm_code|退货仓库编码' => 'require'
        ]);

        if ($saleReturn['num'] < array_sum(array_column($param['list'], 'return_num'))) return json_show(1004, '数量错误');

        Db::startTrans();

        try {

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

            //维护退货地址
            if (isset($saleReturnAddr)) {
                Db::name('sale_returnaddr')
                    ->where(['id' => $saleReturnAddr['id'], 'is_del' => 0, 'is_sale_return_child' => 0])
                    ->update(['is_sale_return_child' => 1, 'updatetime' => $date]);

            }

            //生成售前退货工单
            $i = 0;
            foreach ($param['list'] as $value) {

                if ($val_child->check($value) == false) throw new Exception($val_child->getError());

                $saleReturnChildCode = substr(makeNo('KCC'), 0, -2) . str_pad($i++, 2, '0', STR_PAD_LEFT);
                $insert = [
                    'orderCode' => $saleReturn['orderCode'],
                    'returnCode' => $param['returnCode'],
                    'outCode' => $param['outCode'],
                    'outChildCode' => $value['outChildCode'] ?? '',
                    'order_out_child_status' => isset($value['outChildCode']) ? ($orderOutChild[$value['outChildCode']]['status'] ?? 0) : 0,
                    'saleReturnChildCode' => $saleReturnChildCode,
//                    'type' => $param['type'],
                    'companyNo' => $saleReturn['companyNo'],
                    'companyName' => $saleReturn['companyName'],
                    'customer_code' => $saleReturn['customer_code'],
                    'customerName' => $saleReturn['customer_name'],
                    'num' => $sale['good_num'],
                    'sale_price' => $sale['sale_price'],
                    'total_price' => $sale['total_price'],
                    'addtime' => $date,
                    'updatetime' => $date,
                    'record' => '',
                    'send_wsm_code' => isset($value['outChildCode']) ? ($orderOutChild[$value['outChildCode']]['wsm_code'] ?? '') : "",
                    'send_num' => isset($value['outChildCode']) ? ($orderOutChild[$value['outChildCode']]['num'] ?? 0) : "",
                    'return_num' => $value['return_num'],
                    'return_wsm_code' => $value['return_wsm_code'],
                    'good_receive_type' => 0,
                    'loss_num' => 0,
                    'remark' => '',
                    'status' => 1,
                    'is_del' => 0,
                    'apply_id' => $this->uid,
                    'apply_name' => $this->uname,
                ];

                $id = Db::name('sale_return_child')->insertGetId($insert);

                //修改状态,添加待办
                ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], [
                    "order_code" => $saleReturnChildCode,//单号
                    "status" => 0,//这里的status是之前的值
                    "action_remark" => '',//备注
                    "action_type" => "create"//新建create,编辑edit,更改状态status
                ], "THGD", 1, $insert);

                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
                    "order_type" => 'THGD',
                    "order_code" => $saleReturnChildCode,//单号
                    "order_id" => $id,
                    "order_status" => 1,
                    "before_status" => 0,
                    'holder_id' => $this->uid
                ]);
				if(isset($value['outChildCode'])){
					 //维护发货工单
                $orderOutChild[$value['outChildCode']]['num'] -= $value['return_num'];
                if ($orderOutChild[$value['outChildCode']]['num'] <= 0) {
                    $orderOutChild[$value['outChildCode']]['status'] = 4;
                    $orderOutChild[$value['outChildCode']]['is_del'] = 1;
                }//4已全部退货

                Db::name('order_out_child')
                    ->where('id', $orderOutChild[$value['outChildCode']]['id'])
                    ->update([
                        'updatetime' => $date,
                        'num' => $orderOutChild[$value['outChildCode']]['num'],
                        'status' => $orderOutChild[$value['outChildCode']]['status'],
                        'is_del' => $orderOutChild[$value['outChildCode']]['is_del'],
                    ]);
				}


                if ($param['outCode'] != '') {
                    //维护发货单
                    $addrinfo = Db::name("order_addr")
                        ->where('id', $out_code_info['addrid'])
                        ->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 ($out_code_info['status'] >= 2) throw new Exception("发货申请单已发货");
                    if ($out_code_info['send_num'] < $value['return_num']) throw new Exception("发货申请单发货数量不足");
                    $out_code_info['send_num'] -= $value['return_num'];
                    $out_code_info['is_del'] = $out_code_info['send_num'] == 0 ? 1 : 0;
                    $out_code_info['updatetime'] = $date;
                    $outup = Db::name("order_out")->save($out_code_info);
                    if ($outup == false) throw new Exception("发货单更新失败");
                }
            }


            //维护售前退货单
            $total_return_num = Db::name('sale_return_child')
                ->where(['is_del' => 0, 'returnCode' => $param['returnCode'], 'status' => 1])
                ->sum('return_num');

            if ($total_return_num >= $saleReturn['num']) {
                Db::name('sale_return')
                    ->where(['is_del' => 0, 'id' => $saleReturn['id'], 'status' => 11])
                    ->update(['status' => 12, 'updatetime' => $date]);

                //修改状态,添加待办
                ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], [
                    "order_code" => $param['returnCode'],//单号
                    "status" => 11,//这里的status是之前的值
                    "action_remark" => '',//备注
                    "action_type" => "status"//新建create,编辑edit,更改状态status
                ], "XSTHD", 12, ['status' => 12, 'updatetime' => $date]);

                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
                    "order_type" => 'XSTHD',
                    "order_code" => $param['returnCode'],//单号
                    "order_id" => $saleReturn['id'],
                    "order_status" => 12,
                    "before_status" => 11,
                    'holder_id' => $saleReturn['apply_id']
                ]);

            }

            Db::commit();
            return json_show(0, '设置退货工单成功');
        } catch (Exception $exception) {
            Db::rollback();
            return json_show(1004, $exception->getMessage());
        }
    }

    //退货工单列表
    public function getList()
    {

        $param = $this->request->only(['page' => 1, 'size' => 10, 'returnCode' => '', 'status' => '', 'orderCode' => '', 'outCode' => '', 'outChildCode' => '', 'saleReturnChildCode' => '', 'order_type' => '', 'supplierNo' => '', 'is_authority' => 1, 'return_wsm_code' => '', 'companyNo' => '', 'customer_code' => '','use_type'=>''], 'post', 'trim');

        if ($param['is_authority'] == '0' && $param['returnCode'] == '' && $param['orderCode'] == '' && $param['outCode'] == '' && $param['outChildCode'] == '' && $param['saleReturnChildCode'] == '') return json_show('请选择筛选条件');

        $db = Db::name('sale_return_child')
            ->alias('a')
            ->leftJoin('sale_return b', 'b.returnCode=a.returnCode and b.is_del=0')
            ->leftJoin('warehouse_info c', 'c.wsm_code=a.return_wsm_code and c.is_del=0')
            ->leftJoin('sale d','d.orderCode=a.orderCode AND d.is_del=0')
            ->leftJoin('platform p', 'p.id=d.platform_id AND p.is_del=0')
            ->where('a.is_del', 0);

        if ($param['returnCode'] != '') $db->whereLike('a.returnCode', '%' . $param['returnCode'] . '%');
        if ($param['status'] !== '') $db->where('a.status', $param['status']);
        if ($param['orderCode'] != '') $db->whereLike('a.orderCode', '%' . $param['orderCode'] . '%');
        if ($param['outCode'] != '') $db->whereLike('a.outCode', '%' . $param['outCode'] . '%');
        if ($param['outChildCode'] != '') $db->whereLike('a.outChildCode', '%' . $param['outChildCode'] . '%');
        if ($param['saleReturnChildCode'] != '') $db->whereLike('a.saleReturnChildCode', '%' . $param['saleReturnChildCode'] . '%');
        if ($param['order_type'] !== '') $db->where('b.order_type', $param['order_type']);
        if ($param['supplierNo'] != '') $db->whereLike('b.supplierNo', '%' . $param['supplierNo'] . '%');
        if ($param['return_wsm_code'] != '') $db->whereLike('a.return_wsm_code', '%' . $param['return_wsm_code'] . '%');
        if ($param['companyNo'] != '') $db->whereLike('a.companyNo', '%' . $param['companyNo'] . '%');
        if ($param['customer_code'] != '') $db->whereLike('a.customer_code', '%' . $param['customer_code'] . '%');
        if($param['use_type']!=='') $db->where('p.use_type',$param['use_type']);

        //启用数据权限
        if ($param['is_authority'] == 1) {
            //供应商账号,只查询该供应商下所有数据
            if ($this->level == 3 && $param['supplierNo'] == '') return json_show(1004, '供应商账号时供应商编码不能为空');

            //1.超管,查看全部;
            //2.业务公司账号-申请人,初始状态只查看自己创建的;
            //3.业务公司账号-退回仓库负责人,只查看自己负责仓库的数据;
            //4.业务公司账号-数据共享接受人,共享给自己的数据;
            if ($this->level == 2) {

                //是否仓库负责人
                $is_contactor = Db::name('warehouse_info')
                    ->field('id')
                    ->where(['is_del' => 0, 'contactor' => $this->uid])
                    ->findOrEmpty();
                if (empty($is_contactor)) {
                    $role = $this->checkDataShare();
                    $hand = resign_hand_user($this->uid, 0);
                    $db->whereIn('b.apply_id', array_unique(array_merge($role[DataGroupModel::$type_全部], $hand)));
                } else {
                    $db->where('`a`.`return_wsm_code` in ' . Db::name('warehouse_info')->field('wsm_code')->where(['is_del' => 0, 'contactor' => $this->uid])->buildSql());
                }
            }
        }

        $count = $db->count('a.id');

        $list = $db
            ->field('a.id,a.saleReturnChildCode,a.outChildCode,a.outCode,a.companyNo,a.companyName,a.customer_code,a.customerName,a.num,a.sale_price,a.total_price,a.status,a.addtime,b.supplierNo,b.supplierName,a.return_wsm_code,c.name return_wsm_name,c.supplierNo return_supplierNo,c.supplierName return_supplierName,c.contactor_name return_contactor_name,b.order_type,a.orderCode,a.returnCode,b.apply_name,b.apply_id,b.good_code,b.good_name,p.use_type,d.order_source')
            ->order(['a.addtime' => 'desc', 'a.id' => 'desc'])
            ->page($param['page'], $param['size'])
            ->select()
            ->toArray();

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

    }

    //库管收货(退货工单)
    public function receive()
    {
        $param = $this->request->only(['id', 'good_receive_type', 'loss_num', 'remark' => ''], 'post', 'trim');

        $val = Validate::rule([
            'id|ID' => 'require|number|gt:0',
            'good_receive_type|货物情况' => 'require|number|between:1,4',
            'loss_num|丢失数量' => 'require|number|egt:0',
            'remark|备注' => 'max:255'
        ]);

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

        $info = Db::name('sale_return_child')
            ->alias('a')
            ->field('a.id,
            a.num,
            a.status,
            a.returnCode,
            a.outChildCode,
            a.return_num,
            a.return_wsm_code,
            a.orderCode,
            a.outCode,
            a.saleReturnChildCode,
            a.apply_id,
            b.good_code spuCode,
            b.sale_price,
            b.good_name,
            b.cat_id,
            c.status order_out_status,
            b.id saleid,
            d.num thnum,
            d.id sr_id,
            d.apply_id sr_apply_id,
            d.apply_name sr_apply_name,
            b.is_stock,
            b.order_type,
            d.is_addr')
            ->leftJoin('sale b', 'b.orderCode=a.orderCode')
            ->leftJoin('order_out_child c', 'c.outChildCode=a.outChildCode AND c.is_del=0')
            ->leftJoin('sale_return d', 'd.returnCode=a.returnCode')
            ->where(['a.is_del' => 0, 'a.id' => $param['id']])
            ->findOrEmpty();
        if (empty($info)) return json_show(1004, '该退货工单不存在');
        if ($info['status'] != 1) return json_show(1004, '该退货工单已收货');
        if ($param['loss_num'] > $info['num']) return json_show(1004, '丢失数量大于下单数量');

        Db::startTrans();

        try {

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

            //维护退货工单
            Db::name('sale_return_child')
                ->where(['is_del' => 0, 'id' => $param['id'], 'status' => 1])
                ->update([
                    'status' => 2,
                    'updatetime' => $date,
                    'good_receive_type' => $param['good_receive_type'],
                    'loss_num' => $param['loss_num'],
                    'remark' => $param['remark'],
                ]);

            //修改状态,添加待办
            ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], [
                "order_code" => $info['saleReturnChildCode'],//单号
                "status" => $info['status'],//这里的status是之前的值
                "action_remark" => '',//备注
                "action_type" => "status"//新建create,编辑edit,更改状态status
            ], "THGD", 2, [
                'status' => 2,
                'updatetime' => $date,
                'good_receive_type' => $param['good_receive_type'],
                'loss_num' => $param['loss_num'],
                'remark' => $param['remark'],
            ]);

            ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
                "order_type" => 'THGD',
                "order_code" => $info['saleReturnChildCode'],//单号
                "order_id" => $info['id'],
                "order_status" => 2,
                "before_status" => $info['status'],
                'holder_id' => $info['apply_id']
            ]);

            //检查所属销售单的退货工单是否全部完成退货
            $temp = Db::name('sale_return_child')
                ->field('id')
                ->where(['is_del' => 0, 'returnCode' => $info['returnCode'], 'status' => 1])
                ->findOrEmpty();
            if (empty($temp)) {
               $up= Db::name('sale_return')
                    ->where(['is_del' => 0, 'returnCode' => $info['returnCode'], 'status' => 12])
                    ->update(['status' => 4, 'updatetime' => $date]);
				if($up==false) throw new Exception('退货单更新失败');

					  $data=[
                        "orderCode"=>$info['orderCode'],
                        "th_type"=>1,
                        "th_num"=>$info['thnum'],
                        "th_fee"=>round($info['sale_price']*$info['thnum'],2),
                        "thCode"=>$info['returnCode'],
                        "spuCode"=>$info['spuCode'],
                        "good_name"=>$info['good_name'],
                        "cat_id"=>$info['cat_id'],
                        "apply_id"=>$info['sr_apply_id'],
                        "apply_name"=>$info['sr_apply_name'],
                        "addtime"=>$date,
                        "status"=>1,
                        "is_del"=>0
                    ];
                    $inse=Db::name("th_data")->insert($data);
                    if($inse==false){
                        throw new Exception('退货单更新失败');
//                        return json_show(1004,"退货单更新失败");
                    }
                //修改状态,添加待办
                ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], [
                    "order_code" => $info['returnCode'],//单号
                    "status" => 12,//这里的status是之前的值
                    "action_remark" => '',//备注
                    "action_type" => "status"//新建create,编辑edit,更改状态status
                ], "XSTHD", 4, ['status' => 4, 'updatetime' => $date]);

                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], [
                    "order_type" => 'XSTHD',
                    "order_code" => $info['returnCode'],//单号
                    "order_id" => $info['sr_id'],
                    "order_status" => 4,
                    "before_status" => 12,
                    'holder_id' => $info['sr_apply_id']
                ]);


                //维护销售单
                $order = Db::name('sale')->where(['is_del' => 0, 'id' => $info['saleid']])->findOrEmpty();
                //未发货数量要减去发货单上的发货数量
//                $out_send_num = Db::name('order_out')
//                    ->where(['is_del' => 0, 'orderCode' => $info['orderCode'], 'status' => [0, 1]])
//                    ->sum('send_num');

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

                $old_status = $order['status'];

                $thnum = $info['thnum'];//退货总数量

//                $thnum = $info['thnum'] - $all_loss_num;//退货总数量-丢失总数量
//                if ($order['wsend_num'] < $thnum) throw new Exception("销售单未发货数量不足退货");

                //如果  发货  维护销售单的
                //else 未发货数量减,
                if ($info['order_out_status'] == 1) {
                    $order['wsend_num'] -= $thnum;
                    $order['send_num'] += $thnum;
                }


//                $lor = $order['status'];

                $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('销售单订单更新失败');

                if ($old_status != $order['status']) {
                    ActionLog::logAdd(['id' => $info['sr_apply_id'], 'nickname' =>$info['sr_apply_name']], [
                        "order_code" => $order["orderCode"],//出库单号
                        "status" => $old_status,//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "status"//新建create,编辑edit,更改状态status
                    ], "XSQRD", $order['status'], $order);

                    ProcessOrder::AddProcess(['id' => $info['sr_apply_id'], 'nickname' =>$info['sr_apply_name']], [
                        "order_type" => 'XSQRD',
                        "order_code" => $order["orderCode"],//出库单号
                        "order_id" => $order["id"],
                        "order_status" => $order['status'],
                        "before_status" => $old_status
                    ]);
                }

                //非库存品转存为库存品
                if ($info['is_stock'] != 1) {
                    //根据转化表判断该非库存品是否转化为库存品
                    $spuCode = Db::name('good_change_stock')
                        ->where(['old_spuCode' => $info['spuCode'], 'old_order_type' => $info['order_type']])
                        ->value('spuCode', '');
                    if ($spuCode == '') {
                        //将非库存品转化为库存品
                        $spuCode = makeNo('SKU');
                        if ($info['order_type'] == 2) {
                            $good = Db::name('good_basic')
                                ->where('spuCode', $info['spuCode'])
                                ->findOrEmpty();
                            if (!empty($good)) {
                                Db::name('good_basic')->insert(array_merge($good, [
                                    'id' => null,
                                    'spuCode' => $spuCode,
                                    'addtime' => $date,
                                    'updatetime' => $date,
//                                    'status' => 0,
                                    'is_stock' => 1,
                                    'status' => 7,
                                    'createrid' => 0,
                                    'creater' => 'system',
                                ]));
                            }
                        } else {
                            $good = Db::name('good_zixun')
                                ->where(['spuCode' => $info['spuCode']])
                                ->findOrEmpty();
                            if (!empty($good)) {
                                Db::name('good_basic')->insert([
                                    'spuCode' => $spuCode,
                                    'good_code' => $good['good_code'],
                                    'good_name' => $good['good_name'],
                                    'cat_id' => $good['cat_id'],
                                    'brand_id' => $good['brand_id'],
                                    'companyNo' => $good['companyNo'],
                                    'companyName' => $good['companyName'],
                                    'good_unit' => $good['good_unit'],
                                    'good_type' => $good['good_type'],
                                    'moq' => $good['moq'],
                                    'is_exclusive' => 0,
                                    'customized' => $good['customized'],
                                    'tax' => $good['tax'],
                                    'supplierNo' => $good['supplierNo'],
                                    'supplierName' => $good['supplierName'],
                                    'is_auth' => $good['is_auth'],
                                    'auth_img' => $good['auth_img'],
                                    'is_stock' => 1,
                                    'after_sales' => '',
                                    'craft_desc' => $good['craft_desc'],
                                    'good_remark' => $good['good_remark'],
                                    'good_size' => '',
                                    'weight' => $good['weight'],
                                    'packing_way' => '',
                                    'packing_size' => '',
                                    'packing_spec' => '',
                                    'packing_list' => '',
                                    'packing_weight' => 0,
                                    'good_bar' => '',
                                    'supply_area' => $good['supply_area'],
                                    'delivery_place' => '',
                                    'origin_place' => '',
                                    'delivery_day' => '',
                                    'lead_time' => '',
                                    'sample_day' => '',
                                    'sample_fee' => '',
                                    'good_img' => $good['good_img'],
                                    'good_thumb_img' => $good['good_thumb_img'],
                                    'good_info_img' => $good['good_info_img'],
                                    'cert_fee' => 0,
                                    'packing_fee' => 0,
                                    'cost_fee' => 0,
                                    'mark_fee' => 0,
                                    'demo_fee' => 0,
                                    'open_fee' => 0,
                                    'noble_metal' => $good['noble_metal'],
                                    'noble_weight' => 0,
                                    'is_gold_price' => $good['is_gold_price'],
                                    'cgd_gold_price' => 0,
                                    'market_price' => 0,
                                    'nake_price' => 0,
                                    'is_step' => 0,
                                    'is_online' => 0,
                                    'status' => 7,
                                    'createrid' => 0,
                                    'creater' => 'system',
                                    'field_change' => '',
                                    'is_del' => 0,
                                    'addtime' => $date,
                                    'updatetime' => $date,
                                    'is_diff' => 0,
                                    'config' => '',
                                    'other_config' => '',
                                    'stock_moq' => 0,
                                    'is_support_barter' => 1,
                                    'chargerid' => $good['createrid'],
                                    'charger' => $good['creater'],
                                    'is_support_stock' => 1
                                ]);
                            }
                        }

                        if (!empty($good)) {
                            //关联表增数据
                            Db::name('good_change_stock')
                                ->insert([
                                    'old_spuCode' => $info['spuCode'],
                                    'old_order_type' => $info['order_type'],
                                    'spuCode' => $spuCode,
                                    'addtime' => $date,
                                    'updatetime' => $date,
                                ]);

                        } else throw new Exception('未找到对应的商品数据');

                    }

                    //新增bn记录,维护旧有bn记录
                    $child_bns = Db::name('child_bn')
                        ->field('id,num,origin_price')
                        ->where(['orderCode' => $info['orderCode'], 'outCode' => $info['outCode']])
                        ->order(['num' => 'desc', 'id' => 'asc'])
                        ->cursor();

                    $total = $info['return_num'];
                    $origin_price = $j = 0;
                    foreach ($child_bns as $child_bn) {
                        if ($origin_price === 0) $origin_price = $child_bn['origin_price'];
                        Db::name('child_bn')
                            ->data(['updatetime' => $date])
                            ->where(['id' => $child_bn['id']])
                            ->dec('num', ($child_bn['num'] >= $total) ? $total : $child_bn['num'])
                            ->update();
                        $total = ($child_bn['num'] >= $total) ? 0 : ($total - $child_bn['num']);
                        if ($total == 0) break;
                    }

                    $all_total = Db::name('sale_return_child')
                        ->where(['is_del' => 0, 'returnCode' => $info['returnCode']])
                        ->field('sum(`return_num`) - sum(`loss_num`) total')
                        ->findOrEmpty();

                    if ($all_total['total'] > 0) {
                        $stockid = Db::name('good_stock')
                            ->insertGetId([
                                'project_code' => '',
                                'spuCode' => $spuCode,
                                'wsm_code' => $info['return_wsm_code'],
                                'wait_in_stock' => 0,
                                'wait_out_stock' => 0,
                                'usable_stock' => $all_total['total'],
                                'intra_stock' => 0,
                                'total_stock' => $all_total['total'],
                                'status' => 1,
                                'is_del' => 0,
                                'warn_stock' => 0,
                                'addtime' => $date,
                                'updatetime' => $date,
                            ]);

                        Db::name('good_stock_info')
                            ->insert([
                                'stockid' => $stockid,
                                'bnCode' => substr(makeNo("BN"), 0, -2) . str_pad($j++, 2, '0', STR_PAD_LEFT),
                                'total_num' => $all_total['total'],
                                'used_num' => 0,
                                'balance_num' => $all_total['total'],
                                'origin_price' => $origin_price,
                                'addtime' => $date,
                                'updatetime' => $date,
                            ]);
                    }
                } else {
                    //维护商品层面的库存数
                    $has_good = Db::name('good')
                        ->field('id')
                        ->where(['is_del' => 0, 'spuCode' => $info['spuCode']])
                        ->findOrEmpty();
                    if (empty($has_good)) throw new Exception('未找到商品上线记录');
                    else {
                        //要增加的实际库存要减去所有丢失数量
                        $all_loss_num = Db::name('sale_return_child')
                            ->where(['is_del' => 0, 'returnCode' => $info['returnCode']])
                            ->sum('loss_num');
                        Db::name('good')
                            ->data(['updatetime' => $date])
                            ->where('id', $has_good['id'])
                            ->inc('usable_stock', $thnum - $all_loss_num)
                            ->update();
                    }

                }
            }

            //在创建退货工单的时候,已经减掉了,这里不用重复减了
            //有地址就会有发货单,继而有发货工单
//            if ($info['is_addr'] == 1) {
//                //发货工单数量减少
//                $tmp = Db::name('order_out_child')
//                    ->where(['is_del' => 0, 'outChildCode' => $info['outChildCode']])
//                    ->field('id,num')
//                    ->findOrEmpty();
//
//                $tmp['num'] -= $info['return_num'];   halt($tmp);
//                $tmp['updatetime'] = $date;
//                if ($tmp['num'] <= 0) $tmp['is_del'] = 1;
//
//                Db::name('order_out_child')
//                    ->where(['is_del' => 0, 'id' => $tmp['id']])
//                    ->update($tmp);
//
//                //维护发货单
//                $temp = Db::name('order_out')
//                    ->field('id,send_num')
//                    ->where(['is_del' => 0, 'outCode' => $info['outCode']])
//                    ->findOrEmpty();
//
//                $temp['send_num'] -= $info['return_num'];
//                $temp['updatetime'] = $date;
//                if ($temp['send_num'] <= 0) $temp['is_del'] = 1;
//
//                Db::name('order_out')
//                    ->where('id', $temp['id'])
//                    ->update($temp);
//            }


            //维护bn
            if ($info['order_out_status'] == 1) {
                //待发货,说明此时有库存,有bn号
                Db::name('child_bn')
                    ->data(['updatetime' => $date])
                    ->where(['orderCode' => $info['orderCode'], 'outCode' => $info['outCode'], 'childCode' => $info['outChildCode']])
                    ->inc('num', $info['return_num'])
                    ->update();
                Db::name('good_stock')
                    ->data(['updatetime' => $date])
                    ->where(['is_del' => 0, 'spuCode' => $info['spuCode'], 'wsm_code' => $info['return_wsm_code']])
                    ->inc('usable_stock', $info['return_num'])
                    ->dec('wait_out_stock', $info['return_num'])
                    ->update();
            }


            Db::commit();
            return json_show(0, '设置退货工单成功');

        } catch (Exception $exception) {
            Db::rollback();
            return json_show(1004, $exception->getMessage());
        }

    }

    //详情
    public function info()
    {
        $param = $this->request->only(['id'], 'post', 'trim');

        $val = Validate::rule(['id' => 'require|number|gt:0']);

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

        $info = Db::name('sale_return_child')
            ->alias('a')
            ->field('a.*,b.supplierNo,b.supplierName,c.name return_wsm_name,c.supplierNo return_supplierNo,c.supplierName return_supplierName,c.contactor_name return_contactor_name,b.good_code spuCode,b.order_type')
            ->leftJoin('sale_return b', 'b.returnCode=a.returnCode and b.is_del=0')
            ->leftJoin('warehouse_info c', 'c.wsm_code=a.return_wsm_code and c.is_del=0')
            ->where(['a.is_del' => 0, 'a.id' => $param['id']])
            ->findOrEmpty();

        return empty($info) ? json_show(1004, '该退货工单不存在') : json_show(0, '获取退货工单详情成功', $info);

    }

    //更新退货工单标记
    public function setRecord()
    {

        $param = $this->request->only(['id', 'record'], 'post', 'trim');

        $val = Validate::rule([
            'id|退货工单id' => 'require|number|gt:0',
            'record|标记内容' => 'require',
        ]);

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

        $temp = Db::name('sale_return_child')
            ->field('id')
            ->where(['is_del' => 0, 'id' => $param['id']])
            ->findOrEmpty();

        if (empty($temp)) return json_show(1004, '该退货工单不存在');

        $rs = Db::name('sale_return_child')
            ->where(['is_del' => 0, 'id' => $param['id']])
            ->update(['record' => $param['record'], 'updatetime' => date('Y-m-d H:i:s')]);

        return $rs ? json_show(0, '更新退货工单标记内容成功') : json_show(1004, '更新退货工单标记内容失败');

    }

}