<?php

namespace app\admin\controller;

use app\admin\model\GoodLog;
use app\admin\model\ProcessOrder;
use Exception;
use think\App;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use app\admin\model\ActionLog;
use think\facade\Validate;

//销售单
class Sale extends Base
{

    public $noble = [];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->noble = \think\facade\Config::get("noble");
    }

    public function create()
    {
        $token = isset($this->post['token']) && $this->post['token'] !== "" ? trim($this->post['token']) : "";
        $orderCode = makeNo("QR");
        $customer_code = isset($this->post['customer_code']) && $this->post['customer_code'] !== "" ? trim($this->post['customer_code']) : "";
        if ($customer_code == "") {
            return error_show(1002, "客户customer_code不能为空");
        }

        $customer = Db::name("customer_info")->where(["companyNo" => $customer_code])->find();
        if ($customer == false) {
            return error_show(1004, "未找到客户数据");
        }
        $supplierNo = isset($this->post['supplierNo']) && $this->post['supplierNo'] !== "" ? trim($this->post['supplierNo']) : "";
        if ($supplierNo == "") {
            return error_show(1002, "参数supplierNo不能为空");
        }
        $supplier = Db::name("business")->where(["companyNo" => $supplierNo])->find();
        if ($supplier == false) {
            return error_show(1004, "未找到平台供应商数据");
        }
        $goodtype = isset($this->post['goodtype']) && $this->post['goodtype'] !== "" ? intval($this->post['goodtype']) : "1";
        $order_type = isset($this->post['order_type']) && $this->post['order_type'] !== "" ? intval($this->post['order_type']) : "1";
        $sendtype = isset($this->post['sendtype']) && $this->post['sendtype'] !== "" ? intval($this->post['sendtype']) : "";
        if ($sendtype === '') {
            return error_show(1004, "参数sendtype不能为空");
        }
        $platform_id = isset($this->post['platform_id']) && $this->post['platform_id'] !== "" ? intval($this->post['platform_id']) : "";
        if ($platform_id == '') {
            return error_show(1004, "参数platform_id不能为空");
        }
        $platform_order = isset($this->post['platform_order']) && $this->post['platform_order'] !== "" ? trim($this->post['platform_order']) : "";
        $good_code = isset($this->post['good_code']) && $this->post['good_code'] !== "" ? trim($this->post['good_code']) : "";
        if ($good_code == '') {
            return error_show(1004, "参数good_code不能为空");
        }
        $good_num = isset($this->post['good_num']) && $this->post['good_num'] !== "" ? intval($this->post['good_num']) : "";
        if ($good_num === '') {
            return error_show(1004, "参数good_num不能为空");
        }
        $arrtime = isset($this->post['arrtime']) && $this->post['arrtime'] != "" ? $this->post['arrtime'] : "";
        if ($arrtime == "") {
            return error_show(1004, "参数arrtime不能为空");
        }
        $paytime = isset($this->post['paytime']) && $this->post['paytime'] != "" ? $this->post['paytime'] : "";
        $workNo = isset($this->post['workNo']) && $this->post['workNo'] != "" ? trim($this->post['workNo']) : "";
        // $poNo =isset($this->post['poNo'])&&$this->post['poNo']!=""? trim($this->post['poNo']):"";
        $ct = Db::name('good_platform')->alias('a')->join('good b', 'b.spuCode=a.spuCode', 'left')
            ->where(['a.skuCode' => $good_code])->field("b.*,a.skuCode,a.platform_code,a.plat_code")->find();
        if ($ct == false) {
            return error_show(1002, "未找到商品数据");
        }
        $goodinfo = $ct;
        $is_stock = $ct['is_stock'];
        $spuCode = $ct['spuCode'];
        $skuCode = $ct['skuCode'];
        $is_activity = isset($this->post['is_activity']) && $this->post['is_activity'] !== "" ? $this->post['is_activity'] : "";
        $actcode = isset($this->post['act_code']) && $this->post['act_code'] !== "" ? trim($this->post['act_code']) : "";
        if ($order_type == 1) {
            if ($is_activity === "") {
                return error_show(1002, "参数is_activity不能为空");
            }
            if ($is_activity == 1 && $actcode == "") {
                return error_show(1002, "参数act_code不能为空");
            }
        }
        if ($goodinfo['is_stock'] == 1) {
            $stock = Db::name("good_stock")->alias("a")->leftJoin("warehouse_info b", "a.wsm_code=b.wsm_code")->where
            (["spuCode" => $spuCode, "a.is_del" => 0, "a.status" => 1, "b.wsm_type" => 5, "b.companyNo" => $supplierNo])->field("a.id,a.wait_in_stock,a.usable_stock,a.wait_out_stock")->find();
            if ($stock == false || $stock['usable_stock'] < $good_num) {
                return error_show(1003, "库存数量不足");
            }
//            if($stock['usable_stock']>0 && $stock['usable_stock']<$good_num){
//                return error_show(1003,"可用库存数量不足");
//            }
//            if($stock['usable_stock']== 0 && $stock['wait_in_stock']- $stock['presale_stock']<$good_num){
//                return error_show(1003,"待入库存数量不足");
//            }
            $origin_price = 0;
        } else {
            if ($is_activity == 0) {
                $origin = Db::name("good_nake")->where([["spuCode", "=", $spuCode], ["min_num", "<=", $good_num], ["is_del", "=", 0]])->order("min_num desc")->find();
                if ($origin == false) {
                    return error_show(1003, "未找到相关阶梯成本价格");
                }
                $origin_price = $origin['nake_total'];
            }
        }

        $sale_price = isset($this->post['good_price']) && $this->post['good_price'] !== "" ? floatval($this->post['good_price']) : '';
        $ct['cgd_gold_price'] = 0;
        if ($goodtype == 1) {
            if ($is_activity == 1) {
                $act = Db::name("activity_info")->alias("a")->leftJoin("good_activity b", "a.activity_code=b.activity_code")
                    ->where(["a.skuCode" => $skuCode, "a.activity_code" => $actcode, "a.is_del" => 0, "a.status" => 1, "b.status" => 6, "b.is_del" => 0])
                    ->find();
                if ($act == false) {
                    return error_show(1003, "未找到相关活动价");
                }
                if ($act['moq_num'] > $good_num) {
                    return error_show(1003, "商品不满足活动价起订量{$act['moq_num']}");
                }
                if ($act['activity_stock'] < $good_num) {
                    return error_show(1003, "商品活动库存剩余{$act['activity_stock']}");
                }
                $sale_price = $sale_price !== "" ? $sale_price : $act['activity_price'];
                $origin_price = $act['cost_price'];
            } else {
                $good = Db::name("good_ladder")->where(["skuCode" => $skuCode, "is_del" => 0, "status" => 1])->where([["min_num", "<=", $good_num]])->order("min_num desc")->find();
                if ($good == false) {
                    return error_show(1003, "未找到相关阶梯价格");
                }
                $sale_price = $sale_price !== "" ? $sale_price : $good['sale_price'];
                if ($ct['is_gold_price'] == 1 && $is_stock != 1) {
                    $gold = Db::name("gold_price1")
                        ->field('id,price')
                        ->where(["type" => $ct['noble_metal'], "is_del" => 0, "status" => 1])
                        ->order("addtime desc")
                        ->find();

                    //$saleprice(最终售价) = (打样费/购买数量 + 开模费/购买数量 + 商品重量* 最新金价 + 工艺费* 商品重量+包装费+加标费+证书费+产品裸价+物流费)/(1-成本售价/100);
                    $sale_price = $sale_price !== "" ? $sale_price : ($ct['demo_fee'] / $good_num + $ct['open_fee'] / $good_num
                        + $ct['noble_weight'] * $gold["price"] + $good['cost_fee'] * $ct['noble_weight'] + $origin['package_fee'] + $origin['mark_fee'] + $origin['cert_fee'] + $origin['nake_fee'] + $origin['delivery_fee']);
                    $ct['cgd_gold_price'] = $gold["price"];
                }
            }

        } else {
            $sale_price = 0;
        }
        $cgd = [
            "supplierNo" => $ct['supplierNo'],
            "companyNo" => $supplierNo,
            "orderCode" => $orderCode,
            "spuCode" => $ct['spuCode'],
            "skuCode" => $ct['skuCode'],
            "good_name" => $ct['good_name'],
            "sale_price" => $origin_price,
            "total_fee" => $origin_price * $good_num,
            "pakge_fee" => isset($origin['package_fee']) ? $origin['package_fee'] : 0,
            "cert_fee" => isset($origin['cert_fee']) ? $origin['cert_fee'] : 0,
            "open_fee" => $ct['open_fee'],
            "cost_fee" => isset($origin['cost_fee']) ? $origin['cost_fee'] : 0,
            "mark_fee" => isset($origin['mark_fee']) ? $origin['mark_fee'] : 0,
            "nake_fee" => isset($origin['nake_fee']) ? $origin['nake_fee'] : 0,
            "delivery_fee" => isset($origin['delivery_fee']) ? $origin['delivery_fee'] : 0,
            "demo_fee" => $ct['demo_fee'],
            "good_num" => $good_num,
            "good_type" => $goodtype,
            "weight" => $ct['noble_weight'],
            "gold_price" => isset($ct['cgd_gold_price']) ? $ct['cgd_gold_price'] : 0,
            "order_type" => $is_stock == 1 ? 1 : 2,
            "order_source" => 1,//1直接下单
            "createrid" => $ct['createrid'],
            "creater" => $ct['creater'],
            'send_way' => 2

        ];
        $addrlist = isset($this->post['addrlist']) && $this->post['addrlist'] !== "" ? $this->post['addrlist'] : "";
        $send_num = 0;
        if ($sendtype == 1) {
            if ($addrlist == "" || empty($addrlist) || !is_array($addrlist)) {
                return error_show(1004, "参数addrlist不能为空");
            }
            $send_num = array_sum(array_column($addrlist, "receipt_quantity"));
        }
        if ($send_num > $good_num) {
            return error_show(1004, "发货数量超出订单总数量");
        }
        $remark = isset($this->post['remark']) && $this->post['remark'] !== "" ? trim($this->post['remark']) : "";
        $proof_id = isset($this->post['proof_id']) && $this->post['proof_id'] !== "" ? intval($this->post['proof_id']) : 0;

        $apply_id = GetUserInfo($token);
        if (empty($apply_id) || $apply_id['code'] != 0) {
            return error_show(1002, "申请人数据不存在");
        }
        $rm = isset($apply_id["data"]['id']) ? $apply_id["data"]['id'] : "";
        $ri = isset($apply_id["data"]['nickname']) ? $apply_id["data"]['nickname'] : "";
        Db::startTrans();
        try {
            $data = [
                "orderCode" => $orderCode,
                "good_code" => $spuCode,
                "skuCode" => $skuCode,
                "customer_code" => $customer_code,
                "good_name" => isset($goodinfo['good_name']) && $goodinfo['good_name'] !== '' ? $goodinfo['good_name'] : '',
                "good_num" => $good_num,
                "cat_id" => $goodinfo['cat_id'],
                "apply_id" => $rm,
                "apply_name" => $ri,
                "origin_price" => $origin_price,
                "sale_price" => $sale_price,
                "post_fee" => 0,
                "status" => 0,
                "send_num" => 0,
                "wsend_num" => $good_num,
                "send_status" => 0,
                "good_type" => $goodtype,
                "send_type" => $sendtype,
                "supplierNo" => $supplierNo,
                "is_del" => 0,
                "zxNo" => "",
                "platform_order" => $platform_order,
                "platform_id" => $platform_id,
                "remark" => $remark,
                "is_stock" => $is_stock,
                "is_activity" => $is_activity === "" ? 0 : $is_activity,
                "activity_code" => $actcode,
                "order_type" => $is_stock == 1 ? 1 : 2,
                "order_source" => 1,//1直接下单
//                "poNo"=>$poNo,
                'good_weight' => $ct['noble_weight'],
                'gold_price' => isset($ct['cgd_gold_price']) ? $ct['cgd_gold_price'] : 0,
                'cost_price' => isset($good['cost_fee']) ? $good['cost_fee'] : 0,
                'diff_weight' => 0,
                'diff_fee' => 0,
                "workNo" => $workNo,
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s"),
                'total_price' => round($sale_price * $good_num, 2),
                'proof_id' => $proof_id
            ];
            $paytime == "" ? "" : $data['paytime'] = $paytime;
            $datainfo = Db::name('sale')->insert($data, true);
            if ($datainfo > 0) {

                //修改状态,添加待办
                ActionLog::logAdd($this->post['token'], [
                    "order_code" => $orderCode,//销售单code
                    "status" => 0,//这里的status是之前的值
                    "action_remark" => '',//备注
                    "action_type" => "create"//新建create,编辑edit,更改状态status
                ], "XSQRD", 0, $this->post);

                ProcessOrder::AddProcess($this->post['token'], [
                    "order_type" => 'XSQRD',
                    "order_code" => $orderCode,//销售单code
                    "order_id" => $datainfo,
                    "order_status" => 0, "before_status" => 0
                ]);

                if ($is_activity == 1) {
                    $actup = [
                        "activity_stock" => $act['activity_stock'] - $good_num,
                        "updatetime" => date("Y-m-d H:i:s")
                    ];
                    $actupp = Db::name("activity_info")->where(["skuCode" => $skuCode, "activity_code" => $actcode,
                        "is_del" => 0, "status" => 1])->save($actup);
                    if ($actupp == false) {
                        Db::rollback();
                        return error_show(1002, "活动库存修改失败");
                    }
                }
                $outstatus = 0;
                $standing_book_da = ['sale_id' => $datainfo, 'customer_code' => $customer_code, 'skuCode' => $skuCode, 'updatetime' => date('Y-m-d H:i:s')];
                if ($is_stock == 0) {
                    $bol = $this->createCgd($cgd, $standing_book_da);
                    if ($bol == false) {
                        Db::rollback();
                        return error_show(1002, "订单创建失败");
                    }
                } else {
                    $outstatus = 1;
                    $bol = $this->RelaCgd([
                        'orderCode' => $orderCode,
                        "good_num" => $good_num,
                        "spuCode" => $spuCode,
                        "companyNo" => $supplierNo,
                        "cost_fee" => isset($good['cost_fee']) ? $good['cost_fee'] : 0,
                        'order_type' => $data['order_type'],
                        'order_source' => $data['order_source'],
                    ], $standing_book_da);
                    if ($bol == false) {
                        Db::rollback();
                        return error_show(1002, "库存商品关联采购单失败");
                    }
                    if (isset($stock)) {

//                        if($stock['usable_stock']==0){
//                            $stck = ["presale_stock"=>$stock['presale_stock']+$good_num,
//                                    "updatetime"=>date("Y-m-d H:i:s")
//                                     ];
//                        }else{
                        $stck = [
                            "usable_stock" => $stock['usable_stock'] - $good_num,
                            "wait_out_stock" => $stock['wait_out_stock'] + $good_num,
                            "updatetime" => date("Y-m-d H:i:s")
                        ];
//                        }

                        $upad = Db::name("good_stock")->where($stock)->update($stck);
                        if ($upad == false) {
                            Db::rollback();
                            return error_show(1002, "库存商品更新库存失败");
                        }
                        //商品变动日志表,good_log_code字段存储采购单号
                        $good_data[] = ['good_log_code' => $orderCode, "stock_id" => $stock['id'], "type" => 2, 'stock' => $good_num, "stock_name" => "usable_stock"];
                        $good_data[] = ['good_log_code' => $orderCode, "stock_id" => $stock['id'], "type" => 1, 'stock' => $good_num, "stock_name" => "wait_out_stock"];
                        GoodLog::LogAdd($this->post['token'], $good_data, "XSQRD");
                    }

                }

                if ($sendtype == 1) {
                    foreach ($addrlist as $value) {
                        $temp = [];
                        $addrs = [];
                        if ($value['addr_code'] !== '' && is_array($value['addr_code']) && !empty($value['addr_code'])) {
                            $addrs['provice_code'] = $value['addr_code'][0];
                            $addrs['city_code'] = $value['addr_code'][1];
                            $addrs['area_code'] = $value['addr_code'][2];
                            $addr = json_encode($addrs);
                        } else {
                            $addr = isset($value['addr_code']) ? $value['addr_code'] : '';
                        }
                        $temp['orderCode'] = $orderCode;
                        $temp['contactor'] = $value['contactor'];
                        $temp['mobile'] = $value['mobile'];
                        $temp['addr'] = $value['addr'];
                        $temp['addr_code'] = $addr;
                        $temp['customer_code'] = $customer_code;
                        $temp['receipt_quantity'] = $value['receipt_quantity'];
                        $temp['post_fee'] = 0;
                        $temp['is_del'] = 0;
                        $temp['addtime'] = date("Y-m-d H:i:s");
                        $temp['updatetime'] = date("Y-m-d H:i:s");
                        $temp['arrive_time'] = $arrtime;
                        $vmp = Db::name('order_addr')->insert($temp, true);
                        if ($vmp > 0) {
                            //  if($is_stock==1) {
                            $order = Db::name("order_num")->where(["orderCode" => $orderCode, "status" => 1])->where([["wsend_num", ">=", 0]])
                                ->lock(true)->find();
                            if ($order == false) {
                                return error_show(1004, "未找到可以发货得采购单数据");
                            }
                            $num = $value['receipt_quantity'];
                            $outCode = makeNo("DF");
                            $order['wsend_num'] -= $num;
                            $order['send_num'] += $num;
                            $or = Db::name("order_num")->save($order);
                            if ($or == false) {
                                Db::rollback();
                                return error_show(1002, "发货地址添加创建失败");
                            }
                            $tep = [
                                "cgdNo" => $order['cgdNo'],
                                "outCode" => $outCode,
                                "send_num" => $num,
                                "status" => 1,
                                "addtime" => date("Y-m-d H:i:s"),
                                "updatetime" => date("Y-m-d H:i:s")
                            ];
                            $sen = Db::name("order_send")->save($tep);
                            if ($sen == false) {
                                Db::rollback();
                                return error_show(1002, "发货地址添加创建失败");
                            }

                            $cgdinfo = Db::name("purchease_order")->where(["cgdNo" => $order['cgdNo']])->find();
                            if ($cgdinfo == false) {
                                Db::rollback();
                                return error_show(1002, "未匹配到采购数据");
                            }
                            $out = [
                                "orderCode" => $orderCode,
                                "outCode" => $outCode,
                                "apply_id" => $rm,
                                "apply_name" => $ri,
                                "addrid" => $vmp,
                                "post_name" => "",
                                "post_code" => "",
                                "post_fee" => 0,
                                "sendtime" => date("Y-m-d H:i:s"),
                                "send_num" => $num,
                                "check_num" => 0,
                                "error_num" => 0,
                                "wsm_code" => $cgdinfo['wsm_code'],
                                "order_type" => $is_stock == 1 ? 1 : 2,
                                "status" => $outstatus,
                                "addtime" => date("Y-m-d H:i:s"),
                                "updatetime" => date("Y-m-d H:i:s")
                            ];
                            $ou = Db::name("order_out")->insert($out);
                            if ($ou == false) {
                                Db::rollback();
                                return error_show(1002, "发货地址添加创建失败");
                            } else {
                                //修改状态,添加待办
                                ActionLog::logAdd($this->post['token'], [
                                    "order_code" => $outCode,//出库单号
                                    "status" => $out['status'],//这里的status是之前的值
                                    "action_remark" => '',//备注
                                    "action_type" => "create"//新建create,编辑edit,更改状态status
                                ], "CKD", $out['status'], $out);

                                ProcessOrder::AddProcess($this->post['token'], [
                                    "order_type" => 'CKD',
                                    "order_code" => $outCode,//出库单号
                                    "order_id" => Db::name("order_out")->getLastInsID(),
                                    "order_status" => $out['status'], "before_status" => $out['status']
                                ]);


//                                        $standing_book_da['outCode'] = $outCode;
                                if (isset($standing_book_da['outCode'])) $standing_book_da['outCode'][] = $outCode;
                                else $standing_book_da['outCode'] = [$outCode];
                            }
                            //   }
                        } else {
                            Db::rollback();
                            return error_show(1002, "发货地址添加创建失败");
                        }
                    }
                }

                //处理台账
                if (isset($standing_book_da['outCode'])) $standing_book_da['outCode'] = implode(',', $standing_book_da['outCode']);//发货单号拼接
                Db::name('standing_book')->insert(array_merge($standing_book_da, ['addtime' => date('Y-m-d H:i:s'), 'updatetime' => date('Y-m-d H:i:s'), 'standBookNo' => makeNo('IO')]));

                Db::commit();
                return error_show(0, "咨询订单创建成功", ["order_code" => $orderCode]);
            }
            Db::rollback();
            return error_show(1002, "咨询订单创建失败");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1005, $e->getMessage());
        }
    }

    //采购单
    public function createCgd($data, array &$standing_book_da = [])
    {
        $cgdCode = makeNo("CG");
        $supplier = Db::name("supplier")->where(["code" => $data['supplierNo'], "is_del" => 0])->find();
        if ($supplier == false) {
            return false;
        }
        $wsm = Db::name("warehouse_info")->where(["supplierNo" => $data["supplierNo"], "companyNo" => $data['companyNo'], "wsm_type" => 2, "is_del" => 0])->find();
        if ($wsm == false) {
            $wsm_code = makeNo("WSM");
            $inwsm = [
                "wsm_code" => $wsm_code,
                "name" => $supplier['name'],
                "wsm_type" => 2,
                "supplierNo" => $supplier['code'],
                "addr" => "",
                "addrs_code" => "",
                "contactor" => $data['order_type'] == 1 ? $supplier['personid'] : $data['createrid'],
                "contactor_name" => $data['order_type'] == 1 ? $supplier['person'] : $data['creater'],
                "mobile" => "",
                "position" => "",
                "companyNo" => $data['companyNo'],
                "status" => 1,
                "is_del" => 0,
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s")
            ];
            $in = Db::name("warehouse_info")->insert($inwsm);
            if ($in == false) {
                return false;
            }
        } else {
            $wsm_code = $wsm['wsm_code'];
        }

        $cg = ["cgdNo" => $cgdCode,
            "bkcode" => "",
            "wsm_code" => $wsm_code,
            "cgder" => $data['creater'],
            "cgder_id" => $data['createrid'],
            "spuCode" => $data['spuCode'],
            "skuCode" => $data['skuCode'],
            "good_name" => $data['good_name'],
            "good_num" => $data['good_num'],
            "good_price" => $data['sale_price'],
            "total_fee" => round($data['sale_price'] * $data['good_num'], 2),
            "pakge_fee" => $data['pakge_fee'],
            "cert_fee" => $data['cert_fee'],
            "open_fee" => $data['open_fee'],
            "teach_fee" => $data['cost_fee'],
            "mark_fee" => $data['mark_fee'],
            "demo_fee" => $data['demo_fee'],
            "nake_fee" => $data['nake_fee'],
            "weight" => $data['weight'],
            "delivery_fee" => $data['delivery_fee'],
            "gold_price" => $data['gold_price'],
            "diff_weight" => "0",
            "diff_fee" => "0",
            "supplierNo" => $data['supplierNo'],
            "supplier_name" => $supplier['name'],
            "companyNo" => $data['companyNo'],
            "send_status" => 1,
            "send_num" => 0,
            "wsend_num" => $data['good_num'],
            "remark" => "",
            "status" => 0,//0初始化
            "lasttime" => date("Y-m-d H:i:s"),
            "is_del" => 0,
            "order_type" => $data['order_type'],
            "order_source" => $data['order_source'],
            "good_type" => $data['good_type'],
            "addtime" => date("Y-m-d H:i:s"),
            "updatetime" => date("Y-m-d H:i:s")
        ];
        $up = Db::name("purchease_order")->insert($cg, true);
        if ($up) {
            //修改状态,添加待办
            ActionLog::logAdd($this->post['token'], [
                "order_code" => $cg['cgdNo'],//销售单code
                "status" => 0,//这里的status是之前的值
                "action_remark" => '',//备注
                "action_type" => "create"//新建create,编辑edit,更改状态status
            ], "CGD", $cg['status'], $cg);

            ProcessOrder::AddProcess($this->post['token'], [
                "order_type" => 'CGD',
                "order_code" => $cg['cgdNo'],//销售单code
                "order_id" => $up,
                "order_status" => $cg['status'], "before_status" => 0
            ]);

            $standing_book_da = array_merge($standing_book_da, [
                'orderCode' => $data['orderCode'],
                'cgdNo' => $cgdCode,
                'spuCode' => $data['spuCode'],
                'skuCode' => $data['skuCode'],
                'order_type' => $data['order_type'],
                'order_source' => $data['order_source'],
                'supplierNo' => $data['supplierNo'],
                "companyNo" => $data['companyNo'],
            ]);

            $rela = [
                "orderCode" => $data['orderCode'],
                "cgdNo" => $cgdCode,
                "spuCode" => $data['spuCode'],
                "good_num" => $data['good_num'],
                "wsend_num" => $data['good_num'],
                "send_num" => 0,
                "wait_num" => 0,
                "status" => 1,
                "source" => 2
            ];
            $re = Db::name("order_num")->save($rela);
            if ($re == false) {
                return false;
            } else {
                $stokc = Db::name("good_stock")->where(['spuCode' => $data['spuCode'], "wsm_code" => $wsm_code, "is_del" => 0])->find();
                if ($stokc == false) {
                    $stokc = [
                        "spuCode" => $data['spuCode'],
                        "wsm_code" => $wsm_code,
                        "wait_in_stock" => $data['good_num'],
                        "wait_out_stock" => 0,
                        "usable_stock" => 0,
                        "intra_stock" => 0,
                        "total_stock" => 0,
                        "status" => 1,
                        "addtime" => date("Y-m-d H:i:s"),
                        "updatetime" => date("Y-m-d H:i:s")
                    ];
                } else {
                    $stokc['wait_in_stock'] += $data['good_num'];
                    $stokc['updatetime'] = date("Y-m-d H:i:s");
                }
                $stoc = Db::name("good_stock")->save($stokc);
                if ($stoc == false) {
                    return false;
                }
                $good_data[] = ['good_log_code' => $cgdCode, "stock_id" => isset($stoc['id']) ? $stoc['id'] : Db::name("good_stock")->getLastInsID(), "type" => 1,
                    'stock' => $data['good_num'], "stock_name" => "wait_in_stock"];
                GoodLog::LogAdd($this->post['token'], $good_data, "CGD");
                return true;
            }
        } else {
            return false;
        }

    }

    public function addAddr()
    {
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] != "" ? trim($this->post['orderCode']) : "";
        $etid = Db::name("sale")->where(["orderCode" => $orderCode, "is_del" => 0])->find();
        if (empty($etid)) {
            return error_show(1002, "未找到数据");
        }
        $arrtime = isset($this->post['arrtime']) && $this->post['arrtime'] != "" ? $this->post['arrtime'] : "";
        $token = isset($this->post['token']) && $this->post['token'] !== "" ? trim($this->post['token']) : "";
        $apply_id = GetUserInfo($token);
        if (empty($apply_id) || $apply_id['code'] != 0) {
            return error_show(1002, "申请人数据不存在");
        }
        $rm = isset($apply_id["data"]['id']) ? $apply_id["data"]['id'] : "";
        $ri = isset($apply_id["data"]['nickname']) ? $apply_id["data"]['nickname'] : "";
        $addrlist = isset($this->post['addrlist']) && $this->post['addrlist'] !== "" ? $this->post['addrlist'] : "";
        if ($addrlist == "" || empty($addrlist) || !is_array($addrlist)) {
            return error_show(1004, "参数addrlist不能为空");
        }
        Db::startTrans();
        try {
            foreach ($addrlist as $value) {
                $temp = [];
                $addrs = [];
                if ($value['addr_code'] !== '' && is_array($value['addr_code']) && !empty($value['addr_code'])) {
                    $addrs['provice_code'] = $value['addr_code'][0];
                    $addrs['city_code'] = $value['addr_code'][1];
                    $addrs['area_code'] = $value['addr_code'][2];
                    $addr = json_encode($addrs);
                } else {
                    $addr = isset($value['addr_code']) && $value['addr_code'] !== '' ? $value['addr_code'] : '';
                }
                $temp['orderCode'] = $orderCode;
                $temp['contactor'] = $value['contactor'];
                $temp['mobile'] = $value['mobile'];
                $temp['addr'] = $value['addr'];
                $temp['addr_code'] = $addr;
                $temp['customer_code'] = $etid['customer_code'];
                $temp['receipt_quantity'] = $value['receipt_quantity'];
                $temp['post_fee'] = 0;
                $temp['is_del'] = 0;
                $temp['addtime'] = date("Y-m-d H:i:s");
                $temp['updatetime'] = date("Y-m-d H:i:s");
                if ($arrtime != "") {
                    $temp['arrive_time'] = $arrtime;
                }
                $vmp = Db::name('order_addr')->insert($temp, true);
                if ($vmp > 0) {
                    $num = $value['receipt_quantity'];
                    $order = Db::name("order_num")->where(["orderCode" => $orderCode, "status" => 1])->where([["wsend_num", ">=", 0]])
                        ->find();
                    if (empty($order) || $order['wsend_num'] < $num) {
                        return error_show(1004, "未找到可以发货得采购单数据");
                    }

                    $outCode = makeNo("DF");
                    $order['send_num'] += $num;
                    $order['wsend_num'] -= $num;
                    $or = Db::name("order_num")->save($order);
                    if ($or == false) {
                        Db::rollback();
                        return error_show(1002, "发货地址添加创建失败");
                    }
                    $tep = [
                        "cgdNo" => $order['cgdNo'],
                        "outCode" => $outCode,
                        "send_num" => $num,
                        "status" => 1,
                        "addtime" => date("Y-m-d H:i:s"),
                        "updatetime" => date("Y-m-d H:i:s")
                    ];
                    $sen = Db::name("order_send")->save($tep);
                    if ($sen == false) {
                        Db::rollback();
                        return error_show(1002, "发货地址添加创建失败");
                    }
                    $cgdinfo = Db::name("purchease_order")->where(["cgdNo" => $order['cgdNo']])->find();
                    if ($cgdinfo == false) {
                        Db::rollback();
                        return error_show(1002, "未匹配到采购数据");
                    }

                    //维护商品所在仓库的库存 --- start
                    $temp = Db::name('good_stock')
                        ->field('id,usable_stock,wait_out_stock')
                        ->where(['spuCode' => $order['spuCode'], 'wsm_code' => $cgdinfo['wsm_code']])
                        ->find();
                    if ($etid['is_stock'] == 1) {
                        if ($temp == false) {
                            Db::rollback();
                            return error_show(1004, '库存不足');
                        }
                        if (($temp['wait_out_stock'] - $num) < 0) {
                            Db::rollback();
                            return error_show(1004, '库存不足');
                        }

//                            $up =Db::name('good_stock')
//                                ->where('id', $temp['id'])
//                                ->update([
//                                    'usable_stock' => $temp['usable_stock'] - $num,
//                                    'wait_out_stock' => $temp['wait_out_stock'] + $num,
//                                    'updatetime' => date('Y-m-d H:i:s'),
//                                ]);
//                            if($up==false){
//                                Db::rollback();
//                                return error_show(1004, '库存更新失败');
//                            }
//                            $good_data[] = ['good_log_code' =>$outCode, "stock_id" =>$temp['id'], "type" => 1,'stock'=>$num, "stock_name" => "wait_out_stock"];
//                            $good_data[] = ['good_log_code' =>$outCode, "stock_id" =>$temp['id'], "type" => 2,'stock'=>$num, "stock_name" => "usable_stock"];
//                            GoodLog::LogAdd($this->post['token'],$good_data,"CKD");
                        $status = 1;
                    } else {
                        if ($temp == false || ($temp['usable_stock'] - $num) < 0) {
                            $status = 0;
                        } else {
                            if (($temp['usable_stock'] - $num) < 0) {
                                Db::rollback();
                                return error_show(1004, '库存不足');
                            }

                            $up = Db::name('good_stock')
                                ->where('id', $temp['id'])
                                ->update([
                                    'usable_stock' => $temp['usable_stock'] - $num,
                                    'wait_out_stock' => $temp['wait_out_stock'] + $num,
                                    'updatetime' => date('Y-m-d H:i:s'),
                                ]);
                            if ($up == false) {
                                Db::rollback();
                                return error_show(1004, '库存更新失败');
                            }
                            $good_data[] = ['good_log_code' => $outCode, "stock_id" => $temp['id'], "type" => 1, 'stock' => $num, "stock_name" => "wait_out_stock"];
                            $good_data[] = ['good_log_code' => $outCode, "stock_id" => $temp['id'], "type" => 2, 'stock' => $num, "stock_name" => "usable_stock"];
                            GoodLog::LogAdd($this->post['token'], $good_data, "CKD");
                            $status = 1;
                        }
                    }


                    $out = [
                        "orderCode" => $orderCode,
                        "outCode" => $outCode,
                        "apply_id" => $rm,
                        "apply_name" => $ri,
                        "addrid" => $vmp,
                        "post_name" => "",
                        "post_code" => "",
                        "post_fee" => 0,
                        "sendtime" => date("Y-m-d H:i:s"),
                        "send_num" => $num,
                        "check_num" => 0,
                        "error_num" => 1,
                        "wsm_code" => $cgdinfo['wsm_code'],
                        "order_type" => $etid['order_type'],
                        "status" => $status,
                        "addtime" => date("Y-m-d H:i:s"),
                        "updatetime" => date("Y-m-d H:i:s")
                    ];
                    $ou = Db::name("order_out")->insert($out);
                    if ($ou == false) {
                        Db::rollback();
                        return error_show(1002, "发货地址添加创建失败");
                    } else {
                        //修改状态,添加待办
                        ActionLog::logAdd($this->post['token'], [
                            "order_code" => $outCode,//出库单号
                            "status" => 0,//这里的status是之前的值
                            "action_remark" => '',//备注
                            "action_type" => "create"//新建create,编辑edit,更改状态status
                        ], "CKD", 0, $out);

                        ProcessOrder::AddProcess($this->post['token'], [
                            "order_type" => 'CKD',
                            "order_code" => $outCode,//出库单号
                            "order_id" => Db::name("order_out")->getLastInsID(),
                            "order_status" => $status, "before_status" => 0
                        ]);

                        //处理台账-既然是根据orderCode更新的数据,那么肯定是有数据的,只需要更新就行了
                        Db::execute("UPDATE `wsm_standing_book` SET `outCode`=CONCAT(`outCode`,',{$outCode}'),`updatetime`='" . date('Y-m-d H:i:s') . "' WHERE `orderCode`='{$orderCode}'");

                    }

                    //维护商品所在仓库的库存 --- end
                } else {
                    Db::rollback();
                    return error_show(1002, "发货地址添加创建失败");
                }
            }
            Db::commit();
            return app_show(0, "发货地址添加完成");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1002, $e->getMessage());
        }

    }

    public function consultOrder()
    {
        $bidNo = isset($this->post['bidNo']) && $this->post['bidNo'] != "" ? trim($this->post['bidNo']) : "";
        if ($bidNo == "") {
            return error_show(1003, "参数bidNo不能为空");
        }
        $zxinfo = Db::name("consult_bids")->where(["bidNo" => $bidNo, "is_del" => 0])->find();
        if ($zxinfo == false) {
            return error_show(1003, "未找到咨询单商品信息");
        }
        if ($zxinfo['status'] != 6) {
            return error_show(1003, "咨询单状态有误无法转单");
        }
        $zx = Db::name("consult_info")->where(["infoNo" => $zxinfo['infoNo'], "is_del" => 0])->find();
        if ($zx == false) {
            return error_show(1003, "未找到咨询单信息");
        }
        if ($zx['status'] != 4) {
            return error_show(1003, "咨询单状态有误无法转单");
        }
        $zxorder = Db::name("consult_order")->where(["zxNo" => $zx["zxNo"], "is_del" => 0])->find();
        if ($zxorder == false) {
            return error_show(1003, "未找到咨询单信息");
        }
        $good_num = isset($this->post['good_num']) && $this->post['good_num'] != "" ? intval($this->post['good_num']) : "";
        if ($good_num === "") {
            return error_show(1003, "参数 good_num 不能为空");
        }
        $sale_price = isset($this->post['sale_price']) && $this->post['sale_price'] != "" ? floatval($this->post['sale_price']) : "";
        if ($sale_price === "") {
            return error_show(1003, "参数 sale_price 销售单价 不能为空");
        }
        if ($sale_price < $zxinfo['sale_price']) {
            return error_show(1003, "修改的销售单价不能低于原来的销售单价");
        }
        $sendtype = isset($this->post['sendtype']) && $this->post['sendtype'] != "" ? intval($this->post['sendtype']) : "";
        if ($sendtype == "") {
            return error_show(1003, "参数sendtype不能为空");
        }
        $companyNo = isset($this->post['companyNo']) && $this->post['companyNo'] != "" ? trim($this->post['companyNo']) : "";
        if ($companyNo == "") {
            return error_show(1003, "参数 companyNo 不能为空");
        }
        $company = Db::name("business")->where(["companyNo" => $companyNo, "is_del" => 0])->find();
        if ($company == false) {
            return error_show(1003, "业务公司数据未找到");
        }
        $remark = isset($this->post['remark']) && $this->post['remark'] != "" ? trim($this->post['remark']) : "";

        $orderCode = makeNo("QR");
        $spuCode = $zxinfo['spuCode'];
        $skuCode = "";
        $is_stock = 0;
        $cgd = [
            "supplierNo" => $zxinfo['supplierNo'],
            "companyNo" => $companyNo,
            "spuCode" => $spuCode,
            "skuCode" => $skuCode,
            "orderCode" => $orderCode,
            "good_name" => $zxinfo['good_name'],
            "sale_price" => $zxinfo['total_fee'],
            "total_fee" => round($zxinfo['total_fee'] * $good_num, 2),
            "pakge_fee" => $zxinfo['pakge_fee'],
            "cert_fee" => $zxinfo['cert_fee'],
            "open_fee" => $zxinfo['open_fee'],
            "cost_fee" => $zxinfo['cost_fee'],
            "mark_fee" => $zxinfo['mark_fee'],
            "demo_fee" => $zxinfo['demo_fee'],
            "nake_fee" => $zxinfo['nake_fee'],
            "delivery_fee" => $zxinfo['delivery_fee'],
            "good_num" => $good_num,
            "createrid" => $zxinfo['createrid'],
            "creater" => $zxinfo['creater'],
            "good_type" => 1,
            "weight" => $zxinfo['good_weight'],
            "gold_price" => $zxinfo['gold_price'],
            "is_diff" => $zxinfo['is_diff'],
            "order_type" => 3,
            "order_source" => 2,//咨询
            'send_way' => $zxinfo['send_way']
        ];
        $token = isset($this->post['token']) && $this->post['token'] != "" ? trim($this->post['token']) : "";
        if ($token == "") {
            return error_show(102, "参数token不能为空");
        }
        $apply_id = GetUserInfo($token);
        if (empty($apply_id) || $apply_id['code'] != 0) {
            return error_show(102, "申请人数据不存在");
        }
        $rm = isset($apply_id["data"]['id']) ? $apply_id["data"]['id'] : "";
        $ri = isset($apply_id["data"]['nickname']) ? $apply_id["data"]['nickname'] : "";

        $va = isset($this->post['order_addr']) && $this->post['order_addr'] !== "" ? $this->post['order_addr'] : "";
        $send_num = 0;
        if ($sendtype == 1) {
            if ($va == "") {
                return error_show(1002, "参数order_addr不能为空");
            }
            $send_num = array_sum(array_column($va, "receipt_quantity"));
        }
        if ($good_num < $send_num) {
            return error_show(1002, "发货数量不能超过购买数量");
        }
        $arrtime = isset($this->post['arrtime']) && $this->post['arrtime'] != "" ? $this->post['arrtime'] : "";
        if ($arrtime == "") {
            return error_show(1002, "参数arrtime不能为空");
        }

        //新加字段
        $platform_order = isset($this->post['platform_order']) && $this->post['platform_order'] != "" ? $this->post['platform_order'] : "";
        $workNo = isset($this->post['workNo']) && $this->post['workNo'] != "" ? $this->post['workNo'] : "";
        $proof_type = isset($this->post['proof_type']) && $this->post['proof_type'] != "" ? intval($this->post['proof_type']) : 0;
        $proof_url = isset($this->post['proof_url']) && $this->post['proof_url'] != "" ? trim($this->post['proof_url']) : '';


        Db::startTrans();
        try {
            $zx = Db::name("consult_info")->where(["infoNo" => $zxinfo['infoNo'], "is_del" => 0])->lock(true)->find();
            if ($zx == false) {
                Db::rollback();
                return error_show(1003, "未找到咨询单信息");
            }
            if ($companyNo != $zxorder['companyNo']) {
                $zxord = Db::name("consult_order")->where($zxorder)->update(["companyNo" => $companyNo, "updatetime" => date("Y-m-d H:i:s")]);
                if ($zxord == false) {
                    Db::rollback();
                    return error_show(1003, "咨询单更新业务公司失败");
                }
            }
            $data = [
                "orderCode" => $orderCode,
                "good_code" => $spuCode,
                "skuCode" => $skuCode,
                "customer_code" => $zxorder['khNo'],
                "good_name" => isset($zxinfo['good_name']) && $zxinfo['good_name'] !== '' ? $zxinfo['good_name'] : '',
                "good_num" => $good_num,
                "cat_id" => $zxinfo['cat_id'],
                "apply_id" => $rm,
                "apply_name" => $ri,
                "origin_price" => $zxinfo['total_fee'],
                "sale_price" => $sale_price,//销售单价支持修改
                "post_fee" => 0,
                "status" => 0,
                "send_num" => 0,
                "wsend_num" => $good_num,
                "send_status" => 1,
                "good_type" => 1,
                "send_type" => $sendtype,
                "supplierNo" => $companyNo,
                "is_del" => 0,
                "zxNo" => $bidNo,
                "platform_order" => $platform_order,
                "platform_id" => $zxorder['platform_code'],
                "remark" => $remark,
                "arrive_time" => $arrtime,
                "is_stock" => 0,
                "is_activity" => 0,
                "activity_code" => '',
                "proof_id" => 0,
                "order_type" => 3,
                "order_source" => 2,//2咨询
                'good_weight' => $zxinfo['good_weight'],
                'gold_price' => $zxinfo['gold_price'],
                'cost_price' => $zxinfo['sale_cost_fee'],
                'diff_weight' => 0,
                'diff_fee' => 0,
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s"),
                'total_price' => round($sale_price * $good_num, 2),
                'workNo' => $workNo,
            ];
            $datainfo = Db::name('sale')->insert($data, true);
            if ($datainfo > 0) {

                $standing_book_data = [
                    'sale_id' => $datainfo,
                    'infoNo' => $zxinfo['infoNo'],
                    'updatetime' => date('Y-m-d H:i:s')
                ];

                //修改状态,添加待办
                ActionLog::logAdd($this->post['token'], [
                    "order_code" => $orderCode,//销售单code
                    "status" => 0,//这里的status是之前的值
                    "action_remark" => '',//备注
                    "action_type" => "create"//新建create,编辑edit,更改状态status
                ], "XSQRD", $data['status'], $data);

                ProcessOrder::AddProcess($this->post['token'], [
                    "order_type" => 'XSQRD',
                    "order_code" => $orderCode,//销售单code
                    "order_id" => $datainfo,
                    "order_status" => $data['status'], "before_status" => 0
                ]);
                $old_zx_status = $zx['status'];
                $sa = Db::name("consult_info")->where($zx)->save(["status" => 5, "updatetime" => date("Y-m-d H:i:s")]);
                if ($sa == false) {
                    Db::rollback();
                    return error_show(1002, "咨询单修改失败");
                } else {
                    //修改状态,添加待办
                    ActionLog::logAdd($this->post['token'], [
                        "order_code" => $zx['infoNo'],//咨询单详情编号
                        "status" => $old_zx_status,//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "status"//新建create,编辑edit,更改状态status
                    ], "ZXD", 5, $zx);

                }
                $bol = $this->createCgd($cgd, $standing_book_data);
                if ($bol == false) {
                    Db::rollback();
                    return error_show(1002, "咨询订单创建失败");
                }
                $limt = [
                    "spuCode" => $zxinfo['spuCode'],
                    "good_name" => $zxinfo['good_name'],
                    "brand_id" => $zxinfo['brand_id'],
                    "good_unit" => $zxinfo['unit_id'],
                    "cat_id" => $zxinfo['cat_id'],
                    "good_type" => 0,
                    "moq" => 1,
                    "customized" => $zxinfo['work_day'],
                    "tax" => $zxinfo['tax'],
                    "supplierNo" => $zxinfo["supplierNo"],
                    "is_auth" => 0,
                    "craft_desc" => $zxinfo['good_name'],
                    "good_remark" => "",
                    "platform_id" => $zxorder['platform_id'],
                    "good_img" => $zxinfo['good_img'],
                    "good_thumb_img" => "",
                    "good_info_img" => "",
                    "specinfo" => $zxinfo['specinfo'],
                    "work_day" => $zxinfo['work_day'],
                    "noble_metal" => $zxinfo['metal_id'],
                    "is_gold_price" => $zxinfo['is_gold_price'],
                    "config" => $zxinfo['config'],
                    "other_config" => $zxinfo['other_config'],
                    "weight" => $zxinfo['weight'],
                    "good_weight" => $zxinfo['good_weight'],
                    "is_diff" => $zxinfo['is_diff'],
                    "supply_area" => $zxinfo['supply_area'],
                    "pay_way" => $zxinfo['pay_way'],
                    "send_way" => $zxinfo['send_way'],
                    "companyNo" => $companyNo,
                    "status" => 1,
                    "is_del" => 0,
                    "createrid" => $zxinfo['createrid'],
                    "creater" => $zxinfo['creater'],
                    "addtime" => date("Y-m-d H:i:s"),
                    "updatetime" => date("Y-m-d H:i:s"),
                    'proof_type' => $proof_type,//凭证类型
                    'proof_url' => $proof_url,//凭证文件
                ];
                $good = Db::name("good_zixun")->insert($limt);
                if (!$good) {
                    Db::rollback();
                    return error_show(1006, "咨询商品录入失败");
                }
                if (!empty($va)) {
                    $order = Db::name("order_num")->where(["orderCode" => $orderCode, "status" => 1])->where([["wsend_num", ">=", 0]])
                        ->find();
                    if ($order == false) {
                        Db::rollback();
                        return error_show(1006, "采购单关联数据未找到");
                    }
                    foreach ($va as $value) {
                        $temp = [];
                        $addrs = [];
                        if ($value['addr_code'] !== '' && is_array($value['addr_code']) && !empty($value['addr_code'])) {
                            $addrs['provice_code'] = $value['addr_code'][0];
                            $addrs['city_code'] = $value['addr_code'][1];
                            $addrs['area_code'] = $value['addr_code'][2];
                            $addr = json_encode($addrs);
                        } else {
                            $addr = isset($value['addr_code']) ? $value['addr_code'] : '';
                        }
                        $temp['orderCode'] = $orderCode;
                        $temp['contactor'] = $value['contactor'];
                        $temp['mobile'] = $value['mobile'];
                        $temp['addr'] = $value['addr'];
                        $temp['addr_code'] = $addr;
                        $temp['customer_code'] = $zxorder['khNo'];
                        $temp['receipt_quantity'] = $value['receipt_quantity'];
                        $temp['post_fee'] = 0;
                        $temp['is_del'] = 0;
                        $temp['addtime'] = date("Y-m-d H:i:s");
                        $temp['updatetime'] = date("Y-m-d H:i:s");
                        $temp['arrive_time'] = $arrtime;
                        $vmp = Db::name('order_addr')->insert($temp, true);
                        if ($vmp > 0) {
                            $outCode = makeNo("DF");
                            $out = [
                                "orderCode" => $orderCode,
                                "outCode" => $outCode,
                                "apply_id" => $rm,
                                "apply_name" => $ri,
                                "addrid" => $vmp,
                                "post_name" => "",
                                "post_code" => "",
                                "post_fee" => 0,
                                "sendtime" => date("Y-m-d H:i:s"),
                                "send_num" => $value['receipt_quantity'],
                                "check_num" => 0,
                                "error_num" => 0,
                                "wsm_code" => "",
                                "order_type" => 3,
                                "status" => 0,
                                "addtime" => date("Y-m-d H:i:s"),
                                "updatetime" => date("Y-m-d H:i:s")
                            ];
                            $ou = Db::name("order_out")->insert($out);
                            if ($ou == false) {
                                Db::rollback();
                                return error_show(1002, "发货地址添加创建失败");
                            } else {
                                //修改状态,添加待办
                                ActionLog::logAdd($this->post['token'], [
                                    "order_code" => $outCode,//出库单号
                                    "status" => 0,//这里的status是之前的值
                                    "action_remark" => '',//备注
                                    "action_type" => "create"//新建create,编辑edit,更改状态status
                                ], "CKD", 0, $out);

                                ProcessOrder::AddProcess($this->post['token'], [
                                    "order_type" => 'CKD',
                                    "order_code" => $outCode,//出库单号
                                    "order_id" => Db::name("order_out")->getLastInsID(),
                                    "order_status" => 0, "before_status" => 0
                                ]);

                                //将发货编号添加到台账中
                                $standing_book_data['outCode'][] = $outCode;
                            }
                            $order['send_num'] += $value['receipt_quantity'];
                            $order['wsend_num'] -= $value['receipt_quantity'];
                            if ($order['wsend_num'] < 0) {
                                Db::rollback();
                                return error_show(1002, "发货数量已超出总数");
                            }
                            $ups = Db::name("order_num")->save($order);
                            if ($ups) {
                                $tep = [
                                    "cgdNo" => $order['cgdNo'],
                                    "outCode" => $outCode,
                                    "send_num" => $value['receipt_quantity'],
                                    "status" => 1,
                                    "addtime" => date("Y-m-d H:i:s"),
                                    "updatetime" => date("Y-m-d H:i:s")
                                ];
                                $sen = Db::name("order_send")->save($tep);
                                if ($sen == false) {
                                    Db::rollback();
                                    return error_show(1002, "发货地址添加创建失败");
                                }
                            }

                        } else {
                            Db::rollback();
                            return error_show(1002, "发货地址添加创建失败");
                        }
                    }
                }

                //处理台账
                if (isset($standing_book_data['outCode'])) {
                    Db::execute("UPDATE `wsm_standing_book` SET `outCode`=CONCAT(`outCode`,'," . implode(',', $standing_book_data['outCode']) . "'),`updatetime`='" . date('Y-m-d H:i:s') . "' WHERE `infoNo`='{$standing_book_data['infoNo']}'");
                    unset($standing_book_data['outCode']);
                }

                Db::name('standing_book')->where('infoNo', $standing_book_data['infoNo'])->update($standing_book_data);

                Db::commit();
                return error_show(0, "咨询订单创建成功", ["order_code" => $orderCode]);
            }
            Db::rollback();
            return error_show(1002, "咨询订单创建失败");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1003, $e->getMessage());
        }
    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function projectCreate()
    {
        $planNo = isset($this->post['planNo']) && $this->post['planNo'] != "" ? trim($this->post['planNo']) : "";
        if ($planNo == "") {
            return error_show(1004, "参数planNo不能为空");
        }
        $plan = Db::name("project_plan")->where(["planNo" => $planNo, "is_del" => 0])->find();
        if ($plan == false) {
            return error_show(1004, "未找到方案信息");
        }
        $feedbackid = Db::name("project_plan_rela")->where(["planNo" => $planNo, "is_del" => 0])->column("feedback_id,sale_price,sale_num");
        if ($feedbackid == false) {
            return error_show(1004, "未找到方案反馈信息");
        }
        $project = Db::name("project")->where(["projectNo" => $plan['projectNo'], "is_del" => 0])->find();
        if ($project == false) {
            return error_show(1004, "未找到方案信息");
        }
        $arrtime = isset($this->post['arrtime']) && $this->post['arrtime'] != "" ? $this->post['arrtime'] : "";
        if ($arrtime == "") {
            return error_show(1002, "参数arrtime不能为空");
        }
        $planinfo = isset($this->post['planinfo']) && !empty($this->post['planinfo']) ? $this->post['planinfo'] : "";
        if ($planinfo == "") {
            return error_show(1002, "参数planinfo不能为空");
        }
        $token = isset($this->post['token']) && $this->post['token'] != "" ? trim($this->post['token']) : "";
        if ($token == "") {
            return error_show(102, "参数token不能为空");
        }
        $apply_id = GetUserInfo($token);
        if (empty($apply_id) || $apply_id['code'] != 0) {
            return error_show(102, "申请人数据不存在");
        }
        $rm = isset($apply_id["data"]['id']) ? $apply_id["data"]['id'] : "";
        $ri = isset($apply_id["data"]['nickname']) ? $apply_id["data"]['nickname'] : "";
        Db::startTrans();
        try {
            $plan = Db::name("project_plan")->where(["planNo" => $planNo, "is_del" => 0])->lock(true)->find();
            if ($plan == false) {
                Db::rollback();
                return error_show(1004, "未找到方案信息");
            }
            $feedid = array_column($feedbackid, "feedback_id");
            foreach ($planinfo as $key => $value) {
                $good = [];
                $feedback = Db::name("project_feedback")->where(["id" => $value['feedback_id'], "projectNo" => $plan['projectNo'],
                    "is_del" => 0])->find();
                if ($feedback == false) {
                    Db::rollback();
                    return error_show(1002, "反馈数据未找到");
                }
                $key = array_search($feedback['id'], $feedid);
                $price = $feedbackid[$key];
                $good['spuCode'] = $feedback['spuCode'];
                $good['skuCode'] = $feedback['skuCode'];
                $good['good_num'] = $price['sale_num'];
                $good['sendtype'] = $value['sendtype'];
                $good['sale_price'] = $price['sale_price'];
                $good['origin_price'] = $feedback['origin_price'];
                $good['companyNo'] = $project['companyNo'];
                $good['customerNo'] = $project['khNo'];
                $good['pgNo'] = $feedback['pgNo'];
                $good['platform_id'] = $project['platform_id'];
                $good['arrtime'] = $arrtime;
                $good['rm'] = $rm;
                $good['ri'] = $ri;
                $good['send_num'] = 0;

                $standing_book_data = ['projectNo' => $plan['projectNo'], 'updatetime' => date('Y-m-d H:i:s')];
                if ($value['sendtype'] == 1) {
                    if (!isset($value['addrlist']) || empty($value['addrlist'])) {
                        Db::rollback();
                        return error_show(1002, "订单地址不能为空");
                    }
                    $good['addrlist'] = $value['addrlist'];
                    $good['send_num'] = array_sum(array_column($value['addrlist'], "receipt_quantity"));
                }
                if ($feedback['data_source'] == 1) {

                    $feed = $this->project_good($good, $standing_book_data);
                    if ($feed !== true) {
                        Db::rollback();
                        switch ($feed) {
                            case 1:
                                $msg = '库存不足';
                                break;
                            case 2:
                                $msg = '库存更新失败';
                                break;
                            case 3:
                                $msg = '关联采购失败';
                                break;
                            case 4:
                                $msg = '商品信息未找到';
                                break;
                            default:
                                $msg = '咨询订单生成失败';

                        }
                        return error_show(1002, $msg);
                    }
                } else {
                    $feed = $this->project_zx($good, $standing_book_data);
                    if ($feed == false) {
                        Db::rollback();
                        return error_show(1002, "咨询订单生成失败");
                    }
                }
                $old_fk_status = $feedback['status'];
                $fed = Db::name("project_feedback")->where($feedback)->save(['status' => 2, "updatetime" => date("Y-m-d H:i:s")]);
                if ($fed == false) {
                    Db::rollback();
                    return error_show(1002, "项目订单生成失败");
                }

                //处理台账(一个项目会生成多个销售订单,第一个更新,其余的新增)
                //项目创建时已有供应商和企业,不能修改
                if (isset($standing_book_data['companyNo'])) unset($standing_book_data['companyNo']);
                if (isset($standing_book_data['customer_code'])) unset($standing_book_data['customer_code']);
                if (isset($standing_book_data['outCode'])) $standing_book_data['outCode'] = implode(',', $standing_book_data['outCode']);

                //普通商品
                if ($feedback['data_source'] == 1) {
                    if ($key == 0) Db::name('standing_book')->where('projectNo', $plan['projectNo'])->update($standing_book_data);
                    else {
                        $temp = Db::name('standing_book')->where('projectNo', $plan['projectNo'])->find();
                        if (!empty($temp)) {
                            unset($temp['id']);
                            $temp = array_merge($temp, $standing_book_data);
                            $temp['standBookNo'] = makeNo('IO');
                            Db::name('standing_book')->insert($temp);
                        }
                    }

                } else {
                    //项目类竞价单
                    Db::name('standing_book')->where(['projectNo' => $plan['projectNo'], 'infoNo' => $standing_book_data['infoNo']])->update($standing_book_data);
                }

            }
            $old_plan_status = $plan['status'];
//            $plan['status']=2;
//            $plan['updatetime']=date("Y-m-d H:i:s");
            $in = Db::name("project_plan")->where($plan)->save(['status' => 2, "updatetime" => date("Y-m-d H:i:s")]);
            if ($in == false) {
                Db::rollback();
                return error_show(1002, "项目订单生成失败");
            } else {
                //修改状态,添加待办,只记录动作
                ActionLog::logAdd($this->post['token'], [
                    "order_code" => $planNo,//编码
                    "status" => $old_plan_status,//这里的status是之前的值
                    "action_remark" => '',//备注
                    "action_type" => "edit"//新建create,编辑edit,更改状态status
                ], "PRP", 2, $plan);
            }
            $old_project_status = $project["status"];
//            $project["status"]=6;
//            $project['updatetime']=date("Y-m-d H:i:s");
            $pr = Db::name("project")->where($project)->save(["updatetime" => date("Y-m-d H:i:s"), "status" => 6]);
            if ($pr == false) {
                Db::rollback();
                return error_show(1002, "项目订单生成失败");
            } else {
                //修改状态,添加待办
                ActionLog::logAdd($this->post['token'], [
                    "order_code" => $project['projectNo'],//项目编码
                    "status" => $old_project_status,//这里的status是之前的值
                    "action_remark" => '',//备注
                    "action_type" => "status"//新建create,编辑edit,更改状态status
                ], "PRO", 6, $project);

                ProcessOrder::AddProcess($this->post['token'], [
                    "order_type" => 'PRO',
                    "order_code" => $project['projectNo'],
                    "order_id" => $project['id'],
                    "order_status" => 6, "before_status" => $old_project_status
                ]);
            }
            //修改状态,添加待办,只记录动作
            ActionLog::logAdd($this->post['token'], [
                "order_code" => $project['projectNo'],//编码,这里是project的编码
                "status" => 1,//这里的status是之前的值
                "action_remark" => '',//备注
                "action_type" => "create"//新建create,编辑edit,更改状态status
            ], "PRT", 2, $this->post);
            $process = ["order_code" => $project['projectNo'], "order_id" => $project['id'], "order_status" => 2, "order_type" => "PRT", "before_status" => 1];
            ProcessOrder::AddProcess($this->post['token'], $process);

            Db::commit();
            return app_show(0, "咨询订单生成成功");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1002, $e->getMessage());
        }

    }

    /**
     * @param $data
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     */

    public function project_zx($data, array &$standing_book_data = [])
    {
        $goodinfo = Db::name("consult_bids")->where(["spuCode" => $data['spuCode'], "is_del" => 0])->find();
        if ($goodinfo == false) {
            return false;
        }
        $orderCode = makeNo("QR");
        $cgd = [
            "supplierNo" => $goodinfo['supplierNo'],
            "companyNo" => $data['companyNo'],
            "spuCode" => $data['spuCode'],
            "skuCode" => "",
            "orderCode" => $orderCode,
            "good_name" => $goodinfo['good_name'],
            "sale_price" => $goodinfo['total_fee'],
            "total_fee" => round($goodinfo['total_fee'] * $data['good_num'], 2),
            "pakge_fee" => $goodinfo['pakge_fee'],
            "cert_fee" => $goodinfo['cert_fee'],
            "open_fee" => $goodinfo['open_fee'],
            "cost_fee" => $goodinfo['cost_fee'],
            "mark_fee" => $goodinfo['mark_fee'],
            "demo_fee" => $goodinfo['demo_fee'],
            "nake_fee" => $goodinfo['nake_fee'],
            "good_num" => $data['good_num'],
            "delivery_fee" => $goodinfo['delivery_fee'],
            "createrid" => $goodinfo['createrid'],
            "creater" => $goodinfo['creater'],
            "weight" => $goodinfo['good_weight'],
            "gold_price" => $goodinfo['gold_price'],
            "good_type" => 1,
            "order_type" => 3,//3咨询商品
            "order_source" => 3,//项目
            "send_way" => $goodinfo['send_way'],

        ];
        $datas = [
            "orderCode" => $orderCode,
            "good_code" => $data['spuCode'],
            "skuCode" => "",
            "customer_code" => $data['customerNo'],
            "good_name" => isset($goodinfo['good_name']) && $goodinfo['good_name'] !== '' ? $goodinfo['good_name'] : '',
            "good_num" => $data['good_num'],
            "cat_id" => $goodinfo['cat_id'],
            "apply_id" => $data['rm'],
            "apply_name" => $data['ri'],
            "origin_price" => $goodinfo['total_fee'],
            "sale_price" => $data['sale_price'],
            "post_fee" => 0,
            "status" => 0,
            "send_num" => 0,
            "wsend_num" => $data['good_num'],
            "send_status" => 1,
            "good_type" => 1,
            "send_type" => $data['sendtype'],
            "supplierNo" => $data['companyNo'],
            "is_del" => 0,
            "zxNo" => $data["pgNo"],
            "platform_order" => "",
            "platform_id" => $data['platform_id'],
            "remark" => "",
            "is_stock" => 0,
            "is_activity" => 0,
            "activity_code" => '',
            "proof_id" => 0,
            "order_type" => 3,//咨询商品
            "order_source" => 3,//项目
            'good_weight' => $goodinfo['good_weight'],
            'gold_price' => $goodinfo['gold_price'],
            'cost_price' => $goodinfo['sale_cost_fee'],
            'diff_weight' => 0,
            'diff_fee' => 0,
            "addtime" => date("Y-m-d H:i:s"),
            "updatetime" => date("Y-m-d H:i:s"),
            'total_price' => round($data['sale_price'] * $data['good_num'], 2),
        ];
        $datainfo = Db::name('sale')->insert($datas, true);
        if ($datainfo > 0) {
            $standing_book_data['sale_id'] = $datainfo;
            $standing_book_data['customer_code'] = $datas['customer_code'];
            $standing_book_data['infoNo'] = $goodinfo['infoNo'];
            //修改状态,添加待办
            ActionLog::logAdd($this->post['token'], [
                "order_code" => $orderCode,//项目编码
                "status" => 0,//这里的status是之前的值
                "action_remark" => '',//备注
                "action_type" => "status"//新建create,编辑edit,更改状态status
            ], "XSQRD", 0, $datas);

            ProcessOrder::AddProcess($this->post['token'], [
                "order_type" => 'XSQRD',
                "order_code" => $orderCode,
                "order_id" => $datainfo,
                "order_status" => 0, "before_status" => 0
            ]);
            $bol = $this->createCgd($cgd, $standing_book_data);
            if ($bol == false) {
                return false;
            }
            $bidstatus = $goodinfo['status'];
            $goodinfo['status'] = 6;
            $goodinfo['updatetime'] = date("Y-m-d H:i:s");
            $sa = Db::name("consult_bids")->save($goodinfo);
            if ($sa == false) {
                return false;
            }
            //修改状态,添加待办
            ActionLog::logAdd($this->post['token'], [
                "order_code" => $goodinfo['bidNo'],//项目编码
                "status" => $bidstatus,//这里的status是之前的值
                "action_remark" => '',//备注
                "action_type" => "status"//新建create,编辑edit,更改状态status
            ], "FKD", 6, $datas);

            $zxorder = Db::name("consult_order")->where(["zxNo" => $goodinfo["zxNo"], "is_del" => 0])->find();
            if ($zxorder == false) {
                return false;
            }
            $limt = [
                "spuCode" => $goodinfo['spuCode'],
                "good_name" => $goodinfo['good_name'],
                "brand_id" => $goodinfo['brand_id'],
                "good_unit" => $goodinfo['unit_id'],
                "cat_id" => $goodinfo['cat_id'],
                "good_type" => 0,
                "moq" => 1,
                "customized" => $goodinfo['work_day'],
                "tax" => $goodinfo['tax'],
                "supplierNo" => $goodinfo["supplierNo"],
                "is_auth" => 0,
                "craft_desc" => $goodinfo['good_name'],
                "good_remark" => "",
                "good_img" => $goodinfo['good_img'],
                "good_thumb_img" => "",
                "good_info_img" => "",
                "platform_id" => $zxorder['platform_id'],
                "specinfo" => $goodinfo['specinfo'],
                "work_day" => $goodinfo['work_day'],
                "noble_metal" => $goodinfo['metal_id'],
                "is_gold_price" => $goodinfo['is_gold_price'],
                "good_weight" => $goodinfo['good_weight'],
                "companyNo" => $zxorder['companyNo'],
                "config" => $goodinfo['config'],
                "other_config" => $goodinfo['other_config'],
                "weight" => $goodinfo['weight'],
                "is_diff" => $goodinfo['is_diff'],
                "supply_area" => $goodinfo['supply_area'],
                "pay_way" => $goodinfo['pay_way'],
                "send_way" => $goodinfo['send_way'],
                "status" => 1,
                "is_del" => 0,
                "createrid" => $goodinfo['createrid'],
                "creater" => $goodinfo['creater'],
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s")
            ];
            $good = Db::name("good_zixun")->insert($limt);
            if (!$good) {
                return false;
            }
            if ($data['sendtype'] == 1 && !empty($data['addrlist'])) {
                $order = Db::name("order_num")->where(["orderCode" => $orderCode, "status" => 1])->where([["wsend_num", ">=", 0]])
                    ->find();
                if ($order == false) {
                    return false;
                }
                foreach ($data['addrlist'] as $value) {
                    $temp = [];
                    $addrs = [];
                    if ($value['addr_code'] !== '' && is_array($value['addr_code']) && !empty($value['addr_code'])) {
                        $addrs['provice_code'] = $value['addr_code'][0];
                        $addrs['city_code'] = $value['addr_code'][1];
                        $addrs['area_code'] = $value['addr_code'][2];
                        $addr = json_encode($addrs);
                    } else {
                        $addr = isset($value['addr_code']) ? $value['addr_code'] : '';
                    }
                    $temp['orderCode'] = $orderCode;
                    $temp['contactor'] = $value['contactor'];
                    $temp['mobile'] = $value['mobile'];
                    $temp['addr'] = $value['addr'];
                    $temp['addr_code'] = $addr;
                    $temp['customer_code'] = $data['companyNo'];
                    $temp['receipt_quantity'] = $value['receipt_quantity'];
                    $temp['post_fee'] = 0;
                    $temp['is_del'] = 0;
                    $temp['addtime'] = date("Y-m-d H:i:s");
                    $temp['updatetime'] = date("Y-m-d H:i:s");
                    $temp['arrive_time'] = $data['arrtime'];
                    $vmp = Db::name('order_addr')->insert($temp, true);
                    if ($vmp > 0) {
                        $outCode = makeNo("DF");
                        $out = [
                            "orderCode" => $orderCode,
                            "outCode" => $outCode,
                            "apply_id" => $data['rm'],
                            "apply_name" => $data['ri'],
                            "addrid" => $vmp,
                            "post_name" => "",
                            "post_code" => "",
                            "post_fee" => 0,
                            "sendtime" => date("Y-m-d H:i:s"),
                            "send_num" => $value['receipt_quantity'],
                            "check_num" => 0,
                            "error_num" => 0,
                            "wsm_code" => "",
                            "order_type" => 3,//3咨询商品
                            "status" => 0,
                            "addtime" => date("Y-m-d H:i:s"),
                            "updatetime" => date("Y-m-d H:i:s")
                        ];
                        $ou = Db::name("order_out")->insert($out);
                        if ($ou == false) {
                            return false;
                        }
                        //修改状态,添加待办
                        ActionLog::logAdd($this->post['token'], [
                            "order_code" => $outCode,//项目编码
                            "status" => 0,//这里的status是之前的值
                            "action_remark" => '',//备注
                            "action_type" => "status"//新建create,编辑edit,更改状态status
                        ], "CKD", 0, $out);

                        ProcessOrder::AddProcess($this->post['token'], [
                            "order_type" => 'CKD',
                            "order_code" => $outCode,
                            "order_id" => Db::name("order_out")->getLastInsID(),
                            "order_status" => 0, "before_status" => 0
                        ]);
                        $order['send_num'] += $value['receipt_quantity'];
                        $order['wsend_num'] -= $value['receipt_quantity'];
                        if ($order['wsend_num'] < 0) {
                            return false;
                        }
                        $ups = Db::name("order_num")->save($order);
                        if ($ups) {
                            $tep = [
                                "cgdNo" => $order['cgdNo'],
                                "outCode" => $outCode,
                                "send_num" => $value['receipt_quantity'],
                                "status" => 1,
                                "addtime" => date("Y-m-d H:i:s"),
                                "updatetime" => date("Y-m-d H:i:s")
                            ];
                            $sen = Db::name("order_send")->save($tep);
                            if ($sen == false) {
                                return false;
                            }

                            $standing_book_data['outCode'][] = $outCode;
                        }

                    } else {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function project_good($data, array &$standing_book_data = [])
    {
        $good = Db::name('good')
            ->alias("a")
            ->leftJoin("good_platform b", "a.spuCode=b.spuCode")
            ->where(["b.skuCode" => $data['skuCode'], "a.is_del" => 0, "b.is_del" => 0])
            ->field("a.*,b.skuCode,b.platform_code")->find();

        if ($good == false) {
            return 4; //商品信息未找到
        }
        $goodlass = Db::name("good_ladder")->where(["skuCode" => $data['skuCode'], "is_del" => 0, "status" => 1])->where([["min_num",
            "<=", $data['good_num']]])->order("min_num desc")->find();
        if ($goodlass == false) {
            return 4;//商品信息未找到
        }
        $sale_price = $goodlass['sale_price'];
        $origin_price = 0;
        if ($good['is_stock'] == 0) {
            $origin = Db::name("good_nake")->where([["spuCode", "=", $data['spuCode']], ["min_num", "<=", $data['good_num']],
                ["is_del", "=", 0]])->order("min_num desc")->find();
            if ($origin == false) {
                return 4;//商品信息未找到
            }
            $origin_price = $origin['nake_total'];
        }
        if ($good['is_gold_price'] == 1 && $good['is_stock'] == 0) {
            $gold = Db::name("gold_price1")
                ->field('id,price')
                ->where(["type" => $good['noble_metal'], "is_del" => 0, "status" => 1])
                ->order("addtime desc")
                ->find();

            //$saleprice(最终售价) = (打样费/购买数量 + 开模费/购买数量 + 商品重量* 最新金价 + 工艺费* 商品重量+包装费+加标费+证书费+产品裸价+物流费)/(1-成本售价/100);
            $sale_price = $good['demo_fee'] / $data['good_num'] + $good['open_fee'] / $data['good_num'] + $good['noble_weight'] * $gold["price"] + $goodlass['cost_fee'] * $good['noble_weight'] + $origin['package_fee'] + $origin['mark_fee'] + $origin['cert_fee'] + $origin['nake_fee'] + $origin['delivery_fee'];
            $good['cgd_gold_price'] = $gold["price"];
        }

        $orderCode = makeNo("QR");
        $datas = [
            "orderCode" => $orderCode,
            "good_code" => $data['spuCode'],
            "skuCode" => $data['skuCode'],
            "customer_code" => $data['customerNo'],
            "good_name" => isset($good['good_name']) && $good['good_name'] !== '' ? $good['good_name'] : '',
            "good_num" => $data['good_num'],
            "cat_id" => $good['cat_id'],
            "apply_id" => $data['rm'],
            "apply_name" => $data['ri'],
            "origin_price" => $origin_price,
            "sale_price" => $sale_price,
            "post_fee" => 0,
            "status" => 0,
            "send_num" => 0,
            "wsend_num" => $data['good_num'],
            "send_status" => 1,
            "good_type" => 1,
            "send_type" => $data['sendtype'],
            "supplierNo" => $data['companyNo'],
            "is_del" => 0,
            "zxNo" => $data["pgNo"],
            "platform_order" => "",
            "platform_id" => $data['platform_id'],
            "remark" => "",
            "is_stock" => $good['is_stock'],
            "is_activity" => 0,
            "activity_code" => '',
            "proof_id" => 0,
            "order_type" => $good['is_stock'] == 1 ? 1 : 2,//1备库,2非库存品
            'order_source' => 3,//3项目
            'good_weight' => $good['noble_weight'],
            'gold_price' => isset($good['cgd_gold_price']) ? $good['cgd_gold_price'] : 0,
            'cost_price' => $goodlass['cost_fee'],
            'diff_weight' => 0,
            'diff_fee' => 0,
            "addtime" => date("Y-m-d H:i:s"),
            "updatetime" => date("Y-m-d H:i:s"),
            'total_price' => round($sale_price * $data['good_num'], 2),
        ];
        $datainfo = Db::name('sale')->insert($datas, true);
        if ($datainfo > 0) {

            $standing_book_data['sale_id'] = $datainfo;
            //修改状态,添加待办
            ActionLog::logAdd($this->post['token'], [
                "order_code" => $orderCode,//项目编码
                "status" => 0,//这里的status是之前的值
                "action_remark" => '',//备注
                "action_type" => "status"//新建create,编辑edit,更改状态status
            ], "XSQRD", 0, $datas);

            ProcessOrder::AddProcess($this->post['token'], [
                "order_type" => 'XSQRD',
                "order_code" => $orderCode,
                "order_id" => $datainfo,
                "order_status" => 0, "before_status" => 0
            ]);
            $cgd = [
                "supplierNo" => $good['supplierNo'],
                "companyNo" => $data['companyNo'],
                "orderCode" => $orderCode,
                "spuCode" => $good['spuCode'],
                "skuCode" => $good['skuCode'],
                "good_name" => $good['good_name'],
                "sale_price" => $origin_price,
                "total_fee" => $origin_price * $data['good_num'],
                "pakge_fee" => isset($origin['package_fee']) ? $origin['package_fee'] : 0,
                "cert_fee" => isset($origin['cert_fee']) ? $origin['cert_fee'] : 0,
                "open_fee" => $good['open_fee'],
                "cost_fee" => isset($origin['cost_fee']) ? $origin['cost_fee'] : 0,
                "mark_fee" => isset($origin['mark_fee']) ? $origin['mark_fee'] : 0,
                "demo_fee" => $good['demo_fee'],
                "nake_fee" => isset($origin['nake_fee']) ? $origin['nake_fee'] : 0,
                "delivery_fee" => isset($origin['delivery_fee']) ? $origin['delivery_fee'] : 0,
                "good_num" => $data['good_num'],
                "good_type" => 1,
                "weight" => $good['noble_weight'],
                "gold_price" => isset($good['cgd_gold_price']) ? $good['cgd_gold_price'] : 0,
                "createrid" => $good['createrid'],
                "creater" => $good['creater'],
                "order_type" => $good['is_stock'] == 1 ? 1 : 2,
                'order_source' => 3,//3项目
                'send_way' => 2
            ];
            if ($good['is_stock'] == 0) {
                $bol = $this->createCgd($cgd, $standing_book_data);
                if ($bol == false) {
                    return 3;//关联采购失败
                }
            } else {

                $stock = Db::name("good_stock")->alias("a")->leftJoin("warehouse_info b", "a.wsm_code=b.wsm_code")->where
                (["spuCode" => $good['spuCode'], "a.is_del" => 0, "a.status" => 1, "b.wsm_type" => 5, "b.companyNo" => $data['companyNo']])->field("a.id,a.usable_stock,a.wait_out_stock")->find();
                if ($stock == false || $stock['usable_stock'] < $data['good_num']) {
                    return 1; //库存不足
                }

                $bol = $this->RelaCgd(['orderCode' => $orderCode, "good_num" => $data['good_num'], "spuCode" => $good['spuCode'], "companyNo" => $data['companyNo'], "cost_fee" => $goodlass['cost_fee'], 'order_type' => $cgd['order_type'], 'order_source' => $cgd['order_source']], $standing_book_data);
                if ($bol == false) {
                    return 3;//关联采购失败
                }
                if (isset($stock)) {
                    $stck = [
                        "usable_stock" => $stock['usable_stock'] - $data['good_num'],
                        "wait_out_stock" => $stock['wait_out_stock'] + $data['good_num'],
                        "updatetime" => date("Y-m-d H:i:s")
                    ];
                    $upad = Db::name("good_stock")->where($stock)->update($stck);
                    if ($upad == false) {
                        return 2; //库存更新失败
                    }
                    //商品变动日志表,good_log_code字段存储采购单号
                    $good_data[] = ['good_log_code' => $orderCode, "stock_id" => $stock['id'], "type" => 2, 'stock' => $data['good_num'], "stock_name" => "usable_stock"];
                    $good_data[] = ['good_log_code' => $orderCode, "stock_id" => $stock['id'], "type" => 1, 'stock' => $data['good_num'], "stock_name" => "wait_out_stock"];
                    GoodLog::LogAdd($this->post['token'], $good_data, "XSQRD");
                }

            }
            if ($data['sendtype'] == 1 && !empty($data['addrlist'])) {
                foreach ($data['addrlist'] as $value) {
                    $temp = [];
                    $addrs = [];
                    if ($value['addr_code'] !== '' && is_array($value['addr_code']) && !empty($value['addr_code'])) {
                        $addrs['provice_code'] = $value['addr_code'][0];
                        $addrs['city_code'] = $value['addr_code'][1];
                        $addrs['area_code'] = $value['addr_code'][2];
                        $addr = json_encode($addrs);
                    } else {
                        $addr = isset($value['addr_code']) ? $value['addr_code'] : '';
                    }
                    $temp['orderCode'] = $orderCode;
                    $temp['contactor'] = $value['contactor'];
                    $temp['mobile'] = $value['mobile'];
                    $temp['addr'] = $value['addr'];
                    $temp['addr_code'] = $addr;
                    $temp['customer_code'] = $data['companyNo'];
                    $temp['receipt_quantity'] = $value['receipt_quantity'];
                    $temp['post_fee'] = 0;
                    $temp['is_del'] = 0;
                    $temp['addtime'] = date("Y-m-d H:i:s");
                    $temp['updatetime'] = date("Y-m-d H:i:s");
                    $temp['arrive_time'] = $data['arrtime'];
                    $vmp = Db::name('order_addr')->insert($temp, true);
                    if ($vmp > 0) {
                        $standing_book_data['customer_code'] = $temp['customer_code'];
//                            if ($good['is_stock'] == 1) {
                        $order = Db::name("order_num")->where(["orderCode" => $orderCode, "status" => 1])->where([["wsend_num", ">=", 0]])
                            ->lock(true)->find();
                        if ($order == false) {
                            return 3;
                        }
                        $num = $value['receipt_quantity'];
                        $outCode = makeNo("DF");
                        $order['wsend_num'] -= $num;
                        $order['send_num'] += $num;
                        $or = Db::name("order_num")->save($order);
                        if ($or == false) {

                            return 3;
                        }
                        $tep = [
                            "cgdNo" => $order['cgdNo'],
                            "outCode" => $outCode,
                            "send_num" => $num,
                            "status" => 1,
                            "addtime" => date("Y-m-d H:i:s"),
                            "updatetime" => date("Y-m-d H:i:s")
                        ];
                        $sen = Db::name("order_send")->save($tep);
                        if ($sen == false) {

                            return 3;
                        }
                        $cgdinfo = Db::name("purchease_order")->where(["cgdNo" => $order['cgdNo']])->find();
                        if ($cgdinfo == false) {

                            return 4;
                        }
                        $out = [
                            "orderCode" => $orderCode,
                            "outCode" => $outCode,
                            "apply_id" => $data['rm'],
                            "apply_name" => $data['ri'],
                            "addrid" => $vmp,
                            "post_name" => "",
                            "post_code" => "",
                            "post_fee" => 0,
                            "sendtime" => date("Y-m-d H:i:s"),
                            "send_num" => $num,
                            "check_num" => 0,
                            "error_num" => 0,
                            "wsm_code" => $cgdinfo['wsm_code'],
                            "order_type" => 1,
                            "status" => $good['is_stock'] == 1 ? 1 : 0,
                            "addtime" => date("Y-m-d H:i:s"),
                            "updatetime" => date("Y-m-d H:i:s")
                        ];
                        $ou = Db::name("order_out")->insert($out);
                        if ($ou == false) {
                            return 0;
                        } else {
                            $standing_book_data['outCode'][] = $outCode;
                            //修改状态,添加待办
                            ActionLog::logAdd($this->post['token'], [
                                "order_code" => $outCode,//出库单号
                                "status" => 0,//这里的status是之前的值
                                "action_remark" => '',//备注
                                "action_type" => "create"//新建create,编辑edit,更改状态status
                            ], "CKD", 0, $out);

                            ProcessOrder::AddProcess($this->post['token'], [
                                "order_type" => 'CKD',
                                "order_code" => $outCode,//出库单号
                                "order_id" => Db::name("order_out")->getLastInsID(),
                                "order_status" => 0, "before_status" => 0
                            ]);
                        }
                    } else {
                        return false;
                    }
                }
            }
//                }
        }

        return true;
    }


    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[] = ['s.is_del', "=", 0];
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] !== "" ? trim($this->post['orderCode']) : "";
        if ($orderCode !== "") {
            $where[] = ['s.orderCode', "like", "%$orderCode%"];
        }
        $apply_name = isset($this->post['apply_name']) && $this->post['apply_name'] !== "" ? trim($this->post['apply_name'])
            : "";
        if ($apply_name !== "") {
            $where[] = ['s.apply_name', "like", "%$apply_name%"];
        }
        $good_name = isset($this->post['good_name']) && $this->post['good_name'] !== "" ? trim($this->post['good_name'])
            : "";
        if ($good_name !== "") {
            $where[] = ['s.good_name', "like", "%$good_name%"];
        }
        $good_code = isset($this->post['good_code']) && $this->post['good_code'] !== "" ? trim($this->post['good_code']) : "";
        if ($good_code !== "") {
            $where[] = ['s.good_code', "like", "%$good_code%"];
        }
        $customer_code = isset($this->post['customer_code']) && $this->post['customer_code'] !== "" ? trim($this->post['customer_code']) : "";
        if ($customer_code !== "") {
            $where[] = ['s.customer_code', "like", "%$customer_code%"];
        }
        $supplierNo = isset($this->post['supplierNo']) && $this->post['supplierNo'] !== "" ? trim($this->post['supplierNo']) : "";
        if ($supplierNo !== "") {
            $where[] = ['s.supplierNo', "like", "%$supplierNo%"];
        }
        $ordertype = isset($this->post['order_type']) && $this->post['order_type'] !== "" ? intval($this->post['order_type'])
            : "";
        if ($ordertype !== "") {
            $where[] = ['s.order_type', "=", $ordertype];
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? trim($this->post['status']) : "";
        if ($status !== "") {
            $where[] = ['s.status', "=", $status];
        }
        $start = isset($this->post['start']) && $this->post['start'] !== "" ? $this->post['start'] : "";
        if ($start != "") {
            $where[] = ["s.addtime", '>=', $start];
        }
        $end = isset($this->post['end']) && $this->post['end'] !== "" ? $this->post['end'] : "";
        if ($end != "") {
            $end .= " 23:59:59";
            $where[] = ["s.addtime", '<=', $end];
        }
        $role = $this->checkRole();
        if (!empty($role['write'])) {
            $where[] = ["s.apply_id", "in", $role['write']];
        }
        $company_name = isset($this->post['company_name']) && $this->post['company_name'] !== "" ? trim($this->post['company_name']) : "";
        if ($company_name !== "") $where[] = ["s.apply_id", 'in', get_company_item_user_by_name($company_name)];
//        if(!empty($role['platform']) ){
//            $where[]=["s.platform_id","in",$role['platform']];
//        }
        $count = Db::name('sale')->alias('s')->where($where)->count();
        $total = ceil($count / $size);
        $page = $page >= $total ? $total : $page;
        $list = Db::name('sale')
            ->alias('s')
            ->field('s.*,u.itemid')
            ->leftJoin("depart_user u", "u.uid=s.apply_id AND u.is_del=0")->where($where)
            ->order("s.addtime desc")
            ->page($page, $size)
            ->cursor();
        $data = [];
        foreach ($list as $value) {
            if ($value['order_type'] == 3) {
                $var = Db::name("good_zixun")->where(["spuCode" => $value['good_code'], "is_del" => 0])->find();
                $value["speclist"] = isset($var['specinfo']) && $var['specinfo'] != "" ? json_decode($var['specinfo'], true) : "";
            } else {
                $var = Db::name('good_platform')->alias('a')->join('good b', 'b.spuCode=a.spuCode', 'left')
                    ->where(['a.skuCode' => $value['skuCode']])->find();
                $spec = Db::name("good_spec")->where(["spuCode" => $var['spuCode'], "is_del" => 0])->select()->toArray();
                $speclist = [];
                if (!empty($spec)) {
                    foreach ($spec as $val) {
                        $temp = [];
                        $temp['id'] = $val['id'];
                        $temp['spuCode'] = $val['spuCode'];
                        $temp['spec_id'] = $val['spec_id'];
                        $temp['spec_value_id'] = $val['spec_value_id'];
                        $sp = Db::name("specs")->where(["id" => $val['spec_id']])->find();
                        $temp['spec_name'] = isset($sp["spec_name"]) ? $sp["spec_name"] : "";
                        $spv = Db::name("spec_value")->where(["id" => $val['spec_value_id']])->find();
                        $temp['spec_value'] = isset($spv["spec_value"]) ? $spv["spec_value"] : "";
                        $speclist[] = $temp;
                    }
                }
                $value["speclist"] = empty($speclist) ? [] : $speclist;
            }

            $value['can'] = isset($var['cat_id']) && $var['cat_id'] != 0 ? made($var['cat_id']) : [];
            $value['supplierName'] = '';
            if ($value['supplierNo'] != "") {
                $supplier = Db::name("business")->where(["companyNo" => $value['supplierNo']])->find();
                $value['supplierName'] = isset($supplier['company']) ? $supplier['company'] : "";
            }
            $value['customerName'] = '';
            if ($value['customer_code'] != "") {
                $supplier = Db::name("customer_info")->where(["companyNo" => $value['customer_code']])->find();
                $value['customerName'] = isset($supplier['companyName']) ? $supplier['companyName'] : "";
            }
            $value['useage'] = "";
            if ($value['use_order'] != 0) {
                $use = Db::name("order_use")->where(["id" => $value['use_order']])->find();
                $value['useage'] = isset($use['order_use']) ? $use['order_use'] : "";
            } else {
                $value['use_order'] = '';
            }
            $value['good_num'] -= $value['th_num'];
            $value['send_num'] -= $value['th_num'];
            $value['total_price'] = round($value['total_price'] - $value['th_fee'], 2);
            $value['company_name'] = implode('/', array_column(GetPart($value['itemid']), 'name'));
            $data[] = $value;
        }
        return app_show(0, "获取成功", ['list' => $data, 'count' => $count]);
    }

    public function edit()
    {
        $token = isset($this->post['token']) && $this->post['token'] !== "" ? trim($this->post['token']) : "";
        $id = isset($this->post['id']) && $this->post['id'] !== "" ? trim($this->post['id']) : "";
        if ($id == "") {
            return error_show(1002, "参数id不能为空");
        }
        $etid = Db::name("sale")->where(["id" => $id, "is_del" => 0])->find();
        if (empty($etid)) {
            return error_show(1002, "未找到数据");
        }
//    $orderCode=isset($this->post['orderCode']) && $this->post['orderCode'] !=="" ? trim($this->post['orderCode']) :"";
//    if($orderCode==""){
//        return error_show(1002,"销售单code不能为空");
//    }
        $good_code = isset($this->post['good_code']) && $this->post['good_code'] !== "" ? trim($this->post['good_code']) : "";
        if ($good_code == "") {
            return error_show(1002, "商品code不能为空");
        }
        $ct = Db::name('good')->alias('a')->join('good_type b', 'b.good_code=a.good_code', 'left')
            ->where(['b.type_code' => $good_code])->find();
        if ($ct == "") {
            return error_show(1002, "未找到商品数据");
        }
        $customer_code = isset($this->post['customer_code']) && $this->post['customer_code'] !== "" ? trim($this->post['customer_code']) : "";
        if ($customer_code == "") {
            return error_show(1002, "客户code不能为空");
        }
        $customer = Db::name("customer_info")->where(["companyNo" => $customer_code])->find();
        if ($customer == false) {
            return error_show(1004, "未找到客户数据");
        }
        $supplierNo = $this->post['supplierNo'] && $this->post['supplierNo'] !== "" ? trim($this->post['supplierNo']) : "";
        if ($supplierNo == "") {
            return error_show(1002, "参数supplierNo不能为空");
        }
        $supplier = Db::name("supplier")->where(["code" => $supplierNo])->find();
        if ($supplier == false) {
            return error_show(1004, "未找到平台供应商数据");
        }
        $apply_id = GetUserInfo($token);
        if (empty($apply_id) || $apply_id['code'] != 0) {
            return error_show(1002, "申请人数据不存在");
        }
        $rm = isset($apply_id["data"]['id']) ? $apply_id["data"]['id'] : "";
        $ri = isset($apply_id["data"]['nickname']) ? $apply_id["data"]['nickname'] : "";
        //  $good_name = isset($this->post['good_name']) && $this->post['good_name'] !== "" ? trim
        //($this->post['good_name']) : "";
        // $good_num = isset($this->post['good_num']) && $this->post['good_num'] !== "" ? intval
        //($this->post['good_num']) : "";
        //  $origin_price = isset($this->post['origin_price']) && $this->post['origin_price'] !== "" ? intval
//    ($this->post['origin_price']) : "";
//        $sale_price = isset($this->post['sale_price']) && $this->post['sale_price'] !== "" ? trim($this->post['sale_price']) : "";
//        $total_price = isset($this->post['total_price']) && $this->post['total_price'] !== "" ? trim($this->post['total_price']) : "";
//        $post_fee = isset($this->post['post_fee']) && $this->post['post_fee'] !== "" ? trim($this->post['post_fee']) : "";
//        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "";

        $vr = isset($this->post['order_addr']) && $this->post['order_addr'] !== "" ? $this->post['order_addr'] : "";
        if ($vr == "") {
            return error_show(1002, "参数order_addr不能为空");
        }
        $vi = isset($this->post['good_stock']) && $this->post['good_stock'] !== "" ? $this->post['good_stock'] : "";
        if ($vi == "") {
            return error_show(1002, "参数good_stock不能为空");
        }
        $good_num = intval(array_sum(array_column($vi, "num")));
        Db::startTrans();
        try {
            $datn = [
                "id" => $id,
                "good_code" => $good_code,
                "customer_code" => $customer_code,
                "good_num" => $good_num,
                "supplierNo" => $supplierNo,
                "apply_id" => $rm,
                "apply_name" => $ri,
                "is_del" => 0,
                "updatetime" => date("Y-m-d H:i:s")
            ];
            $datninfo = Db::name('sale')->where(['id' => $id, 'is_del' => 0])->save($datn);
            if ($datninfo > 0) {
                $stn = ["order_code" => $etid['orderCode'], "status" => $etid['status'], "action_remark" => '', "action_type" => "edit"];
                ActionLog::logAdd($this->post['token'], $stn, "XSQRD", $etid['status'], $datn);
//                $order=["order_type"=>'XSQRD',"order_code"=>$etid['orderCode'],"order_id"=>$id,"order_status"=>$etid['status'],"before_status"=> 0];
//                ProcessOrder::AddProcess($this->post['token'],$order);

                //更新台账
                Db::name('standing_book')
                    ->where('orderCode', $etid['orderCode'])
                    ->update([
                        'customer_code' => $customer_code,
                        'supplierNo' => $supplierNo,
                        'updatetime' => date("Y-m-d H:i:s")
                    ]);

                foreach ($vi as $ion) {
                    $iten = [];
                    isset($ion['id']) && $ion['id'] !== "" ? $iten['id'] = $ion['id'] : '';
                    $iten['orderCode'] = $etid['orderCode'];
                    $iten['wsm_code'] = $ion['wsm_code'];
                    $iten['stock_id'] = 0;
                    $iten['num'] = $ion['num'];
                    $iten['status'] = 1;
                    $iten['sale_price'] = $ct['original_price'];
                    isset($ion['id']) && $ion['id'] !== "" ? '' : $iten['addtime'] = date("Y-m-d H:i:s");
                    $iten['updatetime'] = date("Y-m-d H:i:s");

                    $vp = Db::name('sale_info')->save($iten);
                    if ($vp == false) {
                        Db::rollback();
                        return error_show(1002, "更新失败");
                    }
                }


                foreach ($vr as $value) {
                    $temp = [];
                    isset($value['id']) && $value['id'] !== "" ? $temp['id'] = $value['id'] : '';
                    $temp['orderCode'] = $etid['orderCode'];
                    $temp['contactor'] = $value['contactor'];
                    $temp['mobile'] = $value['mobile'];
                    $temp['addr'] = $value['addr'];
                    $temp['addr_code'] = $value['addr_code'];
                    $temp['customer_code'] = $customer_code;
                    $temp['receipt_quantity'] = $value['receipt_quantity'];
                    $temp['post_fee'] = 0;
                    $temp['is_del'] = $value['is_del'];
                    isset($value['id']) && $value['id'] !== "" ? '' : $temp['addtime'] = date("Y-m-d H:i:s");
                    $temp['updatetime'] = date("Y-m-d H:i:s");
                    $temp['arrive_time'] = date("Y-m-d H:i:s");
                    $dat = Db::name('order_addr')->save($temp);
                    if ($dat == false) {
                        Db::rollback();
                        return error_show(1002, "更新失败");
                    }
                }

                Db::commit();
                return error_show(0, "更新成功");
            }
            Db::rollback();
            return error_show(1002, "更新失败");
        } catch (Exception $e) {
            Db::rollback();
            return error_show(1005, $e->getMessage());
        }
    }

    public function info()
    {
        $id = isset($this->post['id']) && $this->post['id'] !== "" ? intval($this->post['id']) : "";
        if ($id == "") {
            return error_show(1002, "参数id不能为空");
        }
        $einfo = Db::name('sale')->where(['id' => $id, 'is_del' => 0])->find();
        if (empty($einfo)) {
            return error_show(1002, "未找到销售订单数据");
        }
        if ($einfo['order_type'] == 3) {
            $goon = Db::name("good_zixun")->where(["spuCode" => $einfo['good_code'], "is_del" => 0])->find();
        } else {
            $goon = Db::name('good_platform')->alias('a')->join('good b', 'b.spuCode=a.spuCode', 'left')
                ->where(['a.skuCode' => $einfo['skuCode']])->find();
        }
        if ($goon == false) {
            return error_show(1003, "未找到商品数据");
        } else {
            $goon['exclusive'] = isset($goon['is_exclusive']) ? makeExcluse($goon['is_exclusive']) : "";
            $unit = Db::name("unit")->where(["id" => $goon['good_unit']])->find();
            $goon['unit'] = isset($unit['unit']) ? $unit['unit'] : '';
            $spec = Db::name("good_spec")->where(["spuCode" => $goon['spuCode'], "is_del" => 0])->select()->toArray();
            $speclist = [];
            if (!empty($spec)) {
                foreach ($spec as $value) {
                    $temp = [];
                    $temp['id'] = $value['id'];
                    $temp['spuCode'] = $value['spuCode'];
                    $temp['spec_id'] = $value['spec_id'];
                    $temp['spec_value_id'] = $value['spec_value_id'];
                    $temp['is_del'] = $value['is_del'];
                    $sp = Db::name("specs")->where(["id" => $value['spec_id']])->find();
                    $temp['spec_name'] = isset($sp["spec_name"]) ? $sp["spec_name"] : "";
                    $spv = Db::name("spec_value")->where(["id" => $value['spec_value_id']])->find();
                    $temp['spec_value'] = isset($spv["spec_value"]) ? $spv["spec_value"] : "";
                    $speclist[] = $temp;
                }
            }
            $goon["speclist"] = empty($speclist) ? [] : $speclist;
            $proof = Db::name("good_proof")->where(["spuCode" => $goon['spuCode'], "is_del" => 0])->order("updatetime desc")->field("id,proof_type,proof_url")->find();
            $goon['proof'] = isset($proof) && $proof != false ? $proof : [];
            $goon['origin_place_cn'] = "";
            $goon['delivery_place_cn'] = "";
            if (isset($goon['delivery_place']) && $goon['delivery_place'] !== "") {
                $place = ["provice_code" => "", "city_code" => "", "area_code" => ""];
                list($place['provice_code'], $place['city_code'], $place['area_code']) = explode(",", $goon['delivery_place']);
                $goon['delivery_place_cn'] = GetAddr(json_encode($place));
            }
            if (isset($goon['delivery_place']) && $goon['origin_place'] !== "") {
                $place = ["provice_code" => "", "city_code" => "", "area_code" => ""];
                list($place['provice_code'], $place['city_code'], $place['area_code']) = explode(",", $goon['origin_place']);
                $goon['origin_place_cn'] = GetAddr(json_encode($place));
            }
            if ($goon['brand_id'] != 0) {
                $brand = Db::name("brand")->where(["id" => $goon['brand_id']])->find();
                $goon["brand_name"] = isset($brand['brand_name']) ? $brand['brand_name'] : "";
            } else {
                $goon["brand_name"] = "";
                $goon["brand_id"] = "";
            }

            $supplier = Db::name("supplier")->where(["code" => $goon['supplierNo']])->find();
            $goon['supplierName'] = isset($supplier['name']) ? $supplier['name'] : "";
            $goon['noble_name'] = isset($goon['noble_metal']) && $goon['noble_metal'] != 0 ? $this->noble[$goon['noble_metal']] : "";
            if (isset($goon['companyNo']) && $goon['companyNo'] != "") {
                $company = Db::name("business")->where(["companyNo" => $goon['companyNo']])->find();
            }
            $goon['company'] = isset($company['company']) ? $company['company'] : "";
        }
        $int = isset($goon['cat_id']) && $goon['cat_id'] != 0 ? made($goon['cat_id']) : [];

        $in = Db::name('customer_info')->where(['companyNo' => $einfo['customer_code']])->field('companyName')->find();
        $einfo['supplierName'] = '';
        if ($einfo['supplierNo'] != "") {
            $supplier = Db::name("business")->where(["companyNo" => $einfo['supplierNo']])->find();
            $einfo['supplierName'] = isset($supplier['company']) ? $supplier['company'] : "";
        }
        $fo = Db::name('order_addr')->alias("a")->leftJoin("order_out b", "a.id=b.addrid and b.is_del=0")
            ->where(['a.orderCode' => $einfo['orderCode'], 'a.is_del' => 0])->field("a.*,b.post_name,b.post_code,
            b.post_fee,b.sendtime,b.send_num,b.check_num,b.error_num,b.wsm_code,b.order_type,b.status as send_status,b.outCode")
            ->select();
        $addrs = [];
        if (!empty($fo)) {
            foreach ($fo as $value) {
                $value['addr_info'] = "";
                $value['send_num'] = 0;
                if ($value['addr_code'] != "" && !empty($value['addr_code'])) {
                    $place = ["provice_code" => "", "city_code" => "", "area_code" => ""];
                    list($place['provice_code'], $place['city_code'], $place['area_code']) = explode(",", $value['addr_code']);
                    $addr = GetAddr(json_encode($place));
                    $value['addr_info'] = $addr;
                }
                $value['wsm_name'] = "";
                if (isset($value['wsm_code']) && $value['wsm_code'] != "") {
                    $wsmcode = Db::name("warehouse_info")->where(["wsm_code" => $value['wsm_code']])->find();
                    $value['wsm_name'] = isset($wsmcode['name']) ? $wsmcode['name'] : "";
                }
                $value['sendtime'] = $value['send_status'] < 2 ? '' : $value['sendtime'];
                $addrs[] = $value;
            }
        }
        $einfo['useage'] = "";
        if ($einfo['use_order'] != 0) {
            $use = Db::name("order_use")->where(["id" => $einfo['use_order']])->find();
            $einfo['useage'] = isset($use['order_use']) ? $use['order_use'] : "";
        } else {
            $einfo['use_order'] = '';
        }

        $einfo['platform_name'] = '';
        if ($einfo['platform_id'] != 0) {
            $plat = Db::name("platform")->where(['id' => $einfo['platform_id']])->find();
            $einfo['platform_name'] = isset($plat['platform_name']) ? $plat['platform_name'] : "";
        }
        $einfo['companyName'] = isset($in['companyName']) ? $in['companyName'] : "";
        $einfo['addrs'] = $addrs;
        $einfo['can'] = $int;
        $einfo['goodinfo'] = $goon;
        $einfo['good_num'] -= $einfo['th_num'];
        $einfo['send_num'] -= $einfo['th_num'];
        $einfo['total_price'] = round($einfo['total_price'] - $einfo['th_fee'], 2);

        //处理凭证
        if ($einfo['order_type'] == 1 || $einfo['order_type'] == 2) {
            $proof = Db::name('good_proof')
                ->field('id,proof_type,proof_url')
                ->where(['id' => $einfo['proof_id'], 'is_del' => 0])
                ->find();
            $einfo['proof_type'] = isset($proof['proof_type']) ? $proof['proof_type'] : '';
            $einfo['proof_url'] = isset($proof['proof_url']) ? $proof['proof_url'] : '';
        } elseif ($einfo['order_type'] == 3) {
            $einfo['proof_type'] = isset($goon['proof_type']) ? $goon['proof_type'] : '';
            $einfo['proof_url'] = isset($goon['proof_url']) ? $goon['proof_url'] : '';
        } else {
            $einfo['proof_type'] = '';
            $einfo['proof_url'] = '';
        }


        if (empty($einfo)) {
            return error_show(1002, "未找到销售订单数据");
        } else {
            return app_show(0, "获取成功", $einfo);
        }
    }

    public function del()
    {
        $id = isset($this->post['id']) && $this->post['id'] !== "" ? intval($this->post['id']) : "";
        if ($id === "") {
            return error_show(1002, "参数id不能为空");
        }
        $ed = Db::name('sale')->where(['id' => $id, 'is_del' => 0])->find();
        if (empty($ed)) {
            return error_show(1002, "未找到销售订单数据");
        }
        $str = Db::name('sale')->update(['id' => $id, 'is_del' => 1, 'updatetime' => date("Y-m-d H:i:s")]);
        if ($str) {
            $stc = ["order_code" => $id, "status" => $ed['status'], "action_remark" => '', "action_type" => "delete"];
            ActionLog::logAdd($this->post['token'], $stc, "XSQRD", $ed['status'], ['id' => $id, 'is_del' => 1, 'updatetime' => date("Y-m-d H:i:s")]);
            $order = ["order_type" => 'XSQRD', "order_code" => $ed['orderCode'], "order_id" => $id, "order_status" => $ed['status']];
            ProcessOrder::workdel($order);
            return error_show(0, "删除成功");
        } else {
            return error_show(1002, "删除失败");
        }
    }

    //废弃接口
    public function status()
    {
        $token = isset($this->post['token']) && $this->post['token'] !== "" ? trim($this->post['token']) : "";
        $id = isset($this->post['id']) && $this->post['id'] !== "" ? intval($this->post['id']) : "";
        if ($id == "") {
            return error_show(1002, "参数id不能为空");
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "";
        if ($status == "") {
            return error_show(1002, "订单状态不能为空");
        }
        $dio = Db::name('sale')->where(['id' => $id, 'is_del' => 0])->find();
        if (empty($dio)) {
            return error_show(1002, "销售单信息未找到");
        }
        if ($status == 1 && $dio['order_type'] == 2) {
            $zxinfo = Db::name("consult")->where(["zxNo" => $dio['zxNo'], "is_del" => 0])->find();
            if ($zxinfo == false) {
                return error_show(1004, "未找到咨询单数据");
            }
            $gold['price'] = 0;
            if ($zxinfo['zx_type'] == 2) {
                if ($zxinfo['metals'] == "") {
                    return error_show(1004, "未找到咨询单贵金属类型数据");
                }
                $metals = $zxinfo['metals'] == '18K' ? 1 : ($zxinfo['metals'] == '24K' ? 2 : 3);
                $gold = Db::name("gold_price")->where(["type" => $metals])->order("addtime desc")->find();
                if (empty($gold)) {
                    return error_show(1004, "未找到咨询单贵金属类型数据");
                }
                $dio['gold_price'] = $gold['price'];
            }
            $wsm = Db::name("warehouse_info")->where(["supplierNo" => $zxinfo['gysNo'], "wsm_type" => 2])->find();
            if (empty($wsm)) {
                return error_show(1002, "供应商仓库未找到");
            }

        }
        $apply_id = GetUserInfo($token);
        if (empty($apply_id) || $apply_id['code'] != 0) {
            return error_show(1002, "申请人数据不存在");
        }
        $rm = isset($apply_id["data"]['id']) ? $apply_id["data"]['id'] : "";
        $ri = isset($apply_id["data"]['nickname']) ? $apply_id["data"]['nickname'] : "";

        Db::startTrans();
        try {
            $vmp = $dio['status'];
            $dio['status'] = $status;
            $dio['updatetime'] = date("Y-m-d H:i:s");
            $st = Db::name('sale')->save($dio);
            if ($st) {
                $stn = ["order_code" => $dio['orderCode'], "status" => $vmp, "action_remark" => '', "action_type" => "status"];
                ActionLog::logAdd($this->post['token'], $stn, $dio['order_type'] == 2 ? "ZXQRD" : "XSQRD", $dio['status'], $dio);
                $order = ["order_type" => "XSQRD", "order_code" => $dio['orderCode'], "order_id" => $id, "order_status" => $dio['status'], "before_status" => 1];
                ProcessOrder::AddProcess($this->post['token'], $order);
                if ($status == 3 && $dio['order_type'] == 1) {
                    $dn = Db::name('sale_info')->where(['orderCode' => $st['orderCode']])->select();
                    foreach ($dn as $value) {
                        $dm = Db::name('good_stock')->where(['wsm_code' => $value['wsm_code'], 'good_type_code' => $st['good_code']])->find();
                        if ($dm == "") {
                            Db::rollback();
                            return error_show(1003, "未找到商品数据");
                        }
                        if ($value['num'] > $dm['usable_stock']) {
                            Db::rollback();
                            return error_show(1002, "超出库存数量");
                        }
                        $dm['usable_stock'] -= $value['num'];
                        $dm['wait_out_stock'] += $value['num'];
                        $send = Db::name("order_out")->where(["wsm_code" => $value['wsm_code'], "is_del" => 0])->sum("send_num");
                        $value['send_num'] = $send ?? 0;
                        $value['wsend_num'] = $value['num'] - $value['send_num'];
                        $Db = Db::name('good_stock')->update($dm);
                        $Db['updatetime'] = date('Y-m-d H:i:s');
                        if ($Db == false) {
                            Db::rollback();
                            return error_show(1002, "状态更新失败");
                        }
                    }
                }
                if ($status == 1 && $dio['order_type'] == 2) {
                    $cgd = makeNo("CG");
                    $clll = [
                        "cgdNo" => $cgd,
                        "bkcode" => $dio['orderCode'],
                        "wsm_code" => $wsm['wsm_code'],
                        "cgder_id" => Db::name('depart_user')->where('nickname', $zxinfo['saler'])->value('uid') ?? 0,//重名以及多个账号的话…………
                        "cgder" => $zxinfo['saler'],
                        "good_code" => "GD-" . $zxinfo['cpNo'],
                        "good_name" => $zxinfo['cpName'],
                        "good_type_code" => $zxinfo['cpNo'],
                        "good_num" => $dio['good_num'],
                        "good_price" => $zxinfo['total_fee'],
                        "total_fee" => round($zxinfo['total_fee'] * $dio['good_num'], 2),
                        "pakge_fee" => $zxinfo['package_fee'],
                        "cert_fee" => $zxinfo['cert_fee'],
                        "open_fee" => $zxinfo['open_fee'],
                        "delivery_fee" => $zxinfo['delivery_fee'],
                        "mark_fee" => $zxinfo['mark_fee'],
                        "teach_fee" => $zxinfo['cost_fee'],
                        "demo_fee" => $zxinfo['demo_fee'],
                        "nake_fee" => $zxinfo['bare_fee'],
                        "weight" => isset($zxinfo['weight']) ? $zxinfo['weight'] : 0,
                        "supplierNo" => $zxinfo['gysNo'],
                        "supplier_name" => $zxinfo['gysname'],
                        "gold_price" => $gold['price'],
                        "send_num" => 0,
                        "wsend_num" => $dio['good_num'],
                        "remark" => '',
                        "lasttime" => date("Y-m-d H:i:s"),
                        "is_del" => 0,
                        "status" => $dio['send_type'] == 1 ? 3 : 0,
                        "order_type" => 2,
                        "order_source" => 3,//3项目,废弃接口???
                        "addtime" => date("Y-m-d H:i:s"),
                        "updatetime" => date("Y-m-d H:i:s")
                    ];
                    $cgin = Db::name("purchease_order")->insert($clll);
                    //  var_dump(Db::name("purchease_order")->getLastSql(),$clll);
                    if ($cgin == false) {
                        $stb = ["order_code" => $cgd, "status" => $clll['status'], "action_remark" => '', "action_type" => "create"];
                        ActionLog::logAdd($this->post['token'], $stb, "xsd", $clll['status'], $stb);
                        Db::rollback();
                        return error_show(1002, "咨询采购单创建商品失败");
                    }
                    if ($dio['send_type'] == 1) {
                        $addr = Db::name('order_addr')->where(["orderCode" => $dio['orderCode'], 'is_del' => 0])->select();
                        foreach ($addr as $value) {
                            $outCode = makeNo("DF");
                            $data = [
                                "wsm_code" => $wsm['wsm_code'],
                                "orderCode" => $dio['orderCode'],
                                "outCode" => $outCode,
                                "order_type" => $dio['order_type'],
                                "apply_id" => $rm,
                                "apply_name" => $ri,
                                "addrid" => $value['id'],
                                "post_name" => '',
                                "post_code" => '',
                                "post_fee" => '',
                                "sendtime" => date("Y-m-d H:i:s"),
                                "send_num" => $value['receipt_quantity'],
                                "check_num" => 0,
                                "error_num" => 0,
                                "status" => 0,
                                "addtime" => date("Y-m-d H:i:s"),
                                "updatetime" => date("Y-m-d H:i:s")
                            ];
                            $datainfo = Db::name('order_out')->insert($data);
                            if (!$datainfo) {
                                $sti = ["order_code" => $dio['orderCode'], "status" => 0, "action_remark" => '', "action_type" => "create"];
                                ActionLog::logAdd($this->post['token'], $sti, "xsd", 0, $sti);
                                Db::rollback();
                                return error_show(1003, "创建失败");
                            } else {
                                //修改状态,添加待办
                                ActionLog::logAdd($this->post['token'], [
                                    "order_code" => $outCode,//出库单号
                                    "status" => 0,//这里的status是之前的值
                                    "action_remark" => '',//备注
                                    "action_type" => "create"//新建create,编辑edit,更改状态status
                                ], "CKD", 0, $data);

                                ProcessOrder::AddProcess($this->post['token'], [
                                    "order_type" => 'CKD',
                                    "order_code" => $outCode,//出库单号
                                    "order_id" => 0,
                                    "order_status" => 0, "before_status" => 0
                                ]);
                            }
                        }
                        $wsm_in_code = makeNo("CF");
                        $orin = [
                            "wsm_in_code" => $wsm_in_code,
                            "cgdNo" => $cgd,
                            "wsm_code" => $wsm['wsm_code'],
                            "wsm_reaper" => "",
                            "send_num" => $dio['good_num'],
                            "post_company" => '',
                            "post_code" => '',
                            "post_fee" => '',
                            "sendtime" => date("Y-m-d H:i:s"),
                            "apply_id" => $rm,
                            "apply_name" => $ri,
                            "wait_num" => 0,
                            "status" => 4,
                            "addtime" => date("Y-m-d H:i:s"),
                            "updatetime" => date("Y-m-d H:i:s")
                        ];
                        $win = Db::name("purchease_in")->insert($orin);
                        if (!$win) {
                            $stv = ["order_code" => $wsm_in_code, "status" => 4, "action_remark" => '', "action_type" => "create"];
                            ActionLog::logAdd($this->post['token'], $stv, "xsd", 4, $stv);
                            Db::rollback();
                            return error_show(1003, "创建失败");
                        }

                        //维护台账
                        Db::execute("UPDATE `wsm_standing_book` SET `wsm_in_code`=CONCAT(`wsm_in_code`,',{$wsm_in_code}'),`updatetime`='" . date('Y-m-d H:i:s') . "' WHERE `cgdNo`='{$cgd}'");

                        $good = Db::name("good_stock")->where(["wsm_code" => $wsm['wsm_code'], "good_type_code" => $zxinfo['cpNo'], "is_del" => 0])->find();
                        if (empty($good)) {
                            $good = [
                                "good_type_code" => $zxinfo['cpNo'],
                                "wsm_code" => $wsm['wsm_code'],
                                "usable_stock" => 0,
                                "wait_out_stock" => 0,
                                "total_stock" => 0,
                                "addtime" => date("Y-m-d H:i:s"),
                                "updatetime" => date("Y-m-d H:i:s"),
                            ];
                        }
                        $good['wait_out_stock'] += $dio['good_num'];
                        $good['total_stock'] = $good['usable_stock'] + $good['wait_out_stock'];
                        $good['updatetime'] = date("Y-m-d H:i:s");
                        $upd = Db::name("good_stock")->save($good);
                        if (!$upd) {
                            $ste = ["order_code" => $zxinfo['cpNo'], "status" => 0, "action_remark" => '', "action_type" => "create"];
                            ActionLog::logAdd($this->post['token'], $ste, "xsd", 0, $ste);
                            Db::rollback();
                            return error_show(1003, "创建失败");
                        }
                    }
                }
            }
            Db::commit();
            return error_show(0, "订单状态更新成功");
        } catch (Exception $e) {
            Db::rollback();
            return error_show(1005, $e->getMessage());
        }
    }

    public function fee()
    {
        $id = isset($this->post['id']) && $this->post['id'] !== "" ? trim($this->post['id']) : "";
        if ($id == "") {
            return error_show(1002, "参数id不能为空");
        }
        $etid = Db::name("sale")->where(["id" => $id, "is_del" => 0])->find();
        if (empty($etid)) {
            return error_show(1002, "未找到数据");
        }
        $vr = isset($this->post['order_addr']) && $this->post['order_addr'] !== "" ? $this->post['order_addr'] : "";
        if ($vr == "") {
            return error_show(1002, "参数order_addr不能为空");
        }
        Db::startTrans();
        try {
            $data = [
                "id" => $id,
                "status" => 2,
                "is_del" => 0,
                "updatetime" => date("Y-m-d H:i:s")
            ];
            $datainfo = Db::name('sale')->where(['id' => $id, 'is_del' => 0])->save($data);
            if ($datainfo) {
                $stx = ["order_code" => $etid['orderCode'], "status" => $etid['status'], "action_remark" => '', "action_type" => "edit"];
                ActionLog::logAdd($this->post['token'], $stx, "XSQRD", 2, $data);
                $order = ["order_type" => "XSQRD", "order_code" => $etid['orderCode'], "order_id" => $id, "order_status" => $data['status'], "before_status" => 0];
                ProcessOrder::AddProcess($this->post['token'], $order);
                foreach ($vr as $value) {
                    $tm = [];
                    $tm['id'] = $value['id'];
                    $tm['orderCode'] = $etid['orderCode'];
                    $tm['post_fee'] = $value['post_fee'];
                    $tm['updatetime'] = date("Y-m-d H:i:s");
                    $dn = Db::name('order_addr')->save($tm);
                    if ($dn == false) {
                        Db::rollback();
                        return error_show(1002, "更新失败");
                    }
                }
                Db::commit();
                return error_show(0, "更新成功");
            }
            Db::rollback();
            return error_show(1003, "更新失败");
        } catch (Exception $e) {
            Db::rollback();
            return error_show(1005, $e->getMessage());
        }
    }

    // 废弃
    public function out()
    {
        $token = isset($this->post['token']) && $this->post['token'] !== "" ? trim($this->post['token']) : "";
        $outCode = makeNo("DF");
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] !== "" ? trim($this->post['orderCode']) : "";
        if ($orderCode == "") {
            return error_show(1002, "参数orderCoder不能为空");
        }
        $der = Db::name('sale')->where(['orderCode' => $orderCode])->find();
        if ($der == "") {
            return error_show(1002, "未找到出库订单单号");
        }
//        $wsm_code = isset($this->post['wsm_code']) && $this->post['wsm_code'] !== "" ? trim($this->post['wsm_code']) : "";
//        if ($wsm_code == "") {
//            return error_show(1002, "参数wsm_code不能为空");
//        }
//        $wsm = Db::name('sale_info')->where(['wsm_code' => $wsm_code, 'orderCode' => $der['orderCode']])->find();
//        if ($wsm == "") {
//            return error_show(1002, "未找到仓库编码");
//        }
        $post_name = isset($this->post['post_name']) && $this->post['post_name'] !== "" ? trim($this->post['post_name']) : "";
        if ($post_name == "") {
            return error_show(1002, "物流公司不能为空");
        }
        $post_code = isset($this->post['post_code']) && $this->post['post_code'] !== "" ? trim($this->post['post_code']) : "";
        if ($post_code == "") {
            return error_show(1002, "物流单号不能为空");
        }
        $post_fee = isset($this->post['post_fee']) && $this->post['post_fee'] !== "" ? intval($this->post['post_fee']) : "";
        if ($post_fee == "") {
            return error_show(1002, "物流费不能为空");
        }
        $send_num = isset($this->post['send_num']) && $this->post['send_num'] !== "" ? $this->post['send_num'] : "";
        if ($send_num == "") {
            return error_show(1002, "发货数量不能为空");
        }
        if ($send_num > $der['wsend_num']) {
            return error_show(1002, "超出可发货数量");
        }
        $apply_id = GetUserInfo($token);
        if (empty($apply_id) || $apply_id['code'] != 0) {
            return error_show(1002, "申请人数据不存在");
        }
        $rm = isset($apply_id["data"]['id']) ? $apply_id["data"]['id'] : "";
        $ri = isset($apply_id["data"]['nickname']) ? $apply_id["data"]['nickname'] : "";
        $addrid = isset($this->post['addrid']) && $this->post['addrid'] !== "" ? intval($this->post['addrid']) : "";
        $dr = Db::name('order_addr')->where(['id' => $addrid, 'is_del' => 0])->find();
        if (empty($dr)) {
            return error_show(1003, "收货人信息未找到");
        }
        if ($dr['orderCode'] !== $orderCode) {
            return error_show(1002, "订单code不存在");
        }
        $sendtime = isset($this->post['sendtime']) && $this->post['sendtime'] !== "" ? $this->post['sendtime'] : date("Y-m-d H:i:s");
//    $check_num = isset($this->post['check_num']) && $this->post['check_num'] !=="" ? $this->post['check_num'] :"";
//    $error_num = isset($this->post['error_num']) && $this->post['error_num'] !=="" ? $this->post['error_num'] :"";
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? $this->post['status'] : "1";
        //$order_type = isset($this->post['order_type']) && $this->post['order_type'] !=="" ? $this->post['order_type'] :"1";
        //$dn=Db::name('sale_info')->where(['wsm_code'=>$outCode])->find();
        Db::startTrans();
        try {
            $data = [
                "wsm_code" => "",
                "orderCode" => $orderCode,
                "outCode" => $outCode,
                "order_type" => $der['order_type'],
                "apply_id" => $rm,
                "apply_name" => $ri,
                "addrid" => $dr['id'],
                "post_name" => $post_name,
                "post_code" => $post_code,
                "post_fee" => $post_fee,
                "sendtime" => $sendtime,
                "send_num" => $send_num,
                "check_num" => 0,
                "error_num" => 0,
                "status" => $status,
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s")
            ];
            $datainfo = Db::name('order_out')->insert($data, true);
            if ($datainfo > 0) {
                $stx = ["order_code" => $outCode, "status" => $status, "action_remark" => '', "action_type" => "create"];
                ActionLog::logAdd($this->post['token'], $stx, $der['order_type'] == 1 ? "CKD" : 'ZXCKD', $status, $data);
                $order = ["order_type" => "CKD", "order_code" => $outCode, "order_id" => $datainfo, "order_status" => $data['status'], "before_status" => 0];
                ProcessOrder::AddProcess($this->post['token'], $order);
                if ($status == 1) {
                    $item = $der['status'];
                    $der['send_num'] += $send_num;
                    $der['wsend_num'] -= $send_num;//($der['send_num'])?$der['wsend_num'] =="" ? $der['send']
                    $der['send_status'] = $der['send_num'] == 0 ? 1 : $der['wsend_num'] == 0 ? 3 : 2;
                    $der['status'] = $der['send_num'] == 0 ? 3 : $der['wsend_num'] == 0 ? 5 : 4;
                    $der['updatetime'] = date("Y-m-d H:i:s");
                    $si = Db::name('sale')->save($der);
                    if ($si == false) {
                        Db::rollback();
                        return error_show(1003, "更新失败");
                    }
                    $stx = ["order_code" => $orderCode, "status" => $item, "action_remark" => '', "action_type" => "edit"];

                    ActionLog::logAdd($this->post['token'], $stx, "XSQRD", $der['status'], $der);
                    $order = ["order_type" => "XSQRD", "order_code" => $orderCode, "order_id" => $der['id'], "order_status" => $data['status'], "before_status" => 0];

                    ProcessOrder::AddProcess($this->post['token'], $order);
                }

                Db::commit();
                return error_show(0, "创建成功");
            } else {
                Db::rollback();
                return error_show(1003, "创建失败");
            }
        } catch (Exception $e) {
            Db::rollback();
            return error_show(1005, $e->getMessage());
        }
    }

    // 废弃
    public function customer()
    {
        $outCode = isset($this->post['outCode']) && $this->post['outCode'] !== "" ? trim($this->post['outCode']) : "";
        if (empty($outCode)) {
            return error_show(1002, "销售订单编号不能为空");
        }
        $codeinfo = Db::name('order_out')->where(['outCode' => $outCode])->find();
        if ($codeinfo == "") {
            return error_show(1003, "未找到订单数据");
        }
//    $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] !=="" ? trim($this->post['orderCode']) :"";
//    if($orderCode==""){
//        return error_show(1002,"参数orderCoder不能为空");
//    }
        $dr = Db::name('sale')->where(['orderCode' => $codeinfo['orderCode']])->find();
        if ($dr == "") {
            return error_show(1002, "未找到销售订单");
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? $this->post['status'] : "";
        if ($status == "") {
            return error_show(10002, "状态不能为空");
        }
        Db::startTrans();
        try {
            $time = $codeinfo['status'];
            $codeinfo['status'] = $status;
            $codeinfo['updatetime'] = date("Y-m-d H:i:s");
            $cust = Db::name('order_out')->save($codeinfo);
            if ($cust) {
                $stx = ["order_code" => $outCode, "status" => $time, "action_remark" => '', "action_type" => "status"];
                ActionLog::logAdd($this->post['token'], $stx, "CKD", $codeinfo['status'], $codeinfo);
                $order = ["order_type" => "CKD", "order_code" => $outCode, "order_id" => $codeinfo['id'], "order_status" => $codeinfo['status'], "before_status" => 0];
                ProcessOrder::AddProcess($this->post['token'], $order);
                if ($status == 1) {
                    $stokc = Db::name("good_stock")->where(['spuCode' => $codeinfo['spuCode'], "wsm_code" => $codeinfo['wsm_code'],
                        "is_del" => 0])->find();
                    if ($stokc == false) {
                        Db::rollback();
                        return error_show(1002, "未找库存到数据");
                    } else {
                        if ($codeinfo['send_num'] > $stokc['usable_stock']) {
                            Db::rollback();
                            return error_show(1002, "超出库存数量");
                        }
                        $stokc['wait_out_stock'] += $codeinfo['send_num'];
                        $stokc['usable_stock'] -= $codeinfo['send_num'];
                        $stokc['updatetime'] = date("Y-m-d H:i:s");
                    }
                    $stoc = Db::name("good_stock")->save($stokc);
                    if ($stoc == false) {
                        Db::rollback();
                        return error_show(1002, "库存更新失败");
                    }
                    $item = $dr['status'];
                    $dr['send_num'] += $codeinfo['send_num'];
                    $dr['wsend_num'] -= $codeinfo['send_num'];//($der['send_num'])?$der['wsend_num'] =="" ? $der['send']
                    $dr['send_status'] = $dr['send_num'] == 0 ? 1 : $dr['wsend_num'] == 0 ? 3 : 2;
                    $dr['status'] = $dr['send_num'] == 0 ? 3 : $dr['wsend_num'] == 0 ? 5 : 4;
                    $dr['updatetime'] = date("Y-m-d H:i:s");
                    $si = Db::name('sale')->save($dr);
                    if ($si == false) {
                        Db::rollback();
                        return error_show(1003, "更新失败");
                    }
                    $stx = ["order_code" => $dr['orderCode'], "status" => $item, "action_remark" => '', "action_type" => "edit"];
                    ActionLog::logAdd($this->post['token'], $stx, $dr['order_type'] == 2 ? "ZXQRD" : "XSQRD", $dr['status'],
                        $dr);
                    $order = ["order_type" => "XSQRD", "order_code" => $dr['orderCode'], "order_id" => $dr['id'], "order_status" => $dr['status'], "before_status" => 0];
                    ProcessOrder::AddProcess($this->post['token'], $order);

                    //商品变动日志表,good_log_code字段存储销售订单编号
                    $good_data[] = ['good_log_code' => $outCode, "stock_id" => $stoc['id'], "type" => 1, 'stock' => $codeinfo['send_num'], "stock_name" => "wait_out_stock"];
                    $good_data[] = ['good_log_code' => $outCode, "stock_id" => $stoc['id'], "type" => 2, 'stock' => $codeinfo['send_num'], "stock_name" => "usable_stock"];
                    GoodLog::LogAdd($this->post['token'], $good_data, 'CKD');
                }
                if ($status == 3) {
                    $var = Db::name('good_stock')->where(['wsm_code' => $codeinfo['wsm_code'], 'good_type_code' => $dr['good_code']])->find();
                    if ($var == false) {
                        Db::rollback();
                        return error_show(1002, "未找到商品数据");
                    }
                    if ($codeinfo['send_num'] > $var['intra_stock']) {
                        Db::rollback();
                        return error_show(1003, "超出在途库存数量");
                    }
                    $var['intra_stock'] -= $codeinfo['send_num'];
                    $var['updatetime'] = date("Y-m-d H:i:s");
                    $stre = Db::name('good_stock')->save($var);

                    //商品变动日志表,good_log_code字段存储销售订单编号
                    $good_data[] = ['good_log_code' => $outCode, "stock_id" => $var['id'], "type" => 2, 'stock' => $codeinfo['send_num'], "stock_name" => "intra_stock"];
                    GoodLog::LogAdd($this->post['token'], $good_data, $codeinfo['order_type'] == 2 ? "ZXCKD" : "CKD");
                    if ($stre == false) {
                        Db::rollback();
                        return error_show(1002, "状态更新失败");
                    }
                }
                Db::commit();
                return error_show(0, "出库订单更新成功");
            } else {
                Db::rollback();
                return error_show(1003, "出库订单更新失败");
            }
        } catch (Exception $e) {
            Db::rollback();
            return error_show(1005, $e->getMessage());
        }
    }

    public function difflist()
    {
        $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 = [];
        $cgdNo = isset($this->post['orderCode']) && $this->post['orderCode'] != "" ? trim($this->post['orderCode']) : "";
        if ($cgdNo != "") {
            $where[] = ['a.orderCode', "like", "%$cgdNo%"];
        }
        $diffNo = isset($this->post['diffCode']) && $this->post['diffCode'] != "" ? trim($this->post['diffCode']) : "";
        if ($diffNo != "") {
            $where[] = ['a.diffCode', "like", "%$diffNo%"];
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "";
        if ($status !== "") {
            $where[] = ['a.status', "=", $status];
        }
        $start = isset($this->post['start']) && $this->post['start'] !== "" ? $this->post['start'] : "";
        if ($start != "") {
            $where[] = ["a.addtime", '>=', $start];
        }
        $end = isset($this->post['end']) && $this->post['end'] !== "" ? $this->post['end'] : "";
        if ($end != "") {
            $where[] = ["a.addtime", '<=', $end];
        }
        $supplierNo = isset($this->post['supplierNo']) && $this->post['supplierNo'] !== "" ? trim($this->post['supplierNo']) : "";
        if ($supplierNo != "") {
            $where[] = ['c.supplierNo', "like", "%$supplierNo%"];
        }
        $companyNo = isset($this->post['companyNo']) && $this->post['companyNo'] !== "" ? trim($this->post['companyNo']) : "";
        if ($companyNo != "") {
            $where[] = ['c.customer_code', "like", "%$companyNo%"];
        }
        //  $role=$this->checkRole();
//        if(!empty($role['write'])){
//            $where[]=["apply_id","in",$role['write']];
//        }
//        if(!empty($role['platform']) ){
//            $where[]=["c.platform_id","in",$role['platform']];
//        }
        $count = Db::name('sale_diff')->alias('a')
            ->join("sale c", "c.orderCode=a.orderCode", "left")
            ->join("customer_info v", "v.companyNo=c.customer_code", "left")
            ->where($where)->count();
        $total = ceil($count / $size);
        $page = $page >= $total ? intval($total) : $page;
        $list = Db::name('sale_diff')->alias('a')
            ->join("sale c", "c.orderCode=a.orderCode", "left")
            ->join("customer_info v", "v.companyNo=c.customer_code", "left")
            ->where($where)->page($page, $size)->field("a.*,c.customer_code,v.companyName,c.skuCode,c.order_type,c.supplierNo")
            ->order("a.addtime desc")->select();

        $data = [];
        foreach ($list as $value) {
            if ($value['order_type'] == 3) {
                $goon = Db::name("good_zixun")->where(["spuCode" => $value['good_code'], "is_del" => 0])->find();
            } else {
                $goon = Db::name('good_platform')->alias('a')->join('good b', 'b.spuCode=a.spuCode', 'left')
                    ->where(['a.skuCode' => $value['skuCode']])->find();
            }
            $value['can'] = isset($goon['cat_id']) && $goon['cat_id'] != 0 ? made($goon['cat_id']) : [];
            $wsm = Db::name("business")->where(['companyNo' => $value['supplierNo']])->find();
            $value['supplierNo'] = isset($wsm['companyNo']) ? $wsm['companyNo'] : "";
            $value['supplierName'] = isset($wsm['company']) ? $wsm['company'] : "";
            $data[] = $value;
        }
        return app_show(0, "获取成功", ['list' => $data, 'count' => $count]);
    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    //工差单审核
    public function diffcheck()
    {
        $token = isset($this->post['token']) && $this->post['token'] !== "" ? trim($this->post['token']) : "";
        $id = isset($this->post['id']) && $this->post['id'] !== "" ? intval($this->post['id']) : "";
        if ($id === "") {
            return error_show(1004, "参数id不能为空");
        }
        $info = Db::name("sale_diff")->where(["id" => $id])->find();
        if (empty($info)) {
            return error_show(1004, "订单数据未找到");
        }
        $sale = Db::name("sale")->where(["orderCode" => $info["orderCode"]])->find();
        if ($sale == false) {
            return error_show(1004, "订单数据未找到");
        }
        $cgd = Db::name("purchease_diff")->where(['id' => $info['cgd_diffid']])->find();
        if ($cgd == false) {
            return error_show(1004, "采购工差单数据未找到");
        }
        $is_act = isset($this->post['is_act']) && $this->post['is_act'] !== "" ? intval($this->post['is_act']) : "";
        if ($is_act === '') {
            return error_show(1004, "参数is_act不能为空");
        }
        $customer_remark = isset($this->post['customer_remark']) && $this->post['customer_remark'] !== "" ? trim($this->post['customer_remark']) : "";
        if ($customer_remark === '') {
            return error_show(1004, "参数customer_remark不能为空");
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "2";
        $remark = isset($this->post['remark']) && $this->post['remark'] !== "" ? trim($this->post['remark']) : "";
        $item = $info['status'];
        $info['is_act'] = $is_act;
        $info['customer_remark'] = $customer_remark;
        $info['status'] = $status;
        $info['remark'] = $remark;
        $info['updatetime'] = date("Y-m-d H:i:s");
        Db::startTrans();
        try {
            $up = Db::name("sale_diff")->save($info);
            if ($up) {
                $stx = ["order_code" => $info["orderCode"], "status" => $item, "action_remark" => '', "action_type" => "edit"];
                ActionLog::logAdd($this->post['token'], $stx, "XSGCD", $info['status'], $info);
                $order = ["order_type" => "XSGCD", "order_code" => $info["orderCode"], "order_id" => $info['id'], "order_status" => $info['status'], "before_status" => $item];
                ProcessOrder::AddProcess($this->post['token'], $order);
                $upda = [
                    "status" => $status,
                    "remark" => $remark,
                    "updatetime" => date("Y-m-d H:i:s"),
                ];

                $old_purchease_diff = Db::name("purchease_diff")
                    ->field('id,cgdNo,status')
                    ->where(["id" => $info['cgd_diffid']])
                    ->find();
                $cgdup = Db::name("purchease_diff")->where(["id" => $info['cgd_diffid']])->save($upda);
                if ($cgdup) {
                    if ($status == 2) {
                        if ($customer_remark == 1) {
                            $sale['diff_weight'] = $info['diff_weight'];
                            $sale['diff_fee'] = $info['diff_price'];
                            $sale['updatetime'] = date("Y-m-d H:i:s");
                            $sal = Db::name("sale")->save($sale);
                            if ($sal == false) {
                                Db::rollback();
                                return error_show(1003, "订单更新工差失败");
                            }
                        }
                        $cgdup = Db::name("purchease_order")->where(["cgdNo" => $cgd['cgdNo']])->save
                        (["diff_weight" => $cgd['diff_weight'], "diff_fee" => $cgd['diff_price'], "updatetime" => date("Y-m-d H:i:s")]);
                        if ($cgdup == false) {
                            Db::rollback();
                            return error_show(1003, "采购订单更新工差失败");
                        }

                    }

                    $a = ["order_code" => $old_purchease_diff["cgdNo"], "status" => $old_purchease_diff['status'], "action_remark" => '', "action_type" => "status"];
                    ActionLog::logAdd($this->post['token'], $a, "CGGCD", $upda['status'], $info);
                    $b = ["order_type" => "CGGCD", "order_code" => $old_purchease_diff["cgdNo"], "order_id" => $old_purchease_diff['id'], "order_status" => $upda['status'], "before_status" => $old_purchease_diff['status']];
                    ProcessOrder::AddProcess($this->post['token'], $b);

                    Db::commit();
                    return app_show(0, "更新成功");
                }
            }
            Db::rollback();
            return error_show(1003, "更新失败");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1003, $e->getMessage());
        }

    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function diffstatus()
    {
        $token = isset($this->post['token']) && $this->post['token'] !== "" ? trim($this->post['token']) : "";
        $id = isset($this->post['id']) && $this->post['id'] !== "" ? intval($this->post['id']) : "";
        if ($id === "") {
            return error_show(1004, "参数id不能为空");
        }
        $info = Db::name("sale_diff")->where(["id" => $id])->find();
        if ($info == false) {
            return error_show(1004, "工差单数据未找到");
        }
        $sale = Db::name("sale")->where(["orderCode" => $info["orderCode"]])->find();
        if ($sale == false) {
            return error_show(1004, "订单数据未找到");
        }
        $cgd = Db::name("purchease_diff")->where(['id' => $info['cgd_diffid']])->find();
        if ($cgd == false) {
            return error_show(1004, "采购工差单数据未找到");
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "3";
        $remark = isset($this->post['remark']) && $this->post['remark'] !== "" ? trim($this->post['remark']) : "";
        $ite = $info['status'];
        Db::startTrans();
        try {
            $upda = [
                "status" => $status,
                "remark" => $remark,
                "updatetime" => date("Y-m-d H:i:s"),
            ];
            $up = Db::name("sale_diff")->where($info)->save($upda);
            if ($up) {
                $stx = ["order_code" => $info["orderCode"], "status" => $ite, "action_remark" => '', "action_type" => "status"];
                ActionLog::logAdd($this->post['token'], $stx, "XSGCD", $status, $info);
                $order = ["order_type" => "XSGCD", "order_code" => $info["orderCode"], "order_id" => $info['id'],
                    "order_status" => $status, "before_status" => $ite];
                ProcessOrder::AddProcess($this->post['token'], $order);
                $cgdup = Db::name("purchease_diff")->where(["id" => $info['cgd_diffid']])->save($upda);
                if ($cgdup) {
                    if ($status == 2 && $info['customer_remark'] == 1) {
                        $sale['diff_weight'] = $info['diff_weight'];
                        $sale['diff_fee'] = $info['diff_price'];
                        $sale['updatetime'] = date("Y-m-d H:i:s");
                        $sal = Db::name("sale")->save($sale);
                        if ($sal == false) {
                            Db::rollback();
                            return error_show(1003, "订单更新工差失败");
                        }
                    }
                    Db::commit();
                    return app_show(0, "更新成功");
                }
            }
            Db::rollback();
            return error_show(1003, "更新失败");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1003, $e->getMessage());
        }

    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function diffinfo()
    {
        $id = isset($this->post['id']) && $this->post['id'] !== "" ? intval($this->post['id']) : "";
        if ($id === "") {
            return error_show(1004, "参数id不能为空");
        }
        $info = Db::name('sale_diff')->where(["id" => $id])->find();
        if (empty($info)) {
            return error_show(1004, "工差订单数据未找到");
        }
        $einfo = Db::name('sale')->where(['orderCode' => $info['orderCode'], 'is_del' => 0])->find();
        if ($einfo == false) {
            return error_show(1002, "未找到销售订单数据");
        }
        if ($einfo['order_type'] == 3) {
            $goon = Db::name("good_zixun")->where(["spuCode" => $einfo['good_code'], "is_del" => 0])->find();
        } else {
            $goon = Db::name('good_platform')->alias('a')->join('good b', 'b.spuCode=a.spuCode', 'left')
                ->where(['a.skuCode' => $einfo['skuCode']])->find();
        }
        if ($goon == false) {
            return error_show(1002, "未找到商品数据");
        }
        $info['skuCode'] = isset($goon['skuCode']) ? $goon['skuCode'] : "";
        $info['spuCode'] = isset($goon['spuCode']) ? $goon['spuCode'] : "";
        $info['order_type'] = isset($einfo['order_type']) ? $einfo['order_type'] : "";
        $info['can'] = isset($info['cat_id']) && $info['cat_id'] !== 0 ? made($info['cat_id']) : [];
        return app_show(0, "获取成功", $info);
    }

    public function saleout()
    {
        $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 = [["a.is_del", "=", 0]];
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] !== "" ? trim($this->post['orderCode']) : "";
        if ($orderCode !== "") {
            $where[] = ['a.orderCode', "like", "%$orderCode%"];
        }
        $order_type = isset($this->post['order_type']) && $this->post['order_type'] !== "" ? trim($this->post['order_type']) : "";
        if ($order_type !== "") {
            $where[] = ['a.order_type', "=", $order_type];
        }
        $outCode = isset($this->post['outCode']) && $this->post['outCode'] !== "" ? trim($this->post['outCode']) : "";
        if ($outCode !== "") {
            $where[] = ['a.outCode', "like", "%$outCode%"];
        }
        $apply_name = isset($this->post['apply_name']) && $this->post['apply_name'] !== "" ? trim($this->post['apply_name']) : "";
        if ($apply_name !== "") {
            $where[] = ['a.apply_name', "like", "%$apply_name%"];
        }
        $good_code = isset($this->post['good_code']) && $this->post['good_code'] !== "" ? trim($this->post['good_code']) : "";
        if ($good_code !== "") {
            $where[] = ['b.good_code', "like", "%$good_code%"];
        }
        $good_name = isset($this->post['good_name']) && $this->post['good_name'] !== "" ? trim($this->post['good_name']) : "";
        if ($good_name !== "") {
            $where[] = ['b.good_name', "like", "%$good_name%"];
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? trim($this->post['status']) : "";
        if ($status !== "") {
            $where[] = ['a.status', "=", $status];
        }
        $start = isset($this->post['start']) && $this->post['start'] !== "" ? $this->post['start'] : "";
        if ($start != "") {
            $where[] = ["a.addtime", '>=', $start];
        }
        $end = isset($this->post['end']) && $this->post['end'] !== "" ? $this->post['end'] : "";
        if ($end != "") {
            $where[] = ["a.addtime", '<=', $end];
        }
        $companyNo = isset($this->post['companyNo']) && $this->post['companyNo'] !== "" ? trim($this->post['companyNo']) : "";
        if ($companyNo != "") {
            $where[] = ['b.customer_code', "like", "%$companyNo%"];

        }
        $cgdNo = isset($this->post['cgdNo']) && $this->post['cgdNo'] !== "" ? $this->post['cgdNo'] : "";
        if ($cgdNo != "") {
            $where[] = ["os.cgdNo", 'like', '%' . $cgdNo . '%'];
        }
        $role = $this->checkRole();
        $condition = '';
        if (!empty($role['write']) && $this->uid != "") {
            // $where[]=["a.apply_id","in",$role['write']];
            $condition .= " (b.is_stock=1 and n.contactor = {$this->uid}) or (b.is_stock=0 and wpo.cgder_id = {$this->uid}) or a.apply_id in (" . implode(',',
                    $role['write']) . ")";
        }
//        if(!empty($role['platform']) ){
//            $where[]=["b.platform_id","in",$role['platform']];
//        }
        $company_name = isset($this->post['company_name']) && $this->post['company_name'] !== "" ? trim($this->post['company_name']) : "";
        if ($company_name !== "") $where[] = ["a.apply_id", 'in', get_company_item_user_by_name($company_name)];

        //发货时间筛选
        $start_sendtime = isset($this->post['start_sendtime']) && $this->post['start_sendtime'] !== "" ? $this->post['start_sendtime'] : "";
        $end_sendtime = isset($this->post['end_sendtime']) && $this->post['end_sendtime'] !== "" ? $this->post['end_sendtime'] : "";

        if ($start_sendtime != "" && $end_sendtime != "") {
            $where[] = ["a.sendtime", 'between', [$start_sendtime, $end_sendtime]];
            $where[] = ["a.status", '>=', 2];//搜索发货时间时,要指定状态为已发货及之后的状态值(0待发货,1待库管发货,2已发货待收货,3已收货,4已全部退货',)
        }

        $count = Db::name('order_out')
            ->alias('a')
            ->join("sale b", "b.orderCode=a.orderCode", "left")
            ->join("customer_info v", "v.companyNo=b.customer_code", "left")
            ->join("warehouse_info n", "n.wsm_code=a.wsm_code", "left")
            ->leftJoin("depart_user u", "u.uid=a.apply_id AND u.is_del=0")
            ->leftJoin("order_send os", "os.outCode=a.outCode")
            ->leftJoin("purchease_order wpo", "wpo.cgdNo=os.cgdNo")
            ->where($where)
            ->where($condition)
            ->count();
        $total = ceil($count / $size);
        $page = $page >= $total ? $total : $page;
        $list = Db::name('order_out')
            ->alias('a')
            ->join("sale b", "b.orderCode=a.orderCode", "left")
            ->join("customer_info v", "v.companyNo=b.customer_code", "left")
            ->join("warehouse_info n", "n.wsm_code=a.wsm_code AND n.is_del=0", "left")
            ->leftJoin("order_send os", "os.outCode=a.outCode")
            ->leftJoin("purchease_order wpo", "wpo.cgdNo=os.cgdNo")
            ->leftJoin("depart_user u", "u.uid=a.apply_id AND u.is_del=0")
            ->field("a.*,b.good_name,b.good_code,b.skuCode,b.supplierNo,b.customer_code,v.companyName,b.origin_price,b.sale_price,b.total_price,os.cgdNo,u.itemid")
            ->where($where)
            ->where($condition)
            ->order("addtime desc")
            ->page($page, $size)
            ->cursor();

        $data = [];
        foreach ($list as $value) {
            $wsmcode = Db::name("warehouse_info")->alias("k")->leftJoin("supplier c", "k.supplierNo=c.code")
                ->where(["k.wsm_code" => $value['wsm_code']])->field("k.name as wsm_name,c.name,c.code")->find();
            $addr = Db::name("order_addr")->where(["id" => $value['addrid']])->find();
            if ($value['order_type'] == 3) {
                $goon = Db::name("good_zixun")->field('id,cat_id')->where(["spuCode" => $value['good_code'], "is_del" => 0])->find();
            } else {
                $goon = Db::name('good_platform')->field('a.id,b.cat_id')->alias('a')->join('good b', 'b.spuCode=a.spuCode', 'left')->where(['a.skuCode' => $value['skuCode']])->find();
            }
            $value['wsm_name'] = isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name'] : "";
            $value['wsm_supplier'] = isset($wsmcode['name']) ? $wsmcode['name'] : "";
            $value['wsm_supplierNo'] = isset($wsmcode['code']) ? $wsmcode['code'] : "";
            $value['addr'] = isset($addr['addr']) ? $addr['addr'] : "";
            $value['contactor'] = isset($addr['contactor']) ? $addr['contactor'] : "";
            $value['mobile'] = isset($addr['mobile']) ? $addr['mobile'] : "";
            $value['can'] = isset($goon['cat_id']) && $goon['cat_id'] != 0 ? made($goon['cat_id']) : [];
            $value['company_name'] = implode('/', array_column(GetPart($value['itemid']), 'name'));
            $value['sendtime'] = $value['status'] < 2 ? '' : $value['sendtime'];
            $data[] = $value;
        }
        return app_show(0, "获取成功", ['list' => $data, 'count' => $count]);
    }

    public function outinfo()
    {
        $outCode = isset($this->post['outCode']) && $this->post['outCode'] !== "" ? trim($this->post['outCode']) : "";
        if ($outCode == "") {
            return error_show(1002, "参数outcode不能为空");
        }
        $codeinfo = Db::name("order_out")->where(['outCode' => $outCode, "is_del" => 0])->find();
        if (empty($codeinfo)) {
            return error_show(1002, "未找到出库数据");
        }
        $item = Db::name("sale")->where(['orderCode' => $codeinfo['orderCode']])->find();
        if ($item['order_type'] == 3) {
            $goodinfo = Db::name("good_zixun")->where(["spuCode" => $item['good_code'], "is_del" => 0])->find();
            if ($goodinfo == false) {
                return error_show(1004, "未找到商品数据");
            }
        } else {
            $goodinfo = Db::name('good_platform')->alias('a')->join('good b', 'b.spuCode=a.spuCode', 'left')
                ->where(['a.skuCode' => $item['skuCode']])->find();
            if ($goodinfo == false) {
                return error_show(1002, "未找到商品数据");
            }
        }
        $int = isset($goodinfo['cat_id']) && $goodinfo['cat_id'] != 0 ? made($goodinfo['cat_id']) : [];
        $addr = Db::name("order_addr")->where(["id" => $codeinfo['addrid']])->find();
        $codeinfo['good_name'] = isset($item['good_name']) ? $item['good_name'] : "";
        $codeinfo['good_num'] = isset($item['good_num']) ? $item['good_num'] : "";
        $codeinfo['good_code'] = isset($item['good_code']) ? $item['good_code'] : "";
        $codeinfo['origin_price'] = isset($item['origin_price']) ? $item['origin_price'] : "";
        $codeinfo['sale_price'] = isset($item['sale_price']) ? $item['sale_price'] : "";
        $codeinfo['total_price'] = isset($item['total_price']) ? $item['total_price'] : "";
        $codeinfo['skuCode'] = isset($item['skuCode']) ? $item['skuCode'] : "";
        $codeinfo['addr'] = GetAddr($addr['addr_code']);
        $codeinfo['addr'] .= isset($addr['addr']) ? $addr['addr'] : "";
        $codeinfo['addr_code'] = isset($addr['addr_code']) ? $addr['addr_code'] : "";
        $codeinfo['contactor'] = isset($addr['contactor']) ? $addr['contactor'] : "";
        $codeinfo['mobile'] = isset($addr['mobile']) ? $addr['mobile'] : "";
        $codeinfo['sendtime'] = $codeinfo['status'] < 2 ? '' : $codeinfo['sendtime'];
        $codeinfo['can'] = $int;
        $codeinfo['order_source'] = $item['order_source'];
        $orderReturn = Db::name("order_return")->where(["outCode" => $outCode, "is_del" => 0])->order("id desc")->find();
        $codeinfo['order_return'] = $orderReturn;
        return app_show(0, "获取成功", $codeinfo);
    }


    public function outadd()
    {
        $token = isset($this->post['token']) && $this->post['token'] !== "" ? trim($this->post['token']) : "";
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] !== "" ? trim($this->post['orderCode']) : "";
        if ($orderCode == "") {
            return error_show(1002, "参数orderCoder不能为空");
        }
        $der = Db::name('sale')->where(['orderCode' => $orderCode, "is_del" => 0])->find();
        if ($der == "") {
            return error_show(1002, "未找到出库订单单号");
        }
        $send_num = isset($this->post['send_num']) && $this->post['send_num'] !== "" ? $this->post['send_num'] : "";
        if ($send_num == "") {
            return error_show(1002, "发货数量不能为空");
        }
        $wsed = Db::name("order_out")->where(["orderCode" => $orderCode])->where([["status", "<", 2], ["is_del", "=", 0]])->sum
        ('send_num');
        if ($send_num > $der['wsend_num'] - $wsed) {
            return error_show(1002, "超出可发货数量");
        }

        $contactor = isset($this->post['contactor']) && $this->post['contactor'] != "" ? trim($this->post['contactor']) : "";
        if ($contactor == "") {
            return error_show(1002, "参数contactor不能为空");
        }
        $mobile = isset($this->post['mobile']) && $this->post['mobile'] != "" ? trim($this->post['mobile']) : "";
        if ($mobile == "") {
            return error_show(1002, "参数mobile不能为空");
        }
        $addr = isset($this->post['addr']) && $this->post['addr'] != "" ? trim($this->post['addr']) : "";
        if ($addr == "") {
            return error_show(1002, "参数addr不能为空");
        }
        $addr_code = isset($this->post['addr_code']) && $this->post['addr_code'] != "" ? trim($this->post['addr_code']) : "";
        if ($addr_code == "") {
            return error_show(1002, "参数addr_code不能为空");
        }
        $apply_id = GetUserInfo($token);
        if (empty($apply_id) || $apply_id['code'] != 0) {
            return error_show(1002, "申请人数据不存在");
        }
        $rm = isset($apply_id["data"]['id']) ? $apply_id["data"]['id'] : "";
        $ri = isset($apply_id["data"]['nickname']) ? $apply_id["data"]['nickname'] : "";
        $sendtime = isset($this->post['sendtime']) && $this->post['sendtime'] !== "" ? $this->post['sendtime'] : date("Y-m-d H:i:s");
        $order = Db::name("order_num")->where(["orderCode" => $orderCode, "status" => 1])->where([["wsend_num", ">=", 0]])
            ->find();
        if (empty($order)) {
            return error_show(1004, "未找到可以发货得采购单数据");
        }
        Db::startTrans();
        try {
            $order = Db::name("order_num")->where(["orderCode" => $orderCode, "status" => 1])->where([["wsend_num", ">=", 0]])
                ->lock(true)->find();
            if ($order == false) {
                Db::rollback();
                return error_show(1004, "未找到可以发货得采购单数据");
            }
            $addrlst = [
                "orderCode" => $orderCode,
                "addr" => $addr,
                "addr_code" => json_encode($addr_code),
                "contactor" => $contactor,
                "mobile" => $mobile,
                "customer_code" => $der['customer_code'],
                "post_fee" => $der['post_fee'],
                "arrive_time" => $sendtime,
                "receipt_quantity" => $send_num,
                "is_del" => 0,
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s")
            ];
            $addrid = Db::name("order_addr")->insert($addrlst, true);
            if ($addrid > 0) {
//                    $der['send_num'] +=$send_num;
//                    $der['wsend_num'] -= $send_num;
//                    $der['send_status'] = $der['send_num'] == 0 ? 1 : $der['wsend_num'] == 0 ? 3 : 2;
//                    $der['status'] = $der['send_num'] == 0 ? 0 : $der['wsend_num'] == 0 ?2 :1;
//                    $der['updatetime'] = date("Y-m-d H:i:s");
//                    $si = Db::name('sale')->save($der);
//                    if($si==false){
//                        Db::rollback();
//                        return error_show(1002,"出库单新建失败");
//                    }

                $outCode = makeNo("DF");
                $cgd = Db::name("purchease_order")->where(["cgdNo" => $order['cgdNo']])->find();
                if ($cgd == false) {
                    Db::rollback();
                    return error_show(1002, "未找到对应的采购单数据");
                }
                $order['wsend_num'] -= $send_num;
                $order['send_num'] += $send_num;
                $or = Db::name("order_num")->save($order);
                if ($or == false) {
                    Db::rollback();
                    return error_show(1002, "发货地址添加创建失败");
                }
                $tep = [
                    "cgdNo" => $order['cgdNo'],
                    "outCode" => $outCode,
                    "send_num" => $send_num,
                    "status" => 1,
                    "addtime" => date("Y-m-d H:i:s"),
                    "updatetime" => date("Y-m-d H:i:s")
                ];
                $sen = Db::name("order_send")->save($tep);
                if ($sen == false) {
                    Db::rollback();
                    return error_show(1002, "发货地址添加创建失败");
                }
                $data = [
                    "wsm_code" => isset($cgd['wsm_code']) ? $cgd['wsm_code'] : "",
                    "orderCode" => $orderCode,
                    "outCode" => $outCode,
                    "order_type" => $der['order_type'],
                    "apply_id" => $rm,
                    "apply_name" => $ri,
                    "addrid" => $addrid,
                    "post_name" => "",
                    "post_code" => "",
                    "post_fee" => "",
                    "sendtime" => $sendtime,
                    "send_num" => $send_num,
                    "check_num" => 0,
                    "error_num" => 0,
                    "status" => 1,
                    "addtime" => date("Y-m-d H:i:s"),
                    "updatetime" => date("Y-m-d H:i:s")
                ];
                if ($der['is_stock'] == 0) {
                    //维护商品所在仓库的库存 --- start
                    $temp = Db::name('good_stock')
                        ->field('id,usable_stock,wait_out_stock')
                        ->where(['spuCode' => $der['good_code'], 'wsm_code' => $cgd['wsm_code']])
                        ->find();
                    if (($temp == false || ($temp['usable_stock'] - $send_num) < 0) && $der['send_type'] == 1) {
                        Db::rollback();
                        return error_show(1004, '库存不足');
                    } else {
                        if (($temp == false || ($temp['usable_stock'] - $send_num) < 0) && $der['send_type'] == 2) {
                            $data['status'] = 0;
                        } else {
                            $up = Db::name('good_stock')
                                ->where('id', $temp['id'])
                                ->update([
                                    'usable_stock' => $temp['usable_stock'] - $send_num,
                                    'wait_out_stock' => $temp['wait_out_stock'] + $send_num,
                                    'updatetime' => date('Y-m-d H:i:s'),
                                ]);
                            if ($up == false) {
                                Db::rollback();
                                return error_show(1004, '库存更新失败');
                            }
                            // ::todo
                            $good_data[] = ['good_log_code' => $outCode, "stock_id" => $temp['id'], "type" => 1, 'stock' => $send_num, "stock_name" => "wait_out_stock"];
                            $good_data[] = ['good_log_code' => $outCode, "stock_id" => $temp['id'], "type" => 2, 'stock' => $send_num, "stock_name" => "usable_stock"];
                            GoodLog::LogAdd($this->post['token'], $good_data, "CKD");
                        }

                    }
                }

                $datainfo = Db::name('order_out')->insert($data, true);
                if ($datainfo > 0) {
                    //修改状态,添加待办
                    ActionLog::logAdd($this->post['token'], [
                        "order_code" => $data['outCode'],//出库单号
                        "status" => $data['status'],//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "create"//新建create,编辑edit,更改状态status
                    ], "CKD", $data['status'], $data);

                    ProcessOrder::AddProcess($this->post['token'], [
                        "order_type" => 'CKD',
                        "order_code" => $data['outCode'],//出库单号
                        "order_id" => $datainfo,
                        "order_status" => $data['status'], "before_status" => 0
                    ]);

                    //维护台账记录
                    Db::name('standing_book')
                        ->where('orderCode', $orderCode)
                        ->update([
                            'order_type' => $der['order_type'],
                            'order_source' => $der['order_source'],
                            'cgdNo' => $order['cgdNo'],
                            'customer_code' => $der['customer_code'],
                            'updatetime' => date('Y-m-d H:i:s'),
                        ]);

                    Db::execute("UPDATE `wsm_standing_book` SET `outCode`=CONCAT(`outCode`,',{$outCode}') WHERE `cgdNo`='{$cgd['cgdNo']}'");

                    Db::commit();
                    return app_show(0, "出库单新建成功");
                }
            }
            Db::rollback();
            return error_show(1004, "出库单新建失败");

        } catch (Exception $e) {
            Db::rollback();
            return error_show(1005, $e->getMessage());
        }
    }


    //库管发货
    public function outSend()
    {
        $outCode = isset($this->post['outCode']) && $this->post['outCode'] != "" ? trim($this->post['outCode']) : "";
        if ($outCode == "") {
            return error_show(1004, "参数outCode不能为空");
        }
        $outinfo = Db::name("order_out")->where(["outCode" => $outCode, "is_del" => 0])->find();
        if ($outinfo == false) {
            return error_show(1004, "发货数据未找到");
        }
        $einfo = Db::name('sale')->where(['orderCode' => $outinfo['orderCode'], 'is_del' => 0])->find();
        if (empty($einfo)) {
            return error_show(1002, "未找到销售订单数据");
        }
        $is_reurn = Db::name("sale_return")->where(['orderCode' => $outinfo['orderCode'], 'is_del' => 0])->where("status", "<", 4)->find();
        if ($is_reurn != false) {
            return error_show(1002, "销售单存在退货未处理完成");
        }
        $post_name = isset($this->post['post_name']) && $this->post['post_name'] != "" ? trim($this->post['post_name']) : "";
        if ($post_name == "") {
            return error_show(1004, "参数post_name不能为空");
        }
        $post_code = isset($this->post['post_code']) && $this->post['post_code'] != "" ? trim($this->post['post_code']) : "";
        if ($post_code == "") {
            return error_show(1004, "参数post_code不能为空");
        }
        $remark = isset($this->post['remark']) && $this->post['remark'] != "" ? trim($this->post['remark']) : "";
        $post_fee = isset($this->post['post_fee']) && $this->post['post_fee'] != "" ? floatval($this->post['post_fee']) : "";
        $outinfo['post_name'] = $post_name;
        $outinfo['post_code'] = $post_code;
        $outinfo['post_fee'] = $post_fee;
        $outinfo['sendtime'] = date("Y-m-d H:i:s");
        $old_outinfo_status = $outinfo['status'];
        $outinfo['status'] = 2;
        $outinfo['updatetime'] = date("Y-m-d H:i:s");
        $outinfo['remark'] = $remark;
        if ($einfo['wsend_num'] < $outinfo['send_num']) {
            return error_show(1004, "订单未发货数量不足");
        }
        Db::startTrans();
        try {
            $up = Db::name("order_out")->save($outinfo);

            $user_info = GetUserInfo($this->post['token']);
            $uid = isset($user_info['data']['id']) ? $user_info['data']['id'] : 0;
            $uname = isset($user_info['data']['nickname']) ? $user_info['data']['nickname'] : '';


            if ($up) {
                //修改状态,添加待办
                ActionLog::logAdd(['id' => $uid, 'nickname' => $uname], [
                    "order_code" => $outinfo['outCode'],//出库单号
                    "status" => $old_outinfo_status,//这里的status是之前的值
                    "action_remark" => '',//备注
                    "action_type" => "edit"//新建create,编辑edit,更改状态status
                ], "CKD", $outinfo['status'], $outinfo);


                ProcessOrder::AddProcess(['id' => $uid, 'nickname' => $uname], [
                    "order_type" => 'CKD',
                    "order_code" => $outinfo['outCode'],//出库单号
                    "order_id" => $outinfo['id'],
                    "order_status" => $outinfo['status'], "before_status" => $old_outinfo_status
                ]);
                $orderstatus = $einfo['status'];
                $einfo['send_num'] += $outinfo['send_num'];
                $einfo['wsend_num'] -= $outinfo['send_num'];
                $einfo['status'] = $einfo['wsend_num'] == 0 ? 2 : ($einfo['send_num'] == 0 ? 0 : 1);
                $einfo['send_status'] = $einfo['wsend_num'] == 0 ? 3 : ($einfo['send_num'] == 0 ? 1 : 2);
                $einfo['updatetime'] = date("Y-m-d H:i:s");
                $saleup = Db::name("sale")->save($einfo);
                if ($saleup == false) {
                    Db::rollback();
                    return error_show(1002, "销售单状态更新失败");
                }
//                }
                //修改状态,添加待办

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


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

                $stokc = Db::name("good_stock")->where(['spuCode' => $einfo['good_code'], "wsm_code" => $outinfo['wsm_code'], "is_del" => 0])->find();
                if ($stokc == false) {
                    Db::rollback();
                    return error_show(1002, "未找到库存数据");
                } else {
                    if ($outinfo['send_num'] > $stokc['wait_out_stock']) {
                        Db::rollback();
                        return error_show(1002, "超出库存数量");
                    }
                    $stokc['wait_out_stock'] -= $outinfo['send_num'];
                    $stokc['total_stock'] = $stokc['wait_out_stock'] + $stokc['usable_stock'];
                    //  $stokc['intra_stock']+=$outinfo['send_num'];
                    $stokc['updatetime'] = date("Y-m-d H:i:s");
                }
                $stoc = Db::name("good_stock")->save($stokc);
                if ($stoc == false) {
                    Db::rollback();
                    return error_show(1002, "库存更新失败");
                }
                $good_data[] = ['good_log_code' => $outCode, "stock_id" => $stokc['id'], "type" => 2, 'stock' => $outinfo['send_num'], "stock_name" => "wait_out_stock"];

                GoodLog::LogAdd(['id' => $uid, 'nickname' => $uname], $good_data, "CKD");
                Cache::store("redis")->handler()->lPush("SENDOUT", $outCode);
                Db::commit();


            } else {
                Db::rollback();
                return error_show(1004, "发货失败");
            }

            //如果是有赞订单的话,将发货信息推到有赞
            //有赞信息有可能推送失败(比如超过72小时,不允许多次修改等),所以不应该和这里的事务放到一起
            if ($einfo['order_source'] == 5) {
                $res = curl_request(config('app.yz_domain') . 'api/yz_out_send', ['orderCode' => $einfo['orderCode'], 'out_stype' => $post_name, 'post_code' => $post_code, 'uid' => $uid, 'uname' => $uname, 'order_out' => $outCode]);
                $res = json_decode($res, true);
                if ($res['code'] != 0) return app_show(0, '发货成功,' . $res['message']);
            }

            return app_show(0, "发货成功");

        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1004, $e->getMessage());
        }

    }

    public function RelaCgd($outinfo, array &$standing_book_da = [])
    {
        $cgd = Db::name("order_bk")->where([["spuCode", "=", $outinfo['spuCode']], ["is_del", "=", 0], ["balance_num", ">=",
            $outinfo['good_num']], ['companyNo', "=", $outinfo['companyNo']]])->lock(true)->find();
        if ($cgd == false) {
            return false;
        }
        $good = Db::name("good")->where(["spuCode" => $outinfo['spuCode'], "is_del" => 0])->find();
        if ($good == false) {
            return false;
        }

        $cgdinfo = Db::name("purchease_order")->where(['cgdNo' => $cgd['cgdNo'], "is_del" => 0])->find();
        if ($cgdinfo == false) {
            return false;
        }
        $QrdCgd = [
            "cgdNo" => makeNo("CG"),
            "bkcode" => $cgdinfo['bkcode'],
            'wsm_code' => $cgdinfo['wsm_code'],
            "cgder_id" => $cgdinfo['cgder_id'],
            "cgder" => $cgdinfo['cgder'],
            "spuCode" => $cgdinfo['spuCode'],
            "good_name" => $cgdinfo['good_name'],
            "good_num" => $outinfo['good_num'],
            "good_price" => $cgdinfo['good_price'],
            "total_fee" => round($cgdinfo['good_price'] * $outinfo['good_num'], 2),
            "pakge_fee" => $cgdinfo['pakge_fee'],
            "cert_fee" => $cgdinfo['cert_fee'],
            "open_fee" => $cgdinfo['open_fee'],
            "delivery_fee" => $cgdinfo['delivery_fee'],
            "mark_fee" => $cgdinfo['mark_fee'],
            "teach_fee" => $cgdinfo['teach_fee'],
            "nake_fee" => $cgdinfo['nake_fee'],
            "demo_fee" => $cgdinfo['demo_fee'],
            "weight" => $cgdinfo['weight'],
            "diff_weight" => $cgdinfo['diff_weight'],
            "diff_fee" => $cgdinfo['diff_fee'],
            "gold_price" => $cgdinfo['gold_price'],
            "supplierNo" => $cgdinfo['supplierNo'],
            "supplier_name" => $cgdinfo['supplier_name'],
            "companyNo" => $cgdinfo['companyNo'],
            "send_status" => 3,
            "send_num" => $outinfo['good_num'],
            "wsend_num" => 0,
            "remark" => $cgdinfo['remark'],
            "status" => 3,
            "lasttime" => $cgdinfo['lasttime'],
            "is_del" => 0,
            "order_type" => $outinfo['order_type'],
            "order_source" => $outinfo['order_source'],
            "good_type" => $cgdinfo['good_type'],
            "addtime" => date("Y-m-d H:i:s"),
            "updatetime" => date("Y-m-d H:i:s")
        ];
        $insetrCgd = Db::name("purchease_order")->insert($QrdCgd);
        if ($insetrCgd == false) {
            return false;
        } else {
            $standing_book_da = array_merge($standing_book_da, [
                'orderCode' => $outinfo['orderCode'],
                'cgdNo' => $cgdinfo['cgdNo'],
                'spuCode' => $outinfo['spuCode'],
                'order_type' => $QrdCgd['order_type'],
                'order_source' => $QrdCgd['order_source'],
                'supplierNo' => $cgdinfo['supplierNo'],
                'companyNo' => $cgdinfo['companyNo'],
                'bk_code' => $cgdinfo['bkcode'],
                'purchease_id' => Db::name('purchease')->where('bk_code', $cgdinfo['bkcode'])->value('id'),
            ]);
        }
        if ($good['is_gold_price'] == 1 && $good['is_stock'] == 1) {
            $gold = Db::name("gold_price1")
                ->field('id,price')
                ->where(["type" => $good['noble_metal'], "is_del" => 0, "status" => 1])
                ->order("addtime desc")
                ->find();

            //$saleprice(最终售价) = (打样费/购买数量 + 开模费/购买数量 + 商品重量* 最新金价 + 工艺费* 商品重量+包装费+加标费+证书费+产品裸价+物流费)/(1-成本售价/100);
            $sale_price = $good['demo_fee'] / $outinfo['good_num'] + $good['open_fee'] / $outinfo['good_num'] + $good['noble_weight'] * $gold["price"] + $outinfo['cost_fee'] * $good['noble_weight'] + $cgdinfo['pakge_fee'] + $cgdinfo['mark_fee'] + $cgdinfo['cert_fee'] + $cgdinfo['nake_fee'] + $cgdinfo['delivery_fee'];
            $ct['cgd_gold_price'] = $gold["price"];
            $updat = [
                "sale_price" => $sale_price,
                "total_price" => round($sale_price * $outinfo['good_num'], 2),
                "origin_price" => $cgdinfo['good_price'],
                "gold_price" => $gold["price"],
            ];
            $upsale = Db::name("sale")->where(["orderCode" => $outinfo['orderCode']])->update($updat);
            if ($upsale == false) {
                return false;
            }
        }
        $merge_num = Db::name("purchease_order")->where(["bkcode" => $cgdinfo['bkcode'], "order_type" => 1, "is_del" => 0])
            ->where("order_source", "<>", 0)
            ->field("sum(send_num)-sum(th_num) as num")->find();
        $cgd['balance_num'] = $cgd['total_num'] - $merge_num['num'];
        $cgd['merge_num'] = $merge_num['num'];
        $cgd['updatetime'] = date("Y-m-d H:i:s");
        $up = Db::name("order_bk")->save($cgd);
        if ($up == false) {
            return false;
        }
        $data = [
            "orderCode" => $outinfo['orderCode'],
            "cgdNo" => $QrdCgd['cgdNo'],
            "spuCode" => $outinfo['spuCode'],
            "companyNo" => $outinfo['companyNo'],
            "good_num" => $outinfo['good_num'],
            "wsend_num" => $outinfo['good_num'],
            "send_num" => 0,
            "wait_num" => $outinfo['good_num'],
            "status" => 1,
            "source" => 1,
        ];
        $order = Db::name("order_num")->save($data);
        if ($order == false) {
            return false;
        }
        return true;
    }

    public function addother()
    {
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode'] != "" ? trim($this->post['orderCode']) : "";
        if ($orderCode == "") {
            return error_show(1004, "参数orderCode不能为空");
        }
        $order = Db::name("sale")->where(["orderCode" => $orderCode, "is_del" => 0])->find();
        if ($order == false) {
            return error_show(1004, "未找到订单数据");
        }
        $paytime = isset($this->post['paytime']) && $this->post['paytime'] != "" ? $this->post['paytime'] : "";
        $workNo = isset($this->post['workNo']) && $this->post['workNo'] != "" ? trim($this->post['workNo']) : "";
        $platform_order = isset($this->post['platform_order']) && $this->post['platform_order'] != "" ? trim($this->post['platform_order']) : "";
        $paytime == "" ? "" : $order['paytime'] = $paytime;
        $order['workNo'] = $workNo;
        $order['platform_order'] = $platform_order;
        $order['updatetime'] = date("Y-m-d H:i:s");
        $sa = Db::name("sale")->save($order);
        if ($sa) {
            return app_show(0, "更新成功");
        } else {
            return error_show(1004, "更新失败");
        }

    }

    public function getPrice()
    {
        $skuCode = isset($this->post['skuCode']) && $this->post['skuCode'] != "" ? trim($this->post['skuCode']) : "";
        if ($skuCode === "") {
            return error_show(1003, "参数skuCode不能为空");
        }
        $is_activity = isset($this->post['is_activity']) && $this->post['is_activity'] !== "" ? intval($this->post['is_activity'])
            : "";
        if ($is_activity === "") {
            return error_show(1003, "参数is_activity不能为空");
        }
        $sale_num = isset($this->post['sale_num']) && $this->post['sale_num'] !== "" ? intval($this->post['sale_num']) : "";
        if ($sale_num === "") {
            return error_show(1003, "参数sale_num不能为空");
        }
        $ct = Db::name('good_platform')->alias('a')->join('good b', 'b.spuCode=a.spuCode', 'left')
            ->where(['a.skuCode' => $skuCode])->find();
        if ($ct == false) {
            return error_show(1002, "未找到商品数据");
        }

        $stock = 0;
        if ($ct['is_stock'] == 1) {
            $good_stock = Db::name("good_stock")->alias("a")->leftJoin("warehouse_info b", "a.wsm_code=b.wsm_code")->where
            (["spuCode" => $ct['spuCode'], "a.is_del" => 0, "a.status" => 1, "b.wsm_type" => 5])->field("a.id,a.usable_stock,a.wait_out_stock")->find();

            //  $good_stock = Db::name("good_stock")->where(["spuCode" => $ct['spuCode'], "is_del" => 0])->find();
            $stock = isset($good_stock['usable_stock']) ? $good_stock['usable_stock'] : "0";
        }
        if ($is_activity == 1) {
            $act = Db::name("activity_info")->alias("a")->leftJoin("good_activity b", "a.activity_code=b.activity_code")
                ->where(["a.skuCode" => $skuCode, "a.is_del" => 0, "a.status" => 1, "b.status" => 6, "b.is_del" => 0])->find();
            if ($act == false) {
                return error_show(1003, "未找到相关活动价");
            }
            if ($act['moq_num'] > $sale_num) {
                return error_show(1003, "商品不满足活动价起订量{$act['moq_num']}");
            }
            if ($act['activity_stock'] < $sale_num) {
                return error_show(1003, "商品活动库存剩余{$act['activity_stock']}");
            }
            return app_show(0, "获取成功", ['sale_price' => $act['activity_price'], "stock" => $act['activity_stock']]);
        } else {


            //good_nake 成本阶梯 good_ladder销售阶梯
            $origin = Db::name("good_nake")->where([["spuCode", "=", $ct['spuCode']], ["is_del", "=", 0]])->order("min_num asc")->find();
            if (!$origin) {
                return error_show(1003, "没有找到成本数据");
            }


            $good = Db::name("good_ladder")->where(["skuCode" => $skuCode, "is_del" => 0, "status" => 1])->order("min_num asc")->find();
            if (!$good) {
                return error_show(1003, "未找到相关阶梯价格");
            }

            if (!isset($origin['min_num'])) $origin['min_num'] = 0;

            //如果是库存品的话,只取销售的库存
            if ($ct['is_stock'] == 1) $lastnum = $good['min_num'];
            else  $lastnum = max($origin['min_num'] ?? 0, $good['min_num']);

            if ($sale_num < $lastnum) {
                return error_show(1003, "商品不满足起订量{$lastnum}");
            }

            $good_temp = Db::name("good_ladder")->where(["skuCode" => $skuCode, "is_del" => 0, "status" => 1])->where('min_num', '<=', $sale_num)->order("min_num desc")->find();
            if (!$good_temp) {
                return error_show(1003, "未找到相关阶梯价格");
            }

            $cat_top_list = made($ct['cat_id']);
            $cat_top_id = isset($cat_top_list[0]['id']) ? $cat_top_list[0]['id'] : 0;

            if ($ct['is_gold_price'] == 1 && $cat_top_id == 6) {
                $gold = Db::name("gold_price1")
                    ->field('id,price')
                    ->where(["type" => $ct['noble_metal'], "is_del" => 0, "status" => 1])
                    ->order("addtime desc")
                    ->find();

                $saleprice = $ct['demo_fee'] / $sale_num + $ct['open_fee'] / $sale_num + $ct['noble_weight'] * $gold["price"] + $good_temp['cost_fee'] * $ct['noble_weight'] + $origin['package_fee'] + $origin['mark_fee'] + $origin['cert_fee'] + $origin['nake_fee'] + $origin['delivery_fee'];


                return app_show(0, "获取成功", ['sale_price' => $saleprice, "stock" => $stock]);
            }

            return app_show(0, "获取成功", ['sale_price' => $good_temp['sale_price'], "stock" => $stock]);
        }
    }

    public function saleuse()
    {
        $orderCode = isset($this->post['orderCode']) && !empty($this->post['orderCode']) ? $this->post['orderCode'] : "";
        if ($orderCode == "") {
            return error_show(1003, "参数orderCode不能为空");
        }
        $order = Db::name("sale")->where(["orderCode" => $orderCode, "is_del" => 0])->select()->toArray();
        if (empty($order)) {
            return error_show(1003, "订单数据未找到");
        }
        $useid = isset($this->post['useid']) && $this->post['useid'] != "" ? intval($this->post['useid']) : "";
        if ($useid == "") {
            return error_show(1003, "参数useid不能为空");
        }
        $use = Db::name("order_use")->where(["id" => $useid, "is_del" => 0])->find();
        if ($use == false) {
            return error_show(1003, "用途数据未找到");
        }
        $asve = ['use_order' => $useid, "updatetime" => date("Y-m-d H:i:s")];
        $up = Db::name("sale")->where(["orderCode" => $orderCode, "is_del" => 0])->update($asve);
        if ($up > 0) {
            return app_show(0, "更新成功");
        } else {
            return error_show(1003, "更新失败");
        }
    }

    public function goodzxinfo()
    {
        $orderCode = isset($this->post['spuCode']) && $this->post['spuCode'] != '' ? trim($this->post['spuCode']) : "";
        if ($orderCode == "") {
            return error_show(1003, "参数spuCode不能为空");
        }
        $order = Db::name("good_zixun")->where(["spuCode" => $orderCode, "is_del" => 0])->find();
        if (empty($order)) {
            return error_show(1003, "订单数据未找到");
        }
        $unit = Db::name("unit")->where(["id" => $order['good_unit']])->find();
        if ($order['brand_id'] != 0) {
            $brand = Db::name("brand")->where(["id" => $order['brand_id']])->find();
            $order["brand_name"] = isset($brand['brand_name']) ? $brand['brand_name'] : "";
        } else {
            $order["brand_name"] = "";
            $order["brand_id"] = "";
        }
        $order['specinfo'] = json_decode($order['specinfo'], true);
        $order['unit'] = isset($unit['unit']) ? $unit['unit'] : '';
        $order['cat_info'] = made($order['cat_id'], []);
        $order['noble_name'] = isset($order['noble_metal']) && $order['noble_metal'] != 0 ? $this->noble[$order['noble_metal']] : "";
        if ($order['is_gold_price'] == 1) {
            $price = Db::name("gold_price1")->where(["type" => $order['noble_metal'], "status" => 1, "is_del" => 0])->order("addtime desc")->find();

        }
        $supplier = Db::name("supplier")->where(["code" => $order['supplierNo']])->find();
        $order['supplier_name'] = isset($supplier['name']) ? $supplier['name'] : "";
        $palt = Db::name("platform")->where(["id" => $order['platform_id']])->find();
        $order['platform_name'] = isset($palt['platform_name']) ? $palt['platform_name'] : "";
        $company = Db::name("business")->where(["companyNo" => $order['companyNo']])->find();
        $order['company'] = isset($company['company']) ? $company['company'] : "";
        $order["gold_price"] = isset($price['price']) ? $price['price'] : 0;
        $order["noble_weight"] = isset($order['weight']) ? $order['weight'] : 0;
        return app_show(0, "获取成功", $order);
    }

    //获取采反商品详情,当数据不在good_zixun中,模仿goodzxinfo
    public function getGoodZxInfoByNotZixun()
    {

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

        $val = Validate::rule(['spuCode' => 'require']);

        if (!$val->check($param)) return error_show(1004, $val->getError());

        $order = Db::name('consult_bids')
            ->field(true)
            ->where(['spuCode' => $param['spuCode'], 'is_del' => 0])
            ->find();

        if (empty($order)) return error_show(1003, "数据未找到");

//        $orderCode= isset($this->post['spuCode'])&&$this->post['spuCode']!=''?trim($this->post['spuCode']):"";
//        if($orderCode==""){
//            return error_show(1003,"参数spuCode不能为空");
//        }
//        $order= Db::name("good_zixun")->where(["spuCode"=>$orderCode,"is_del"=>0])->find();
//        if(empty($order)){
//            return error_show(1003,"订单数据未找到");
//        }
        $unit = Db::name("unit")->where(["id" => $order['unit_id']])->find();
        if ($order['brand_id'] != 0) {
            $brand = Db::name("brand")->where(["id" => $order['brand_id']])->find();
            $order["brand_name"] = isset($brand['brand_name']) ? $brand['brand_name'] : "";
        } else {
            $order["brand_name"] = "";
            $order["brand_id"] = "";
        }
        $order['specinfo'] = json_decode($order['specinfo'], true);
        $order['unit'] = isset($unit['unit']) ? $unit['unit'] : '';
        $order['cat_info'] = made($order['cat_id'], []);
        $order['noble_name'] = isset($order['metal_id']) && $order['metal_id'] != 0 ? $this->noble[$order['metal_id']] : "";
        if ($order['is_gold_price'] == 1) {
            $price = Db::name("gold_price1")->where(["type" => $order['metal_id'], "status" => 1, "is_del" => 0])->order("addtime desc")->find();

        }
        $supplier = Db::name("supplier")->where(["code" => $order['supplierNo']])->find();
        $order['supplier_name'] = isset($supplier['name']) ? $supplier['name'] : "";
//        $palt =Db::name("platform")->where(["id"=>$order['platform_id']])->find();
//        $order['platform_name']=isset($palt['platform_name']) ? $palt['platform_name']:"";
        $order["gold_price"] = isset($price['price']) ? $price['price'] : 0;
        $order["noble_weight"] = isset($order['weight']) ? $order['weight'] : 0;
        return app_show(0, "获取成功", $order);
    }

    //发货申请单导出
    public function exportSaleOut()
    {
        $outCodes = $this->request->post('outCodes', [], 'trim');

        if (empty($outCodes)) return error_show(1004, '要导出的发货申请单编号不能为空');

        $i = 1;
        $send_type = [1 => '直接发货', 2 => '延时发货'];
        $status = [0 => '待发货', 1 => '待库管发货', 2 => '已发货待收货', 3 => '已收货', 4 => '已全部退货'];
        $list = Db::name("order_out")
            ->alias('a')
            ->field('"" as 序号,a.addtime as 创建时间,po.cgdNo as 采购单编号,po.status as 采购单状态,po.cgder as 采购员,b.orderCode as 确认单号,b.addtime as 确认单时间,b.good_code as 产品编号,b.good_name as 产品名称,"" as 规格,"" as 单位,wi.name as 供应商名称,s.code as 供应商编号,po.nake_fee as 裸价,a.post_fee as 物流费,b.send_type as 发货方式,po.good_price as 采购单价,b.remark as 确认单备注,po.good_num as 采购数量,po.total_fee as 采购货款,a.send_num 发货数量,oa.contactor as 收货人,oa.mobile as 联系方式,oa.addr as 收货地址,oa.arrive_time as 到货时间,a.outCode as 发货申请单号,po.order_type,b.platform_order 平台订单号,a.post_name 发货申请单物流公司,a.post_code 发货申请单物流单号,a.post_fee 发货申请单物流费用,a.remark 发货申请单备注,a.apply_name 申请人,b.cat_id 商品分类')
            ->whereIn('a.outCode', $outCodes)
            ->order("a.addtime desc")
            ->withAttr('序号', function () use (&$i) {
                return $i++;
            })->withAttr('采购单状态', function ($val) use ($status) {
                return isset($status[$val]) ? $status[$val] : '';
            })->withAttr('发货方式', function ($val) use ($send_type) {
                return isset($send_type[$val]) ? $send_type[$val] : '';
            })->where("a.is_del", "=", 0)
            ->leftJoin("sale b", "b.orderCode=a.orderCode")
            ->leftJoin("order_addr oa", "oa.id=a.addrid AND oa.is_del=0")
            ->leftJoin("warehouse_info wi", "wi.wsm_code=a.wsm_code AND wi.is_del=0")
            ->leftJoin("supplier s", "s.code=wi.supplierNo AND s.is_del=0")
            ->leftJoin('order_send os', 'os.outCode=a.outCode ')
            ->leftJoin("purchease_order po", "po.cgdNo=os.cgdNo AND po.is_del=0")
            ->select()
            ->toArray();

        foreach ($list as &$value) {

            if ($value['order_type'] == 3) {
                $temp = Db::name("good_zixun")
                    ->where(["spuCode" => $value['产品编号'], "is_del" => 0])
                    ->field('id,specinfo,good_unit')
                    ->find();
                $good_unit = isset($temp['good_unit']) ? $temp['good_unit'] : 0;
                $specinfo = isset($temp['specinfo']) ? json_decode($temp['specinfo'], true) : [];

                $speclist = [];
                foreach ($specinfo as $val) {
                    $speclist[] = $val['spec_name'] . ':' . $val['spec_value_name'];
                }
            } else {
                $good_unit = Db::name('good_basic')
                    ->where(['spuCode' => $value['产品编号']])
                    ->value('good_unit', 0);
                $spec = Db::name("good_spec")
                    ->field('id,spec_id,spec_value_id')
                    ->where(["spuCode" => $value['产品编号'], "is_del" => 0])
                    ->select()
                    ->toArray();
                $speclist = [];
                if (!empty($spec)) {
                    foreach ($spec as $val) {
                        $speclist[] = Db::name("specs")->where(["id" => $val['spec_id']])->value('spec_name', '') . ':' . Db::name("spec_value")->where(["id" => $val['spec_value_id']])->value('spec_value', '');
                    }
                }
            }

            $value['规格'] = empty($speclist) ? '' : implode(',', $speclist);;
            $value['单位'] = $good_unit ? Db::name('unit')->where(['id' => $good_unit, 'is_del' => 0])->value('unit', '') : '';
            $value['商品分类'] = implode('/', array_column(made($value['商品分类']), 'name'));
            $value['发货申请单物流单号'] = ' ' . $value['发货申请单物流单号'];//添加空格防止将数字转为科学计数法(比如,韵达的快递单号就是纯数字)
            unset($value['order_type']);
        }

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

        $headerArr = array_keys($list[0]);
        excelSave('发货申请单导出' . date('YmdHis'), $headerArr, $list);
    }

    //发货申请单 签收(目前只改动状态,后面要实时查询物流信息,以判断是否签收)
    public function saleoutReceipt()
    {

        $outCode = $this->request->post('outCode', '', 'trim');

        if (empty($outCode)) return error_show(1004, '发货申请单编号不能为为空');

        Db::startTrans();

        try {

            $rs = Db::name('order_out')
                ->field('id,orderCode')
                ->where(['outCode' => $outCode, 'status' => 2, "is_del" => 0])
                ->find();

            if (empty($rs)) throw new Exception('该出库单不存在或不允许确认收货');

            //发货单收货
            $res_order_out = Db::name('order_out')
                ->where(['id' => $rs['id'], 'status' => 2, "is_del" => 0])
                ->update(['status' => 3, 'updatetime' => date('Y-m-d H:i:s')]);

            //查询该发货单所属的销售单,是否还有未收货的其他发货单
            $other_res_sale = Db::name('order_out')
                ->where(['orderCode' => $rs['orderCode'], 'status' => 2, "is_del" => 0])
                ->where('id', '<>', $rs['id'])
                ->find();

            if (empty($other_res_sale)) {
                //所属销售单也确认收货
                Db::name('sale')
                    ->where(['orderCode' => $rs['orderCode'], 'status' => 0])
                    ->update(['status' => 2, 'updatetime' => date('Y-m-d H:i:s')]);
            }

            if ($res_order_out) {
                Db::commit();
                return app_show(0, '收货完成');
            } else {
                Db::rollback();
                error_show(1005, '收货失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1005, $e->getMessage());
        }

    }

    //库管批量发货
    public function outSendBatchByImport()
    {

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

        if (empty($param['list'])) return error_show(1005, 'list参数不能为空');

        $user = GetUserInfo($param['token']);
        $createrid = isset($user['data']['id']) ? $user['data']['id'] : 0;
        $creater = isset($user['data']['nickname']) ? $user['data']['nickname'] : '';

        //所有发货单信息
        $order_out_infos = Db::name("order_out")
            ->where('status', 1)
            ->where('is_del', 0)
            ->whereIn('outCode', array_column($param['list'], 'outCode'))
            ->column('id,status,send_num,orderCode,wsm_code', 'outCode');

        //处理数据
        Db::startTrans();
        try {

            $good_data = [];

            $temp_out_codes = [];

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

                if (!isset($order_out_infos[$value['outCode']])) throw new Exception($value['outCode'] . '该发货单未找到或状态不允许发货');
                //每次循环都需要重新查询对应数据,为了数据及时更新
                $sale_infos = Db::name("sale")
                    ->where('orderCode', $order_out_infos[$value['outCode']]['orderCode'])
                    ->where('is_del', 0)
                    ->column('id,send_num,wsend_num,status,good_code,order_source', 'orderCode');

                if (!isset($sale_infos[$order_out_infos[$value['outCode']]['orderCode']])) throw new Exception($value['outCode'] . '该发货单对应的销售单未找到');

                //判断发货单是否重复
                if (isset($temp_out_codes[$value['outCode']])) {
                    Db::rollback();
                    return app_show(1005, '下列发货申请单号重复', [$value]);
                } else $temp_out_codes[$value['outCode']] = $value['outCode'];

                //【发货单】
                //查询已有发货单信息及状态

                //更新发货单
                $up = Db::name("order_out")
                    ->where(['id' => $order_out_infos[$value['outCode']]['id'], 'outCode' => $value['outCode'], 'status' => 1, "is_del" => 0])
                    ->update([
                        'post_name' => isset($value['post_name']) ? $value['post_name'] : '',
                        'post_code' => $value['post_code'],
                        'post_fee' => $value['post_fee'],
                        'sendtime' => date('Y-m-d H:i:s'),
                        'status' => 2,
                        'updatetime' => date('Y-m-d H:i:s'),
                        'remark' => isset($value['remark']) ? $value['remark'] : '',
                    ]);

                if ($up) {

                    //修改状态,添加待办
                    ActionLog::logAdd(['id' => $createrid, 'nickname' => $creater], [
                        "order_code" => $value['outCode'],//出库单号
                        "status" => $order_out_infos[$value['outCode']]['status'],//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "edit"//新建create,编辑edit,更改状态status
                    ], "CKD", 2, $order_out_infos[$value['outCode']]);

                    ProcessOrder::AddProcess(['id' => $createrid, 'nickname' => $creater], [
                        "order_type" => 'CKD',
                        "order_code" => $value['outCode'],//出库单号
                        "order_id" => $order_out_infos[$value['outCode']]['id'],
                        "order_status" => 2, "before_status" => $order_out_infos[$value['outCode']]['status']
                    ]);


                    //【销售单】
                    $einfo = [];
                    $einfo['send_num'] = $sale_infos[$order_out_infos[$value['outCode']]['orderCode']]['send_num'] + $order_out_infos[$value['outCode']]['send_num'];
                    $einfo['wsend_num'] = $sale_infos[$order_out_infos[$value['outCode']]['orderCode']]['wsend_num'] - $order_out_infos[$value['outCode']]['send_num'];
                    $einfo['status'] = $einfo['wsend_num'] == 0 ? 2 : ($einfo['send_num'] == 0 ? 0 : 1);
                    $einfo['send_status'] = $einfo['wsend_num'] == 0 ? 3 : ($einfo['send_num'] == 0 ? 1 : 2);
                    $einfo['updatetime'] = date("Y-m-d H:i:s");

                    $saleup = Db::name("sale")
                        ->where('id', $sale_infos[$order_out_infos[$value['outCode']]['orderCode']]['id'])
                        ->update($einfo);
                    if ($saleup == false) throw new Exception($value['outCode'] . '销售单状态更新失败');

                    //修改状态,添加待办
                    ActionLog::logAdd(['id' => $createrid, 'nickname' => $creater], [
                        "order_code" => $order_out_infos[$value['outCode']]['orderCode'],//销售单号
                        "status" => $sale_infos[$order_out_infos[$value['outCode']]['orderCode']]['status'],//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "edit"//新建create,编辑edit,更改状态status
                    ], "XSQRD", $einfo['status'], $einfo);

                    ProcessOrder::AddProcess(['id' => $createrid, 'nickname' => $creater], [
                        "order_type" => 'XSQRD',
                        "order_code" => $order_out_infos[$value['outCode']]['orderCode'],//出库单号
                        "order_id" => $sale_infos[$order_out_infos[$value['outCode']]['orderCode']]['id'],
                        "order_status" => $einfo['status'], "before_status" => $sale_infos[$order_out_infos[$value['outCode']]['orderCode']]['status']
                    ]);

                    //【库存】
                    $stock = Db::name("good_stock")
                        ->field('id,wait_out_stock,usable_stock,total_stock,updatetime')
                        ->where([
                            "is_del" => 0,
                            'spuCode' => $sale_infos[$order_out_infos[$value['outCode']]['orderCode']]['good_code'],
                            "wsm_code" => $order_out_infos[$value['outCode']]['wsm_code'],
                        ])->find();
                    if ($stock == false) throw new Exception($value['outCode'] . '未找到库存数据');
                    else {
                        if ($order_out_infos[$value['outCode']]['send_num'] > $stock['wait_out_stock']) throw new Exception($value['outCode'] . '超出库存数量');

                        $stock['wait_out_stock'] -= $order_out_infos[$value['outCode']]['send_num'];
                        $stock['total_stock'] = $stock['wait_out_stock'] + $stock['usable_stock'];
                        $stock['updatetime'] = date("Y-m-d H:i:s");

                        $stock_rs = Db::name("good_stock")
                            ->where('id', $stock['id'])
                            ->update($stock);
                        if ($stock_rs == false) throw new Exception($value['outCode'] . '库存更新失败');

                        $good_data[] = [
                            'good_log_code' => $value['outCode'],
                            'stock_id' => $stock['id'],
                            'type' => 2,
                            'stock' => $order_out_infos[$value['outCode']]['send_num'],
                            'stock_name' => 'wait_out_stock'
                        ];

                    }


                } else throw new Exception($value['outCode'] . '发货失败');
                Cache::store("redis")->handler()->lPush("SENDOUT",$value['outCode']);
            }

            if (!empty($good_data)) GoodLog::LogAdd(['id' => $createrid, 'nickname' => $creater], $good_data, "CKD");

            Db::commit();

            return app_show(0, '发货成功');

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


    }

    //获取物流信息
    public function getLogisticsInformation()
    {
        $post_code = $this->request->post('post_code', '', 'trim');

        if (empty($post_code)) return error_show(1004, '快递单号不能为空');
        $postCode = explode(",", $post_code);

        $rs = Db::name('express_data')
            ->where('post_code', $postCode[0])
            ->where('status', ">=", 0)
            ->withAttr('post_data', function ($val) {
                return json_decode($val, true);
            })->findOrEmpty();
        settype($rs, 'object');//格式统一转为对象
        return app_show(0, '请求成功', $rs);

    }


}