<?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 AfterChild extends Base
{

    //退货工单列表
    public function getList()
    {
        $param = $this->request->only(['page' => 1, 'size' => 10, 'returnCode' => '', 'status' => '', 'orderCode' => '', 'outCode' => '', 'order_type' => '', 'supplierNo' => '', 'is_authority' => 0, 'type' => '', 'outChildCode' => '', 'return_wsm_code' => '', 'companyNo' => '', 'supplierNo' => '', 'customer_code' => '','use_type'=>''], 'post', 'trim');

        $db = Db::name('order_return_child')
            ->alias('a')
            ->leftJoin('warehouse_info b', 'b.wsm_code=a.send_wsm_code')
            ->leftJoin('warehouse_info c', 'c.wsm_code=a.return_wsm_code')
            ->leftJoin('order_return d', 'd.returnCode=a.returnCode and d.is_del=0')
            ->leftJoin('sale e','e.orderCode=a.orderCode AND e.is_del=0')
            ->leftJoin('platform p', 'p.id=e.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['order_type'] !== '') $db->where('d.order_type', $param['order_type']);
        if ($param['supplierNo'] != '') $db->whereLike('d.supplierNo', '%' . $param['supplierNo'] . '%');
        if ($param['type'] !== '') $db->where('a.type', $param['type']);
        if ($param['outChildCode'] !== '') $db->whereLike('a.outChildCode', '%' . $param['outChildCode'] . '%');
        if ($param['return_wsm_code'] !== '') $db->whereLike('a.return_wsm_code', '%' . $param['return_wsm_code'] . '%');
        if ($param['companyNo'] !== '') $db->whereLike('d.companyNo', '%' . $param['companyNo'] . '%');
        if ($param['supplierNo'] !== '') $db->whereLike('d.supplierNo', '%' . $param['supplierNo'] . '%');
        if ($param['customer_code'] !== '') $db->whereLike('d.customer_code', '%' . $param['customer_code'] . '%');
        if ($param['use_type'] !== '') $db->where('p.use_type',  $param['use_type']);

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

        //数据权限相关
        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('d.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.returnCode,a.orderCode,a.outCode,a.order_out_child_status,a.outChildCode,b.supplierName send_supplierName,b.supplierNo send_supplierNo,b.name send_wsm_name,a.send_wsm_code,b.contactor_name send_contactor_name,a.send_num,a.return_num,c.supplierName return_supplierName,c.supplierNo return_supplierNo,c.name return_wsm_name,a.return_wsm_code,c.contactor_name return_contactor_name,a.status,d.companyNo,d.companyName,d.customer_code,d.customer_name,d.order_type,d.apply_id,d.apply_name,a.type,a.can_sell_num,a.defective_num,a.loss_num,a.return_num_total,d.good_code,d.good_name,p.use_type,e.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 setOrderReturnChild()
    {

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

        $val = Validate::rule([
            'returnCode|售后申请单编码' => 'require',
            'list|工单集合' => 'require|array|max:100',
        ]);
        if ($val->check($param) == false) return json_show(1004, $val->getError());

        $info = Db::name('order_return')
            ->where(['is_del' => 0, 'returnCode' => $param['returnCode']])
            ->findOrEmpty();
        if (empty($info)) return json_show(1004, '售后申请单不存在');
        if ($info['status'] != 11) return json_show(1004, '售后申请单状态错误');
        if ($info['is_receive'] != 1) return json_show(1004, '未收到货,无需设置退货工单');

        $order_out = Db::name('order_out')
            ->field('id,status order_out_status,orderCode')
            ->where(['is_del' => 0, 'outCode' => $info['outCode']])
            ->findOrEmpty();
        if (empty($order_out)) return json_show(1004, '未找到对应的发货单');

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

        //发货工单详情
        $order_out_child = Db::name('order_out_child')
            ->where(['is_del' => 0, 'outCode' => $info['outCode'], 'outChildCode' => array_column($param['list'], 'outChildCode')])
            ->column('num,wsm_code,status', 'outChildCode');

        //所有仓库详情
        $wsm_info = Db::name('warehouse_info')
            ->where(['is_del' => 0, 'wsm_code' => array_unique(array_merge(array_column($order_out_child, 'wsm_code'), array_column($param['list'], 'return_wsm_code')))])
            ->column('id', 'wsm_code');

        if (array_sum(array_column($param['list'], 'return_num')) != $info['error_num']) return json_show(1004, '数量错误');

        Db::startTrans();
        try {

            $insert = [];
            $date = date('Y-m-d H:i:s');
            foreach ($param['list'] as $value) {
                if ($val_child->check($value) == false) throw new Exception($val_child->getError());

                if (!isset($order_out_child[$value['outChildCode']])) throw new Exception($value['outChildCode'] . '发货工单不存在');
                if (!isset($wsm_info[$value['return_wsm_code']])) throw new Exception($value['return_wsm_code'] . '退货仓库不存在');

                if ($value['return_num'] <= 0) continue;//数量为0的不再处理
                $insert[] = [
                    'returnCode' => $param['returnCode'],
                    'outChildCode' => $value['outChildCode'],
                    'order_out_child_status' => $order_out_child[$value['outChildCode']]['status'],
                    'return_num' => $value['return_num'],
                    'return_wsm_code' => $value['return_wsm_code'],
                    'apply_id' => $this->uid,
                    'apply_name' => $this->uname,
                    'is_del' => 0,
                    'status' => 1,
                    'remark' => '',
                    'addtime' => $date,
                    'updatetime' => $date
                ];

            }

            if ($insert) Db::name('order_return_prepare')->insertAll($insert);

            Db::name('order_return')
                ->where(['is_del' => 0, 'id' => $info['id'], 'status' => 11])
                ->update(['status' => 4, 'updatetime' => $date]);

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


    }

    //库管收货
    public function deliveryOrderReturnChild()
    {
        $param = $this->request->only(['returnCode', 'list'], 'post', 'trim');

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

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

        $order_return = Db::name('order_return')
            ->alias('a')
            ->field('a.id,a.good_code,a.good_name,c.sale_price,c.cat_id,a.error_num,a.apply_id,a.apply_name,a.outCode,b.orderCode,c.is_stock,c.order_type,a.status')
            ->leftJoin('order_out b', 'b.outCode=a.outCode AND b.is_del=0')
            ->leftJoin('sale c', 'c.orderCode=b.orderCode AND c.is_del=0')
            ->where(['a.is_del' => 0, 'a.returnCode' => $param['returnCode']])
            ->findOrEmpty();
        if (empty($order_return)) return json_show(1004, '售后申请单不存在');
        if ($order_return['status'] != 12) return json_show(1004, '售后申请单状态有误');

        //退货工单设置信息
        $info = Db::name('order_return_prepare')
            ->alias('a')
            ->leftJoin('order_return b', 'b.returnCode=a.returnCode and b.is_del=0')
            ->leftJoin('order_out_child c', 'c.outChildCode=a.outChildCode and c.is_del=0')
            ->leftJoin('warehouse_info d', 'd.wsm_code=c.wsm_code')
            ->leftJoin('warehouse_info e', 'e.wsm_code=a.return_wsm_code')
            ->where(['a.is_del' => 0, 'a.returnCode' => $param['returnCode']])
            ->column('a.id,a.returnCode,b.orderCode,c.outCode,a.order_out_child_status,a.outChildCode,d.supplierName send_supplierName,d.supplierNo send_supplierNo,d.name send_wsm_name,c.wsm_code send_wsm_code,d.contactor_name send_contactor_name,c.num send_num,a.return_num,e.supplierName return_supplierName,e.supplierNo return_supplierNo,e.name return_wsm_name,a.return_wsm_code,e.contactor_name return_contactor_name,a.status', 'a.id');
//        $info = Db::name('order_return_prepare')
//            ->alias('a')
//            ->leftJoin('order_out_child b', 'b.outChildCode=a.outChildCode')
//            ->leftJoin('warehouse_info c', 'c.wsm_code=a.return_wsm_code')
//            ->where(['a.is_del' => 0, 'a.returnCode' => $param['returnCode'], 'a.id' => array_column($param['list'], 'id')])
//            ->column('a.*,b.wsm_code,c.addr,c.addrs_code,c.mobile,c.contactor_name', 'a.id');
        if (empty($info)) return json_show(1004, '退货工单设置信息不存在');

        $val_child = Validate::rule([
            'id|退货工单设置信息id' => 'require|gt:0|max:999999999',
            'can_sell_num|销售仓入库数量' => 'require|number|egt:0|max:999999999999',
            'defective_num|次品仓入库数量' => 'require|number|egt:0|max:999999999999',
            'loss_num|丢失数量' => 'require|number|egt:0|max:999999999999',
            'remark|备注' => 'max:255'
        ]);

        Db::startTrans();
        try {

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

            $insert = [];
            foreach ($param['list'] as $value) {
                if ($val_child->check($value) == false) throw new Exception($val_child->getError());
                if (!isset($info[$value['id']])) throw new Exception($value['id'] . '退货工单设置信息不存在');
                if ($info[$value['id']]['status'] != 1) throw new Exception($value['id'] . '退货工单设置信息状态有误');

                //退货工单

                if ($value['can_sell_num'] > 0) {
                    $insert[] = [
                        'returnCode' => $param['returnCode'],
                        'orderCode' => $info[$value['id']]['orderCode'],
                        'outCode' => $info[$value['id']]['outCode'],
                        'order_out_child_status' => $info[$value['id']]['order_out_child_status'],
                        'outChildCode' => $info[$value['id']]['outChildCode'],
                        'send_wsm_code' => $info[$value['id']]['send_wsm_code'],
                        'send_num' => $info[$value['id']]['send_num'],
                        'return_num' => $info[$value['id']]['return_num'],
                        'return_wsm_code' => $info[$value['id']]['return_wsm_code'],
                        'can_sell_num' => $value['can_sell_num'],
                        'defective_num' => $value['defective_num'],
                        'loss_num' => $value['loss_num'],
                        'apply_id' => $this->uid,
                        'apply_name' => $this->uname,
                        'status' => 2,
                        'is_del' => 0,
                        'remark' => '',
                        'addtime' => $date,
                        'updatetime' => $date,
                        'type' => 1,
                        'return_num_total' => $value['can_sell_num'],
                    ];
                }
                //如果次品仓入库数量大于0,另生成退货工单,以类型区分
                if ($value['defective_num'] > 0) {
                    $insert[] = [
                        'returnCode' => $param['returnCode'],
                        'orderCode' => $info[$value['id']]['orderCode'],
                        'outCode' => $info[$value['id']]['outCode'],
                        'order_out_child_status' => $info[$value['id']]['order_out_child_status'],
                        'outChildCode' => $info[$value['id']]['outChildCode'],
                        'send_wsm_code' => $info[$value['id']]['send_wsm_code'],
                        'send_num' => $info[$value['id']]['send_num'],
                        'return_num' => $info[$value['id']]['return_num'],
                        'return_wsm_code' => $info[$value['id']]['return_wsm_code'],
                        'can_sell_num' => $value['can_sell_num'],
                        'defective_num' => $value['defective_num'],
                        'loss_num' => $value['loss_num'],
                        'apply_id' => $this->uid,
                        'apply_name' => $this->uname,
                        'status' => 2,
                        'is_del' => 0,
                        'remark' => '',
                        'addtime' => $date,
                        'updatetime' => $date,
                        'type' => 2,
                        'return_num_total' => $value['defective_num'],
                    ];
                }

                if ($insert) Db::name('order_return_child')->insertAll($insert);

                //发货工单数量减少
                $ot=Db::name('order_out_child')
                    ->data(['updatetime' => $date])
                    ->where(['is_del' => 0, 'outChildCode' => $info[$value['id']]['outChildCode']])
                    ->dec('num', $info[$value['id']]['return_num'])
                    ->update();
                if($ot==false) throw new \Exception('发货工单更新失败');
                $orde = Db::name('order_out')
                            ->field('id,outCode,status')
                            ->where(['outCode' => $info[$value['id']]['outCode'], 'is_del' => 0])
                            ->findOrEmpty();
                        if (empty($orde)) throw new \Exception('未找到出库单数据');

                        $sale = Db::name('sale')
                            ->field('id,th_num,th_fee,sale_price,good_code,good_name,cat_id')
                            ->where(['is_del' => 0, 'orderCode' => $info[$value['id']]['orderCode']])
                            ->findOrEmpty();
                        if (empty($sale)) throw new \Exception('未找到销售单数据');

                        $od_status = $orde['status'];
                        $orde['status'] = 4;
                        $orde['updatetime'] = $date;
                        $out = Db::name('order_out')->save($orde);
                        if ($out == false) throw new Exception('发货单更新失败');
						 $action_log_user = ['id' => $this->uid, 'nickname' => $this->uname];
                        $order = ['order_code' => $orde['outCode'], 'status' => $od_status, 'action_remark' => '', 'action_type' => 'edit'];
                        ActionLog::logAdd($action_log_user, $order, 'CKD', $orde['status'], $this->post);
                        $process = ['order_code' => $orde['outCode'], 'order_id' => $orde['id'], 'order_status' => $orde['status'], 'order_type' => 'CKD', 'before_status' => $od_status];
                        ProcessOrder::AddProcess($action_log_user, $process);
                        $sale['th_num'] += $info[$value['id']]['return_num'];
                        $sale['th_fee'] += round($info[$value['id']]['return_num']* $sale['sale_price'], 2);
                        $sale['updatetime'] = $date;
                        $sup = Db::name('sale')->save($sale);
                        if ($sup == false) throw new \Exception('销售单更新失败');
            }

            $total = array_sum(array_column($param['list'], 'can_sell_num'));

            if ($total > 0) {
                if ($order_return['is_stock'] != 1) {
                    //根据转化表判断该非库存品是否转化为库存品
                    $spuCode = Db::name('good_change_stock')
                        ->where(['old_spuCode' => $order_return['good_code'], 'old_order_type' => $order_return['order_type']])
                        ->value('spuCode', '');
                    if ($spuCode == '') {
                        //将非库存品转化为库存品
                        $spuCode = makeNo('SKU');
                        if ($order_return['order_type'] == 2) {
                            $good = Db::name('good_basic')
                                ->where('spuCode', $order_return['good_code'])
                                ->findOrEmpty();
                            if (!empty($good)) {
                                $up2=Db::name('good_basic')->insert(array_merge($good, [
                                    'id' => null,
                                    'is_stock' => 1,
                                    'spuCode' => $spuCode,
                                    'addtime' => $date,
                                    'updatetime' => $date,
                                    'status' => 7,
                                    'createrid'=>0,
                                    'creater'=>'system'
                                ]));
                                 if($up2==false) throw new \Exception("{$order_return['good_code']} 商品库新增失败");
                            }
                        } else {
                            $good = Db::name('good_zixun')
                                ->where(['spuCode' => $order_return['good_code']])
                                ->findOrEmpty();
                            if (!empty($good)) {
                               $up= 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($up==false) throw new \Exception("咨询商品录入商品库失败");
                            }
                        }

                        if (!empty($good)) {
                            //关联表增数据
                           $dd= Db::name('good_change_stock')
                                ->insert([
                                    'old_spuCode' => $order_return['good_code'],
                                    'old_order_type' => $order_return['order_type'],
                                    'spuCode' => $spuCode,
                                    'addtime' => $date,
                                    'updatetime' => $date,
                                ]);
                           if($dd==false) throw new \Exception('关联表新增失败');

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

                    }

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

                    $origin_price = $j = 0;
                    foreach ($child_bns as $child_bn) {
                        if ($origin_price === 0) $origin_price = $child_bn['origin_price'];
                       $bn= Db::name('child_bn')
                            ->data(['updatetime' => $date])
                            ->where(['id' => $child_bn['id']])
                            ->dec('num', ($child_bn['num'] >= $total) ? $total : $child_bn['num'])
                            ->update();
                        if($bn==false) throw new \Exception('商品库bn数据更新失败');
                        $total = ($child_bn['num'] >= $total) ? 0 : ($total - $child_bn['num']);
                        if ($total == 0) break;
                    }

                    foreach ($param['list'] as $value) {
                        if ($value['can_sell_num'] > 0) {
                            $stockid = Db::name('good_stock')
                                ->insertGetId([
                                    'project_code' => '',
                                    'spuCode' => $spuCode,
                                    'wsm_code' => $info[$value['id']]['return_wsm_code'],
                                    'wait_in_stock' => 0,
                                    'wait_out_stock' => 0,
                                    'usable_stock' => $value['can_sell_num'],
                                    'intra_stock' => 0,
                                    'total_stock' => $value['can_sell_num'],
                                    'status' => 1,
                                    'is_del' => 0,
                                    'warn_stock' => 0,
                                    'addtime' => $date,
                                    'updatetime' => $date,
                                ]);
                    if($stockid==false) throw new \Exception('商品库存新增失败');
                         $stockinfo=   Db::name('good_stock_info')
                                ->insert([
                                    'stockid' => $stockid,
                                    'bnCode' => substr(makeNo("BN"), 0, -2) . str_pad($j++, 2, '0', STR_PAD_LEFT),
                                    'total_num' => $value['can_sell_num'],
                                    'used_num' => 0,
                                    'balance_num' => $value['can_sell_num'],
                                    'origin_price' => $origin_price,
                                    'addtime' => $date,
                                    'updatetime' => $date,
                                ]);
                         if($stockinfo==false) throw new \Exception('商品库存BN新增失败');
                        }
                    }
                }
                else {
                    //库存品,直接维护stock和info
                    $stockids = Db::name('good_stock')
                        ->where(['is_del' => 0, 'spuCode' => $order_return['good_code'], 'wsm_code' => array_column($info, 'return_wsm_code')])
                        ->column('id', 'wsm_code');

                    foreach ($param['list'] as $value) {

                        //定义了stockid,维护bn
                        if (isset($stockids[$info[$value['id']]['return_wsm_code']])) {
                            $good_stock_info = Db::name('good_stock_info')
                                ->where(['stockid' => $stockids[$info[$value['id']]['return_wsm_code']]])
                                ->findOrEmpty();

                            if (empty($good_stock_info)) {
                                //从child_bn查询bn号并维护,新建到good_stock_info中
                                $child_bns = Db::name('child_bn')
                                    ->field('id,num,bnCode,origin_price')
                                    ->where(['orderCode' => $order_return['orderCode'], 'outCode' => $order_return['outCode'], 'childCode' => $info[$value['id']]['outChildCode']])
                                    ->order(['num' => 'desc', 'id' => 'asc'])
                                    ->cursor();

                                $total = $value['can_sell_num'];
                                foreach ($child_bns as $child_bn) {
                                 $bns=   Db::name('child_bn')
                                        ->data(['updatetime' => $date])
                                        ->where(['id' => $child_bn['id']])
                                        ->dec('num', ($child_bn['num'] >= $total) ? $total : $child_bn['num'])
                                        ->update();
								if($bns==false) throw new \Exception('商品库存BN数量新增失败');
                                  $bninfo=  Db::name('good_stock_info')
                                        ->insert([
                                            'stockid' => $stockids[$info[$value['id']]['return_wsm_code']],
                                            'bnCode' => $child_bn['bnCode'],
                                            'total_num' => ($child_bn['num'] >= $total) ? $total : $child_bn['num'],
                                            'used_num' => 0,
                                            'balance_num' => ($child_bn['num'] >= $total) ? $total : $child_bn['num'],
                                            'origin_price' => $child_bn['origin_price'],
                                            'addtime' => $date,
                                            'updatetime' => $date,
                                        ]);
									if($bninfo==false) throw new \Exception('商品库存BN更新失败');
                                    $total = ($child_bn['num'] >= $total) ? 0 : ($total - $child_bn['num']);
                                    if ($total == 0) break;
                                }
                            } else {
                                //维护记录
                             $bninfo=   Db::name('good_stock_info')
                                    ->data(['updatetime' => $date])
                                    ->where(['id' => $good_stock_info['id']])
                                    ->inc('balance_num', $value['can_sell_num'])//可用数量增加
                                    ->dec('used_num', $value['can_sell_num'])//已用数量减少
                                    ->update();
                             if($bninfo==false) throw new \Exception('商品库存BN更新失败');
                            }

                            //维护good_stock
                          $stockinfoe=  Db::name('good_stock')
                                ->data(['updatetime' => $date])
                                ->where(['is_del' => 0, 'id' => $stockids[$info[$value['id']]['return_wsm_code']]])
                                ->inc('usable_stock', $value['can_sell_num'])
                                ->inc('total_stock', $value['can_sell_num'])
                                ->update();
                    if($stockinfoe==false) throw new \Exception('商品库存更新失败');
                        } else {
                            //新建good_stock和good_stock_info
                            $stockid = Db::name('good_stock')
                                ->insertGetId([
                                    'project_code' => '',
                                    'spuCode' => $order_return['good_code'],
                                    'wsm_code' => $value['return_wsm_code'],
                                    'wait_in_stock' => 0,
                                    'wait_out_stock' => 0,
                                    'usable_stock' => $value['can_sell_num'],
                                    'intra_stock' => 0,
                                    'total_stock' => $value['can_sell_num'],
                                    'status' => 1,
                                    'is_del' => 0,
                                    'warn_stock' => 0,
                                    'addtime' => $date,
                                    'updatetime' => $date,
                                ]);
							if($stockid==false) throw new \Exception('商品库存新增失败');
                            //从child_bn查询bn号并维护,新建到good_stock_info中
                            $child_bns = Db::name('child_bn')
                                ->field('id,num,bnCode,origin_price')
                                ->where(['orderCode' => $order_return['orderCode'], 'outCode' => $order_return['outCode'], 'childCode' => $info[$value['id']]['outChildCode']])
                                ->order(['num' => 'desc', 'id' => 'asc'])
                                ->cursor();

                            $total = $value['can_sell_num'];
                            foreach ($child_bns as $child_bn) {
                                $bn=Db::name('child_bn')
                                    ->data(['updatetime' => $date])
                                    ->where(['id' => $child_bn['id']])
                                    ->dec('num', ($child_bn['num'] >= $total) ? $total : $child_bn['num'])
                                    ->update();
								if($bn==false) throw new \Exception('商品库存BN更新失败');
                                $bninfo=Db::name('good_stock_info')
                                    ->insert([
                                        'stockid' => $stockid,
                                        'bnCode' => $child_bn['bnCode'],
                                        'total_num' => ($child_bn['num'] >= $total) ? $total : $child_bn['num'],
                                        'used_num' => 0,
                                        'balance_num' => ($child_bn['num'] >= $total) ? $total : $child_bn['num'],
                                        'origin_price' => $child_bn['origin_price'],
                                        'addtime' => $date,
                                        'updatetime' => $date,
                                    ]);
								if($bninfo==false) throw new \Exception('商品库存BN新增失败');
                                $total = ($child_bn['num'] >= $total) ? 0 : ($total - $child_bn['num']);
                                if ($total == 0) break;
                            }

                        }
                    }

                    //维护商品层面的库存数
                  $goodinfo=  Db::name('good')
                        ->data(['updatetime' => $date])
                        ->where(['is_del' => 0, 'spuCode' => $order_return['good_code']])
                        ->inc('usable_stock', array_sum(array_column($param['list'], 'can_sell_num')))
                        ->update();
                    if($goodinfo==false) throw new \Exception('商品可售库存数更新失败');

                }
            }

            //售后申请单状态维护
            $Reup=Db::name('order_return')
                ->where(['is_del' => 0, 'returnCode' => $param['returnCode'], 'status' => 12])
                ->update(['status' => 5, 'updatetime' => $date]);
			 if($Reup==false) throw new \Exception('售后申请退货状态更新失败');
            //售后退货工单设置信息维护
            $Reupchild=Db::name('order_return_prepare')
                ->where(['is_del' => 0, 'status' => 1, 'id' => array_column($info, 'id')])
                ->update(['updatetime' => $date, 'status' => 3]);
             if($Reupchild==false) throw new \Exception('售后申请退货工单状态更新失败');
            $data = [
                            "orderCode" => $order_return['orderCode'],
                            "th_type" => 2,
                            "th_num" => $order_return['error_num'],
                            "th_fee" => round($order_return['error_num'] * $order_return['sale_price'], 2),
                            "thCode" => $param['returnCode'],
                            "spuCode" => $order_return['good_code'],
                            "good_name" => $order_return['good_name'],
                            "cat_id" => $order_return['cat_id'],
                            "apply_id" => $order_return['apply_id'],
                            "apply_name" => $order_return['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 $exception) {
            Db::rollback();
            return json_show(1004, $exception->getMessage());
        }


    }

    //更新退货工单标记
    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('order_return_child')
            ->field('id')
            ->where(['is_del' => 0, 'id' => $param['id']])
            ->findOrEmpty();

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

        $rs = Db::name('order_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, '更新退货工单标记内容失败');

    }

    //详情
    public function info()
    {

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

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

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

        $info = Db::name('order_return_child')
            ->alias('a')
            ->field('a.*,b.supplierName send_supplierName,b.supplierNo send_supplierNo,b.name send_wsm_name,b.contactor_name send_contactor_name,c.supplierName return_supplierName,c.supplierNo return_supplierNo,c.name return_wsm_name,c.contactor_name return_contactor_name,d.companyNo,d.companyName,d.customer_code,d.customer_name,d.order_type,d.good_code spuCode')
            ->leftJoin('warehouse_info b', 'b.wsm_code=a.send_wsm_code')
            ->leftJoin('warehouse_info c', 'c.wsm_code=a.return_wsm_code')
            ->leftJoin('order_return d', 'd.returnCode=a.returnCode and d.is_del=0')
            ->where(['a.is_del' => 0, 'a.id' => $param['id']])
            ->findOrEmpty();

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

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

    }

    //获取 售后退货工单设置信息
    public function getPreList()
    {

        $param = $this->request->only(['page' => 1, 'size' => 10, 'returnCode' => '', 'status' => ''], 'post', 'trim');

        $db = Db::name('order_return_prepare')
            ->alias('a')
            ->leftJoin('order_return b', 'b.returnCode=a.returnCode and b.is_del=0')
            ->leftJoin('order_out_child c', 'c.outChildCode=a.outChildCode and c.is_del=0')
            ->leftJoin('warehouse_info d', 'd.wsm_code=c.wsm_code')
            ->leftJoin('warehouse_info e', 'e.wsm_code=a.return_wsm_code')
            ->where('a.is_del', 0);

        if ($param['returnCode'] != '') $db->whereLike('a.returnCode', '%' . $param['returnCode'] . '%');
        if ($param['status'] !== '') $db->where('a.status', $param['status']);

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

        $list = $db
            ->field(['a.id',
                'a.returnCode',
                'b.orderCode',
                'c.outCode',
                'a.order_out_child_status',
                'a.outChildCode',
                'd.supplierName send_supplierName',
                'd.supplierNo send_supplierNo',
                'd.name send_wsm_name',
                'c.wsm_code send_wsm_code',
                'd.contactor_name send_contactor_name',
                'c.num send_num',
                'a.return_num',
                'e.supplierName return_supplierName',
                'e.supplierNo return_supplierNo',
                'e.name return_wsm_name',
                'a.return_wsm_code',
                'e.contactor_name return_contactor_name',
                'a.status'])
            ->order(['a.addtime' => 'desc', 'a.id' => 'desc'])
            ->page($param['page'], $param['size'])
            ->select()
            ->toArray();

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

    }


}