<?php

namespace app\admin\controller;

use app\admin\model\ActionLog;
use think\facade\Db;
use app\admin\model\ProcessOrder;
use think\facade\Validate;

//报备单
class Filing extends Base
{
    //列表
    public function getList()
    {
        $data = $this->request->only(['page' => 1, 'size' => 10, 'cat_id' => '', 'start_date' => '', 'end_date' => '',
        'filingCode' => '', 'status' => '', 'good_name' => '', 'companyName' => '', 'companyCode' => '', 'orderCode' => '','customerCode' => '', 'supplierNo' => ''], 'post');

        $where = [['is_del', '=', '0']];
        if ($data['cat_id'] != '') $where[] = ['cat_id', '=', $data['cat_id']];
        if ($data['start_date'] != '' && $data['end_date'] != '') $where[] = ['addtime', 'between', [$data['start_date'] . ' 00:00:00', $data['end_date'] . ' 23:59:59']];
        if ($data['filingCode'] != '') $where[] = ['filingCode', 'like', '%' . $data['filingCode'] . '%'];
        if ($data['status'] != '') $where[] = ['status', '=', $data['status']];
        if ($data['good_name'] != '') $where[] = ['good_name', 'like', '%' . $data['good_name'] . '%'];
        if ($data['companyName'] != '') $where[] = ['companyName', 'like', '%' . $data['companyName'] . '%'];
        if ($data['companyCode'] != '') $where[] = ['companyCode', 'like', '%' . $data['companyCode'] . '%'];
        if ($data['orderCode'] != '') $where[] = ['orderCode', 'like', '%' . $data['orderCode'] . '%'];
        if ($data['supplierNo'] != '') $where[] = ['supplierNo', 'like', '%' . $data['supplierNo']. '%' ];
        if ($data['customerCode'] != '') $where[] = ['customerCode', 'like', '%' . $data['customerCode'] . '%'];

        $count = Db::name('filing')
            ->where($where)
            ->count('id');

        $list = Db::name('filing')
            ->field('id,filingCode,cat_id,good_name,num,wait_num,transfer_num,good_img,
            price,expect_service,companyName,companyCode,status,addtime,supplierNo,supplierName,customerCode,customerName,
            "" catinfo,orderCode,cgd_charge')
            ->where($where)
            ->page($data['page'], $data['size'])
            ->order('id', 'desc')
            ->withAttr('good_img', function ($val) {
                return explode(',', $val);
            })
            ->select()
            ->toArray();
		 $has_account = checkHasAccountBySupplierNos(array_unique(array_column($list,'supplierNo')));
        $all_cat = [];
        foreach ($list as &$value) {
            if (!isset($all_cat[$value['cat_id']])) $all_cat[$value['cat_id']] = implode('/', array_column(made($value['cat_id']), 'name'));
            $value['catinfo'] = $all_cat[$value['cat_id']];
            $value['wsm_has_account'] = (int)isset($has_account[$value['supplierNo']]);
            
        }
        return json_show(0, '获取报备单列表成功', ['count' => $count, 'list' => $list]);
    }

    //添加
    public function add()
    {
        $param = $this->request->filter(["trim",'strip_tags'])->only([
        	'customerCode',
        	'supplierNo',
        	'companyName',
        	"manager",
        	"managerid",
        	'num',
        	'is_determine_price',
        	'price' => 0,
        	'expect_service_proportion',
        	'expect_service',
        	'cgd_charge' => 0,
        	'brand_id',
        	'fill_url',
        	'preservation_day',
        	'delivery_day',
        	'make_day',
        	'tax',
        	'unit_id',
        	'cat_id',
        	'spec_list' => [],
        	'good_name',
        	'origin_place',
        	'delivery_place',
        	'weight',
        	'supply_area',
        	'pay_way',
        	'gold_weight',
        	'noble_metal',
        	'config',
        	'other_config',
        	'remark',
        	'cost_desc',
        	'good_img'], 'post');

        $val = Validate::rule([
            'customerCode|业务公司' => 'require|max:255',
            'supplierNo|供应商' => 'require|max:255',
            'companyName|客户名称' => 'require|max:255',
            'num|销售数量' => 'require|number|gt:0|lt:999999999',
            'is_determine_price|是否确定售价' => 'require|number|in:1,0',
            'price|销售价' => 'requireIf:is_determine_price,1|float|max:99999999.99',
            'expect_service_proportion|期望服务费比例' => 'require|float|between:0,100',
            'expect_service|期望服务费' => 'require|float|max:99999999.99',
            'cgd_charge|采购价' => 'requireIf:is_determine_price,0|float|max:99999999.99',
            'brand_id|品牌' => 'require|number|gt:0',
            'fill_url|报备附件' => 'require',
            'preservation_day|有效期' => 'require|number|max:999999999',
            'delivery_day|物流时间' => 'require|number|max:999999999',
            'make_day|生产工期' => 'require|number|max:999999999',
            'tax|税点' => 'require|number|between:0,100',
            'unit_id|单位' => 'require|number|gt:0',
            'cat_id|分类' => 'require|number|gt:0',
            'spec_list|规格类型' => 'array|max:100',
            'good_name|商品名称' => 'require|max:255',
            'origin_place|产地' => 'require|array|length:3',
            'delivery_place|发货地' => 'require|array|length:3',
            'weight|总重量' => 'require|float|max:99999999.99',
            'supply_area|供货区域' => 'require|number|in:1,2',
            'pay_way|付款方式' => 'require|number|in:0,1,2',
            'remark|采购备注' => 'require|max:255',
            'cost_desc|工艺说明' => 'max:255',
            'good_img|商品图片' => 'require|array|max:10',
        ]);

        if (!$val->check($param)) return json_show(1004, $val->getError());
        $manager = $param['manager']??$this->uname;
        $managerid = $param['managerid']??$this->uid;
        //如果是贵金属的话,额外判断
        $cat = made($param['cat_id']);
        if (isset($cat[0]['id']) && $cat[0]['id'] == 6) {
            $val_gold = Validate::rule([
                'gold_weight|贵金属重量' => 'require|float|max:99999999.99',
                'noble_metal|贵金属类型' => 'require|number|in:1,2,3',
                'config|配置要求' => 'require|max:255',
                'other_config|其他配置要求' => 'require|max:255',
            ]);
            if (!$val_gold->check($param)) return json_show(1004, $val_gold->getError());
        }

        $val2 = Validate::rule([
            'spec_id|规格id' => 'require|number|gt:0',
            'spec_value_id|规格值id' => 'require|number|gt:0',
        ]);

        $all_spec = Db::name('specs')
            ->whereIn('id', array_column($param['spec_list'], 'spec_id'))
            ->column('spec_name', 'id');

        $all_spec_value = Db::name('spec_value')
            ->whereIn('id', array_column($param['spec_list'], 'spec_value_id'))
            ->column('spec_value', 'id');

        foreach ($param['spec_list'] as &$spec_list) {
            if (!$val2->check($spec_list)) return json_show(1004, $val2->getError());
            $spec_list['spec_name'] = $all_spec[$spec_list['spec_id']] ?? '';
            $spec_list['spec_value_name'] = $all_spec_value[$spec_list['spec_value_id']] ?? '';
        }

        if ($param['is_determine_price'] == 1) $param['cgd_charge'] = round(bcsub($param['price'], $param['expect_service'], 3), 2);//确定售价时,采购价=售价-服务费
        else $param['price'] = round(bcadd($param['cgd_charge'], $param['expect_service'], 3), 2);//不确定售价时,售价=采购价+服务费

        $userCommon = \app\admin\common\User::getIns();
        $names = $userCommon->handle('getCodeAndName', ['code' => [$param['customerCode'], $param['supplierNo']]]);
        if (!isset($names['data'][$param['customerCode']]) || $names['data'][$param['customerCode']] == '') return json_show(1004, '该业务公司不存在');
        if (!isset($names['data'][$param['supplierNo']]) || $names['data'][$param['supplierNo']] == '') return json_show(1004, '该供应商不存在');
		$data=array_merge($param, [
                'customerName' => $names['data'][$param['customerCode']],
                'supplierName' => $names['data'][$param['supplierNo']],
                'filingCode' => makeNo('BM'),
                'service_proportion' => $param['expect_service_proportion'],//服务费比例与期望服务费比例一致
                'service_charge' => $param['expect_service'],//服务费与期望服务费一致
                'specinfo' => json_encode($param['spec_list']),
                'wait_num'=>$param['num'],
                'send_way' => 2,
                'cert_fee' => 0,
                'pakge_fee' => 0,
                'cost_fee' => 0,
                'mark_fee' => 0,
                'demo_fee' => 0,
                'open_fee' => 0,
                'fill_url' =>$param['fill_url'],
                'delivery_fee' => 0,
                'is_gold_price' => 0,
                'is_diff' => 0,
                'apply_id' => $this->uid,
                'apply_name' => $this->uname,
                'status' => 0,
                'is_del' => 0,
                "manager"=>$manager,
                "managerid"=>$managerid,
                'addtime' => date('Y-m-d H:i:s'),
                'updaterid' => $this->uid,
                'updater' => $this->uname,
                'updatetime' => date('Y-m-d H:i:s'),
                'gold_weight' => $param['gold_weight'] ?? 0,
                'noble_metal' => $param['noble_metal'] ?? 0,
                'config' => $param['config'] ?? '',
                'other_config' => $param['other_config'] ?? '',
                'good_img' => implode(',', $param['good_img']),
                'origin_place' => implode(',', $param['origin_place']),
                'delivery_place' => implode(',', $param['delivery_place']),
            ]);
        $rs = Db::name('filing')
            ->strict(false)
            ->insertGetId($data);
		         $stn = ['order_code' => $data['filingCode'], 'status' => 0, 'action_remark' => '', 'action_type' => 'add'];
                ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], $stn, 'BBD', 0, $data);
                			$process=[
                            'order_type' => 'BBD',
                            'order_code' => $data['filingCode'],//出库单号
                            'order_id' => $rs ,
                            'order_status' => 0,
                            'before_status' => 0,
                            'holder_id'=>0,
                        ];
			ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname],$process);
        return $rs ? json_show(0, '创建报备单成功') : json_show(1004, '创建报备单失败');

    }
    //添加
    public function save()
    {
        $param = $this->request->filter(['trim','strip_tags'])->only(["id",
        	'customerCode',
        	'supplierNo',
        	'companyName',
        	'num',
        	'is_determine_price',
        	'price' => 0,
        	'expect_service_proportion',
        	'expect_service',
        	'cgd_charge' => 0,
        	'brand_id',
        	'preservation_day',
        	'delivery_day',
        	'make_day',
        	'tax',
        	 'fill_url' ,
        	'unit_id',
        	'cat_id',
        	'spec_list' => [],
        	'good_name',
        	'origin_place',
        	'delivery_place',
        	'weight',
        	'supply_area',
        	'pay_way',
        	'gold_weight',
        	'noble_metal',
        	'config',
        	'other_config',
        	'remark',
        	'cost_desc',
        	'good_img'], 'post');

        $val = Validate::rule([
            'id|报备单主键id' => 'require',
            'customerCode|业务公司' => 'require|max:255',
            'supplierNo|供应商' => 'require|max:255',
            'companyName|客户名称' => 'require|max:255',
            'num|销售数量' => 'require|number|gt:0|lt:999999999',
            'is_determine_price|是否确定售价' => 'require|number|in:1,0',
            'price|销售价' => 'requireIf:is_determine_price,1|float|max:99999999.99',
            'expect_service_proportion|期望服务费比例' => 'require|float|between:0,100',
            'expect_service|期望服务费' => 'require|float|max:99999999.99',
            'cgd_charge|采购价' => 'requireIf:is_determine_price,0|float|max:99999999.99',
            'brand_id|品牌' => 'require|number|gt:0',
            'preservation_day|有效期' => 'require|number|max:999999999',
            'delivery_day|物流时间' => 'require|number|max:999999999',
            'make_day|生产工期' => 'require|number|max:999999999',
            'fill_url|报备附件' =>"require",
            'tax|税点' => 'require|number|between:0,100',
            'unit_id|单位' => 'require|number|gt:0',
            'cat_id|分类' => 'require|number|gt:0',
            'spec_list|规格类型' => 'array|max:100',
            'good_name|商品名称' => 'require|max:255',
            'origin_place|产地' => 'require|array|length:3',
            'delivery_place|发货地' => 'require|array|length:3',
            'weight|总重量' => 'require|float|max:99999999.99',
            'supply_area|供货区域' => 'require|number|in:1,2',
            'pay_way|付款方式' => 'require|number|in:0,1,2',
            'remark|采购备注' => 'require|max:255',
            'cost_desc|工艺说明' => 'max:255',
            'good_img|商品图片' => 'require|array|max:10',
        ]);

        if (!$val->check($param)) return json_show(1004, $val->getError());
		$row= Db::name("filing")->findOrEmpty($param["id"]);
		if(empty($row))  return json_show(1004, "未找到数据");
        //如果是贵金属的话,额外判断
        $cat = made($param['cat_id']);
        if (isset($cat[0]['id']) && $cat[0]['id'] == 6) {
            $val_gold = Validate::rule([
                'gold_weight|贵金属重量' => 'require|float|max:99999999.99',
                'noble_metal|贵金属类型' => 'require|number|in:1,2,3',
                'config|配置要求' => 'require|max:255',
                'other_config|其他配置要求' => 'require|max:255',
            ]);
            if (!$val_gold->check($param)) return json_show(1004, $val_gold->getError());
        }

        $val2 = Validate::rule([
            'spec_id|规格id' => 'require|number|gt:0',
            'spec_value_id|规格值id' => 'require|number|gt:0',
        ]);

        $all_spec = Db::name('specs')
            ->whereIn('id', array_column($param['spec_list'], 'spec_id'))
            ->column('spec_name', 'id');

        $all_spec_value = Db::name('spec_value')
            ->whereIn('id', array_column($param['spec_list'], 'spec_value_id'))
            ->column('spec_value', 'id');

        foreach ($param['spec_list'] as &$spec_list) {
            if (!$val2->check($spec_list)) return json_show(1004, $val2->getError());
            $spec_list['spec_name'] = $all_spec[$spec_list['spec_id']] ?? '';
            $spec_list['spec_value_name'] = $all_spec_value[$spec_list['spec_value_id']] ?? '';
        }

        if ($param['is_determine_price'] == 1) $param['cgd_charge'] = round(bcsub($param['price'], $param['expect_service'], 3), 2);//确定售价时,采购价=售价-服务费
        else $param['price'] = round(bcadd($param['cgd_charge'], $param['expect_service'], 3), 2);//不确定售价时,售价=采购价+服务费

        $userCommon = \app\admin\common\User::getIns();
        $names = $userCommon->handle('getCodeAndName', ['code' => [$param['customerCode'], $param['supplierNo']]]);
        if (!isset($names['data'][$param['customerCode']]) || $names['data'][$param['customerCode']] == '') return json_show(1004, '该业务公司不存在');
        if (!isset($names['data'][$param['supplierNo']]) || $names['data'][$param['supplierNo']] == '') return json_show(1004, '该供应商不存在');
        $data=array_merge($param,[
                'customerName' => $names['data'][$param['customerCode']],
                'supplierName' => $names['data'][$param['supplierNo']],
                'service_proportion' => $param['expect_service_proportion'],//服务费比例与期望服务费比例一致
                'service_charge' => $param['expect_service'],//服务费与期望服务费一致
                'specinfo' => json_encode($param['spec_list']),
                'wait_num'=>$param['num'],
                'send_way' => 2,
                'status'=>0,
                'is_check'=>0,
                'fill_url'=>$param['fill_url'],
                'apply_id' => $this->uid,
                'apply_name' => $this->uname,
                'updaterid' => $this->uid,
                'updater' => $this->uname,
                'updatetime' => date('Y-m-d H:i:s'),
                'gold_weight' => $param['gold_weight'] ?? 0,
                'noble_metal' => $param['noble_metal'] ?? 0,
                'config' => $param['config'] ?? '',
                'other_config' => $param['other_config'] ?? '',
                'good_img' => implode(',', $param['good_img']),
                'origin_place' => implode(',', $param['origin_place']),
                'delivery_place' => implode(',', $param['delivery_place']),
            ]);
        $rs = Db::name('filing')
            ->save(array_intersect_key($data,$row));
				$stn = ['order_code' => $row['filingCode'], 'status' => 0, 'action_remark' => '', 'action_type' => 'edit'];
                ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], $stn, 'BBD',  $row['status'], $data);
                	$process=[
                            'order_type' => 'BBD',
                            'order_code' => $row['filingCode'],//出库单号
                            'order_id' => $row['id'],
                            'order_status' => 0,
                            'before_status' => $row['status'],
                            'holder_id'=>0,
                        ];
			ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname],$process);
        return $rs ? json_show(0, '报备单更新成功') : json_show(1004, '报备单更新失败');

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

        $rs = Db::name('filing')
            ->alias('a')
            ->field('a.*,b.brand_name,d.unit unit_name,p.platform_name,"" cat_info')
            ->leftJoin('brand b', 'b.id=a.brand_id')
            ->leftJoin('unit d', 'd.id=a.unit_id')
            ->leftJoin('platform p', 'p.id=a.platform_id')
            ->where(['a.is_del' => 0, 'a.id' => $param['id']])
            ->withAttr('specinfo', function ($val) {
                return json_decode($val);
            })
            ->withAttr('good_img', function ($val) {
                return explode(',', $val);
            })->withAttr('origin_place', function ($val) {
                return explode(',', $val);
            })->withAttr('delivery_place', function ($val) {
                return explode(',', $val);
            })->withAttr('cat_info', function ($val, $da) {
                return made($da['cat_id']);
            })
            ->findOrEmpty();
        if(!empty($rs['origin_place']))$origin = ["provice_code"=>$rs['origin_place'][0]??"","city_code"=>$rs['origin_place'][1]??'','area_code'=>$rs['origin_place'][2]??''];
        $rs["origin_place_cn"] = GetAddr(json_encode($origin));
        if(!empty($rs['delivery_place']))$deliev = ['provice_code'=>$rs['delivery_place'][0]??'','city_code'=>$rs['delivery_place'][1]??'','area_code'=>$rs['delivery_place'][2]??''];
        $rs['delivery_place_cn'] = GetAddr(json_encode($deliev));
        return json_show(0, '获取报备单详情成功', $rs);
//        return FilingLogic::detail($param);
    }

    //0 待审核  1 待修改 不合规 2 合规可转单 3 部分 4 转单成功 5取消转单
    public function status()
    {
        if ($this->level != 2) return json_show(1004, '业务公司账号不能审核');

        $param = $this->request->only(['id', 'companyCode', 'plat_code' => '','platform_id',"remark"=>"",'is_check'=>''], 'post');

        $val = Validate::rule([
            'id' => 'require|number|gt:0',
            'companyCode|客户' => 'requireIf:is_check,2|length:18',
            'platform_id|平台id' => 'requireIf:is_check,2|number|gt:0',
            'plat_code|平台商品编号' => 'requireIf:is_check,2|max:255',
            "is_check|是否合规"=> 'require|number|in:1,2',
            "remark|备注"=> 'requireIf:is_check,1',
        ]);

        if (!$val->check($param)) return json_show(1004, $val->getError());
        $rs = Db::name('filing')
            ->field('id,filingCode,status,is_determine_price,price,cgd_charge,platform_id,customerCode,customerName')
            ->where(['is_del' => 0, 'id' => $param['id'],"status"=>0])
            ->findOrEmpty();
        if (empty($rs)) return json_show(1005, '该报备单不存在或不允许审核');

		 $update = array_merge($param, [
            'status'=>$param['is_check'],
            'updaterid' => $this->uid,
            'updater' => $this->uname,
            'updatetime' => date('Y-m-d H:i:s'),
        ]);
		 //不合规则不处理原数据
        if($param["is_check"]==2){
	        $userCommon = \app\admin\common\User::getIns();
	        $company = $userCommon->handle('cInfo', ['companyNo' => $param['companyCode']]);
	        if (!isset($company['data'])) return json_show(1005, '该客户不存在');
	        $update['companyName']=$company['data']['companyName']??"";
	                   $tmp = Db::name('platform')
	            ->where(['is_del' => 0, 'id' => $param['platform_id']])
	            ->field('id,is_select_pay_rate,status')
	            ->findOrEmpty();
	        if (empty($tmp)) return json_show(1005, '该平台不存在');
	        if ($tmp['status'] != 1) return error_show(1004, '平台信息已禁用');
		    if($tmp['is_select_pay_rate']==1 && channel_is_company($param['platform_id'],$rs['customerCode']))return
		    error_show(1004, "平台渠道包含当前业务公司 {$rs['customerName']}");
        }
 


        //校验支付渠道中的业务公司是否与报备单业务公司重复
//
//        $update = array_merge($param, [
//            'companyName' =>  $companyName,
//            "status"=>$param["is_check"],
//            'updaterid' => $this->uid,
//            'updater' => $this->uname,
//            'updatetime' => date('Y-m-d H:i:s'),
//        ]);
//
//        if ($rs['is_determine_price'] == 1) $update['cgd_charge'] = round(bcsub($rs['price'], $param['service_charge'], 3), 2);//确定售价时,采购价=售价-服务费
//        else $update['price'] = round(bcadd($rs['cgd_charge'], $param['service_charge'], 3), 2);//不确定售价时,售价=采购价+服务费

        $res = Db::name('filing')
            ->where(['is_del' => 0, 'id' => $param['id']])
            ->whereIn('status', 0)
            ->update($update);
        		 $stn = ['order_code' => $rs['filingCode'], 'status' =>$param['is_check'], 'action_remark' => '', 'action_type' => 'status'];
                ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], $stn, 'BBD', 0, $update);
                    $process=[
                            'order_type' => 'BBD',
                            'order_code' => $rs['filingCode'],//出库单号
                            'order_id' => $rs['id'],
                            'order_status' =>$param['is_check'],
                            'before_status' =>$rs['status'],
                            'holder_id'=>0,
                        ];
			ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname],$process);
        return $res ? json_show(0, '操作成功') : json_show(1004, '操作失败');


//        return FilingLogic::status($param);
    }

    //取消转单
    public function cancel()
    {
        if ($this->level == 1) return json_show(1004, '超管不允许操作');

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


        $where = [
            ['is_del', '=', 0],
            ['id', '=', $param['id']],
            ['status', 'in', [0, 1, 2]]
        ];

        $rs = Db::name('filing')
            ->field('id,status,supplierNo,filingCode')
            ->where($where)
            ->findOrEmpty();
        if (empty($rs)) return json_show(1005, '该报备单不存在或不允许取消');

        if ($this->level == 2) {
            $supp = get_personid_by_supplierNo([$rs['supplierNo']]);
            if ($this->uid != $supp[$rs['supplierNo']]) return json_show(1004, '只有供应商负责人才能操作');
        }

        $res = Db::name('filing')
            ->where($where)
            ->update(['status' => 5, 'updatetime' => date('Y-m-d H:i:s'), 'updaterid' => $this->uid, 'updater' => $this->uname,]);
         $stn = ['order_code' => $rs['filingCode'], 'status' =>5, 'action_remark' => '', 'action_type' =>'status'];
         ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], $stn, 'BBD', $rs['status'], $param);
         $process=[
                            'order_type' => 'BBD',
                            'order_code' => $rs['filingCode'],//出库单号
                            'order_id' => $rs['id'],
                            'order_status' =>5,
                            'before_status' =>$rs['status'],
                            'holder_id'=>0,
                        ];
			ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname],$process);
        return $res ? json_show(0, '操作成功') : json_show(1004, '操作失败');
    }

    //转单
    public function transfer()
    {
        if ($this->level == 1) return json_show(1004, '超管不允许操作');

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

        $val = Validate::rule([
            'id|报备的主键id' => 'require|number|gt:0',
            "customerCode|客户编号"=>"require|max:255",
            'addr_list|收货地址' => 'require|array|max:100',
        ]);

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

        $val2 = Validate::rule([
            'receipt_quantity|收货数量' => 'require|number|gt:0|max:999999999',
            'contactor|联系人' => 'require|max:255',
            'mobile|联系电话' => 'require|mobile',
            'addr_code|收货省市区编码' => 'array|length:3',
            'addr|详细地址' => 'require|max:255',
        ]);


        foreach ($param['addr_list'] as $addr_list) {
            if (!$val2->check($addr_list)) return json_show(1004, $val2->getError());
        }
		
        $filing = Db::name('filing')
            ->field(true)
            ->where(['is_del' => 0, 'id' => $param['id'], 'status' => [2,3]])
            ->findOrEmpty();
        if (empty($filing)) return json_show(1005, '该报备单不存在或不允许转单');
        $send_num = array_sum(array_column($param['addr_list'], 'receipt_quantity'));
		$wait_num = $filing['wait_num'] - $send_num ;
        if ($wait_num<0) return json_show(1004, '收货地址的收货总数超过报备单可转单数量');
        
        $userCommon = \app\admin\common\User::getIns();
        $supplier = $userCommon->handle('sInfo', ['code' => $filing['supplierNo']]);

        $names = $userCommon->handle('getCodeAndName', ['code' => [ $param['customerCode']]]);
		if (!isset($names['data'])) return json_show(1005, '该客户不存在');
        //level3账号都可以操作
        //level2账号的话,只有供应商负责人能操作
        if (($this->level == 2) && ($this->uid != $supplier['data']['personid'])) return json_show(1004, '只有供应商负责人才能操作');

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

        Db::startTrans();

        try {

            $order_type = 4;//报备商品
            $order_source = 7;//报备转单

            $spuCode = makeNo('SKU');

            //商品表
         $goodIn=   Db::name('good_zixun')
                ->insert([
                    'spuCode' => $spuCode,
                    'good_name' => $filing['good_name'],
                    'brand_id' => $filing['brand_id'],
                    'cat_id' => $filing['cat_id'],
                    'good_unit' => $filing['unit_id'],
                    'good_type' => 0,
                    'moq' => 1,
                    'customized' => $filing['make_day'],
                    'tax' => $filing['tax'],
                    'platform_id' => $filing['platform_id'],
                    'supplierNo' => $filing['supplierNo'],
                    'supplierName' => $supplier['data']['name'],
                    'is_auth' => 0,
                    'craft_desc' => $filing['good_name'],
                    'good_remark' => '',
                    'good_img' => $filing['good_img'],
                    'good_thumb_img' => '',
                    'good_info_img' => '',
                    'status' => 1,
                    'createrid' => $filing['updaterid'],
                    'creater' => $filing['updater'],
                    'is_del' => 0,
                    'addtime' => $date,
                    'updatetime' => $date,
                    'specinfo' => $filing['specinfo'],
                    'work_day' => $filing['make_day'],
                    'noble_metal' => $filing['noble_metal'],
                    'is_gold_price' => $filing['is_gold_price'],
                    'good_weight' => $filing['gold_weight'],
                    'config' => $filing['config'],
                    'other_config' => $filing['other_config'],
                    'weight' => $filing['weight'],
                    'supply_area' => $filing['supply_area'],
                    'is_diff' => $filing['is_diff'],
                    'pay_way' => $filing['pay_way'],
                    'send_way' => $filing['send_way'],
                    'companyNo' => $filing['customerCode'],
                    'companyName' => $filing['customerName'],
                    'proof_type' => '',
                    'proof_url' => '',
                    'order_type' => $order_type
                ]);
			if($goodIn==false) throw new \Exception("商品录入商品库失败");
            $orderCode = makeNo('QR');
            //订单表
            //sale
            $sale_id = Db::name('sale')->insertGetId([
                'orderCode' => $orderCode,
                'apply_id' => $filing['updaterid'],
                'apply_name' => $filing['updater'],
                'order_type' => $order_type,//报备商品
                'order_source' => $order_source,//报备转单
                'platform_id' => $filing['platform_id'],
                'good_code' => $spuCode,
                'skuCode' => '',
                'cat_id' => $filing['cat_id'],
                'good_name' => $filing['good_name'],
                'good_num' => $send_num,
                'good_type' => 1,
                'origin_price' => $filing['cgd_charge'],
                'sale_price' => $filing['price'],
                'total_price' => round(bcmul($filing['price'], $filing['num'], 3), 2),
                'post_fee' => 0,
                'is_diff' => $filing['is_diff'],
                'is_activity' => 0,
                'activity_code' => '',
                'is_stock' => 0,
                'customer_code' => $param['customerCode'],
                'customerName' => $names['data'][$param['customerCode']]??"",
                'supplierNo' => $filing['customerCode'],
                'supplierName' => $filing['customerName'],
                'supNo' => $filing['supplierNo'],
                'supName' => $filing['supplierName'],
                'zxNo' => '',
                'platform_order' =>$filing['filingCode'],
                'send_num' => 0,
                'wsend_num' => $send_num,
                'th_num' => 0,
                'th_fee' => 0,
                'send_status' => 1,
                'send_type' => 1,//直接发货
                'remark' => '',
                'status' => 0,
                'is_del' => 0,
                'proof_id' => 0,
                'other_orderNo' => '',
                'workNo' => '',
                'poNo' => '',
                'use_order' => 0,
                'good_weight' => 0,
                'gold_price' => 0,
                'cost_price' => $filing['cost_fee'],
                'diff_weight' => 0,
                'diff_fee' => 0,
                'returnCode' => '',
                'addtime' => $date,
                'updatetime' => $date,
                'cgderid' => $supplier['data']['personid'],
                'cgder' => $supplier['data']['person'],
                'good_createrid' => $filing['updaterid'],
                'good_creater' => $filing['updater'],
                 'manager'=>$filing['manager'],
                'managerid'=>$filing['managerid'],
            ]);
			if($sale_id==false)  throw new \Exception('订单生成失败');
			 ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], [
                    'order_code' => $orderCode,//销售单code
                    'status' => 0,//这里的status是之前的值
                    'action_remark' => '',//备注
                    'action_type' => 'create'//新建create,编辑edit,更改状态status
                ], 'XSQRD', 0, $this->post);

                ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname], [
                    'order_type' => 'XSQRD',
                    'order_code' => $orderCode,//销售单code
                    'order_id' => $sale_id,
                    'order_status' => 0,
                    'before_status' => 0,
                    'holder_id' => $this->uid
                ]);
            //仓库
            $wsm = Db::name('warehouse_info')
                ->field('id,wsm_code')
                ->where(['supplierNo' => $filing['supplierNo'], 'companyNo' => $filing['customerCode'], 'is_del' => 0])
                ->findOrEmpty();
            if (empty($wsm)) {
                $wsm_code = makeNo('WSM');
              $ws=  Db::name('warehouse_info')->insert([
                    'wsm_code' => $wsm_code,
                    'name' => $supplier['data']['name'],
                    'wsm_type' => 2,
                    'supplierNo' => $supplier['data']['code'],
                    'addr' => '',
                    'addrs_code' => '',
                    'contactor' => 0,
                    'contactor_name' => 0,
                    'mobile' => '',
                    'position' => '',
                    'companyNo' => $filing['supplierNo'],
                    'status' => 1,
                    'is_del' => 0,
                    'addtime' => $date,
                    'updatetime' => $date,
                ]);
              if($ws==false)throw new \Exception('仓库生成失败');
            } else  $wsm_code = $wsm['wsm_code'];

            //采购单
            $cgdCode = makeNo('CG');

           $cg= Db::name('purchease_order')->insertGetId([
                'cgdNo' => $cgdCode,
                'bkcode' => '',
                'wsm_code' => $wsm_code,
                'cgder' => $supplier['data']['person'],
                'cgder_id' => $supplier['data']['personid'],
                'spuCode' => $spuCode,
                'good_name' => $filing['good_name'],
                'good_num' => $send_num,
                'good_price' => $filing['cgd_charge'],
                'total_fee' => round(bcmul($filing['cgd_charge'], $filing['num']), 2),
                'pakge_fee' => $filing['pakge_fee'],
                'cert_fee' => $filing['cert_fee'],
                'open_fee' => $filing['open_fee'],
                'delivery_fee' => $filing['delivery_fee'],
                'mark_fee' => $filing['mark_fee'],
                'demo_fee' => $filing['demo_fee'],
                'diff_weight' => '0',
                'diff_fee' => '0',
                'gold_price' => '0',
                'supplierNo' => $filing['supplierNo'],
                'supplier_name' => $filing['supplierName'],
                'companyNo' => $filing['customerCode'],
                'companyName' => $filing['customerName'],
                'send_status' => 1,
                'send_num' => '0',
                'wsend_num' => $send_num,
                'remark' => '',
                'status' => 0,
                'lasttime' => $date,
                'is_del' => 0,
                'order_type' => $order_type,
                'order_source' => $order_source,
                'good_type' => 1,
                'addtime' => $date,
                'updatetime' => $date,
                'good_createrid' => $filing['updaterid'],
                'good_creater' => $filing['updater'],
            ]);
			if($cg==false)throw new \Exception('采购单生成失败');
			ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], [
                'order_code' =>$cgdCode,//销售单code
                'status' => 0,//这里的status是之前的值
                'action_remark' => '',//备注
                'action_type' => 'create'//新建create,编辑edit,更改状态status
            ], 'CGD', 0, $param);

            //当节点是0待与供应商确认,推给供应商负责人
            ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname], [
                'order_type' => 'CGD',
                'order_code' => $cgdCode,//销售单code
                'order_id' => $cg,
                'order_status' => 0,
                'before_status' => 0,
                'holder_id' => $this->uid,
                'wait_id'=>$this->uid,
                'wait_name'=>$this->uname,
            ]);
            //台账
            $standing_bood_data = [
                'standBookNo' => makeNo('IO'),
                'orderCode' => $orderCode,
                'sale_id' => $sale_id,
                'customer_code' => $filing['companyCode'],
                'supplierNo' => $filing['supplierNo'],
                'order_type' => $order_type,
                'order_source' => $order_source,
                'spuCode' => $spuCode,
                'addtime' => $date,
                'updatetime' => $date,
                'cgdNo' => $cgdCode,
            ];

            $i = 0;
            $order_send_insert = [];
            foreach ($param['addr_list'] as $addr) {
                //地址addr
                $addrid = Db::name('order_addr')->insertGetId([
                    'orderCode' => $orderCode,
                    'addr' => $addr['addr'],
                    'addr_code' =>empty( $addr['addr_code'])?"": implode(',', $addr['addr_code']),
                    'contactor' => $addr['contactor'],
                    'mobile' => $addr['mobile'],
                    'customer_code' => $param['customerCode'],
                    'post_fee' => 0,
                    'receipt_quantity' => $addr['receipt_quantity'],
                    'is_del' => 0,
                    'addtime' => $date,
                    'updatetime' => $date,
                ]);
				if($addrid==false)throw new \Exception('地址生成失败');
                //发货单
                $outCode = makeNo('DF');
                //改变编码规则,将原来的编码后两位换成序列号
                //str_pad字符串填充
                $outCode = substr($outCode, 0, -2) . str_pad($i, 2, '0', STR_PAD_LEFT);
               $send= Db::name('order_out')->insertGetId([
                    'orderCode' => $orderCode,
                    'outCode' => $outCode,
                    'apply_id' => $filing['updaterid'],
                    'apply_name' => $filing['updater'],
                    'addrid' => $addrid,
                    'post_name' => '',
                    'post_code' => '',
                    'post_fee' => 0,
                    'sendtime' => $date,
                    'send_num' => $addr['receipt_quantity'],
                    'check_num' => 0,
                    'error_num' => 0,
                    'wsm_code' => $wsm_code,
                    'order_type' => $order_type,
                    'status' => 0,
                    'addtime' => $date,
                    'updatetime' => $date,
                ]);
               if($send==false) throw new \Exception('发货单生成失败');
                 ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname], [
                                            'order_type' => 'CKD',
                                            'order_code' => $outCode,//出库单号
                                            'order_id' => $send,
                                            'order_status' => 0,
                                            'before_status' => 0,
                                            'wait_id'=>0,
                                            'wait_name'=>0,
                                        ]);
                $standing_bood_data['outCode'][] = $outCode;
                $order_send_insert[] = [
                    'cgdNo' => $cgdCode,
                    'outCode' => $outCode,
                    'send_num' => $addr['receipt_quantity'],
                    'bnCode' => '',
                    'status' => 1,
                    'addtime' => $date,
                    'updatetime' => $date,
                ];
                $i++;
            }

            //更新报备单
           $fillup= Db::name('filing')
                ->where(['is_del' => 0, 'id' => $param['id'], 'status' => [2,3]])
                ->update([
                	'status' =>$wait_num>0?3:4,
                	'wait_num' =>$wait_num,
                	'transfer_num' =>$filing['transfer_num']+$send_num,
                    'updatetime' => $date,
                    'spuCode' => $spuCode,
                    'orderCode' =>$filing["orderCode"].$orderCode.",",
                    'reason' => '',
                    'updaterid' => $this->uid,
                    'updater' => $this->uname]);
	  
			if($fillup==false)throw new \Exception('报备单更新失败');
            //待办已办先不处理
			$stn = ['order_code' => $filing['filingCode'], 'status' =>$wait_num>0?3:4, 'action_remark' => '', 'action_type' => 'status'];
            ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], $stn, 'BBD', $filing['status'], $param);
                     $process=[
                            'order_type' => 'BBD',
                            'order_code' => $filing['filingCode'],//出库单号
                            'order_id' => $filing['id'],
                            'order_status' =>$wait_num>0?3:4,
                            'before_status' =>$filing['status'],
                            'holder_id'=>0,
                        ];
			ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname],$process);
            //关联表
           $gu= Db::name('order_num')
                ->insert([
                    'orderCode' => $orderCode,
                    'cgdNo' => $cgdCode,
                    'spuCode' => $spuCode,
                    'companyNo' => $filing['customerCode'],
                    'good_num' => $send_num,
                    'wsend_num' =>$send_num,
                    'send_num' => 0,
                    'wait_num' => $send_num,
                ]);
			if($gu==false) throw new \Exception('关联表新建失败');
            if ($order_send_insert) Db::name('order_send')->insertAll($order_send_insert);


            //处理台账
            if (isset($standing_bood_data['outCode']) && is_array($standing_bood_data['outCode'])) $standing_bood_data['outCode'] = implode(',', $standing_bood_data['outCode']);

            Db::name('standing_book')->insert($standing_bood_data);

            Db::commit();
            return json_show(0, '转单成功');

        } catch (\Exception $exception) {
            Db::rollback();
            return json_show(1005, '转单失败,' . $exception->getMessage());
        }
    }

    //订单录入
    public function orderAdd()
    {
        $param = $this->request->param([
            "companyNo" => '',
            "poCode" => "",
            "workCode" => "",
            "khNo" => "",
            "qrdType" => 3,
            "goodName" => "",
            "tax" => "",
            "goodNum" => "",
            "goodPrice" => "",
            "sale_total" => "",
            "goodUnit" => "",
            "mobile" => "",
            "addr" => "",
            "addr_code" => "",
            "contactor" => "",
            "sendtime" => "",
            "cat_id" => '',
            "supplierNo" => "",
            "cgdPrice" => "",
            "cgd_total" => "",
            "platform_id" => "0",
        ], "post", "trim");

        $valid = Validate::rule([
            "companyNo|业务公司编号" => "require|max:255|min:1",
            "supplierNo|业务公司编号" => "require|max:255|min:1",
            "poCode|PO编号" => "require|max:255|min:1",
            "khNo|客户公司编号" => "require|max:255|min:1",
            "qrdType|订单类型" => "require|number|in:1,2,3",
            "goodName|商品名称" => "require|max:255|min:1",
            "goodUnit|商品单位" => "require|number|gt:0",
            "tax|税率" => "require|number|gt:0",
            "goodNum|商品数量" => "require|number|gt:0",
            "sale_total|销售总额" => "require|float|gt:0",
            "cgd_total|采购总额" => "require|float|gt:0",
//            "goodPrice|商品单价" => "require|float|gt:0",
            "mobile|联系人电话" => "require|number|mobile",
            "contactor|联系人" => "require|max:255|min:1",
            "addr|收货地址" => "require|max:255|min:1",
            "sendtime|发货时间" => "require|date",
            "cat_id|商品分类id" => "require|number|gt:0",
//            "cgdPrice|采购单价" => "require|float|gt:0",
            "platform_id|平台" => "require|number"
        ]);
        if ($valid->check($param) == false) return error_show(1004, $valid->getError());
        $qrdcode = makeNo("QR");
        $cgddcode = makeNo("CG");
        $goodCode = makeNo("SKU");
        $userCommon = \app\admin\common\User::getIns();
        $tmp = $userCommon->handle('getCodeAndName',['code'=>[$param['khNo'],$param['supplierNo'],$param['companyNo']]]);
        if(!isset($tmp['code']) || $tmp['code']!=0) return json_show($tmp['code'],$tmp['message'],$tmp['data']);
        if(!isset($tmp['data'][$param['khNo']])) return json_show(1004, "未找到客户数据");
        if(!isset($tmp['data'][$param['supplierNo']])) return json_show(1004, "未找到平台供应商数据");
        if(!isset($tmp['data'][$param['companyNo']])) return json_show(1004, "未找到平台业务公司数据");

            $payinfo = Db::name("platform")->where(["id"=> $param['platform_id'],"is_del"=>0])->findOrEmpty();
            if (empty($payinfo)) return error_show(1004, "平台信息未找到");
            if ($payinfo['status'] != 1) return error_show(1004, "平台信息已禁用");
            if($payinfo['is_select_pay_rate']==1 && channel_is_company($param['platform_id'],$param['companyNo']))return error_show(1004, "平台渠道包含当前业务公司 {$tmp['data'][$param['companyNo']]}");

		$supplierinfo = $userCommon->handle("hqInfo",["code"=>$param['supplierNo']]);
		if(!isset($supplierinfo['data'])|| empty($supplierinfo['data'])) return json_show(1004, "未找到供应商公司数据");
		$person =$supplierinfo['data']['child']??["person"=>'',"person_id"=>0];
		 if($param['companyNo']== $supplierinfo['data']['relation_code']) return json_show(1004,'供应商和业务公司不能为同一家公司');
		 $cgdprice = round($param['cgd_total']/$param['goodNum'],2);
		 $saleprice = round($param['sale_total']/$param['goodNum'],2);
        $qrddata = [
            "orderCode" => $qrdcode,
            "apply_id" => $this->uid,
            "apply_name" => $this->uname,
            "order_type" => $param['qrdType'],
            "order_source" => 9,
            "platform_id" => $param['platform_id'],
            "good_code" => $goodCode,
            "skuCode" => '',
            "cat_id" => $param['cat_id'],
            "good_name" => $param['goodName'],
            "good_num" => $param['goodNum'],
            "good_type" => 1,
            "origin_price" => $cgdprice,
            "sale_price" => $saleprice,
            "total_price" =>$param['sale_total'],
            "post_fee" => 0,
            "is_diff" => 0,
            "is_activity" => 0,
            "activity_code" => '',
            "is_stock" => 0,
            "arrive_time" => $param['sendtime'],
            "customer_code" => $param['khNo'],
            "customerName" => $tmp['data'][$param['khNo']],
            "supplierNo" => $param['companyNo'],
            "supplierName" =>$tmp['data'][$param['companyNo']],
            "supName" => $tmp['data'][$param['supplierNo']],
            "supNo" => $param['supplierNo'],
            "platform_order" => $param['poCode'],
            "send_num" => $param['goodNum'],
            "wsend_num" => 0,
            "send_status" => 3,
            "send_type" => 1,
            "status" => 2,
            "is_del" => 0,
            "pay_id" => 0,
            "workNo" => $param['workCode'],
            "addtime" => date("Y-m-d H:i:s"),
            "updatetime" => date("Y-m-d H:i:s"),
            "cgderid" => $person['personid'],
            "cgder" => $person['person'],
            "good_createrid" => $this->uid,
            "good_creater" => $this->uname
        ];
        $orderCgd = [
            "orderCode" => $qrdcode,
            "cgdNo" => $cgddcode,
            "spuCode" => $goodCode,
            "good_num" => $param['goodNum'],
            "wsend_num" => 0,
            "send_num" => $param['goodNum'],
            "wait_num" => 0
        ];
        $cgddata = [
            "cgdNo" => $cgddcode,
            "bkcode" => '',
            "wsm_code" => "",
            "cgder_id" => $person['personid'],
            'cgder' => $person['person'],
            "spuCode" => $goodCode,
            "good_name" => $param['goodName'],
            "good_num" => $param['goodNum'],
            "good_price" => $cgdprice,
            "total_fee" => $param['cgd_total'],
            "supplierNo" => $param['supplierNo'],
            "supplier_name" =>$tmp['data'][$param['supplierNo']],
            "companyNo" => $param['companyNo'],
            "companyName" => $tmp['data'][$param['companyNo']],
            "send_status" => 3,
            "send_num" => $param['goodNum'],
            "wsend_num" => 0,
            "status" => 3,
            "lasttime" => date("Y-m-d H:i:s"),
            "order_type" => $param['qrdType'],
            "order_source" => 9,
            "addtime" => date("Y-m-d H:i:s"),
            "updatetime" => date("Y-m-d H:i:s"),
            "good_createrid" => $this->uid,
            "good_creater" => $this->uname,
        ];
        $goodinfo = [
            "spuCode" => $goodCode,
            "good_name" => $param['goodName'],
            "brand_id" => 0,
            "cat_id" => $param['cat_id'],
            "good_unit" => $param['goodUnit'],
            "good_type" => 1,
            "moq" => 1,
            "customized" => 0,
            "platform_id" => $param['platform_id'],
            "tax" => $param['tax'],
            "supplierNo" => $param['supplierNo'],
            "supplierName" =>$tmp['data'][$param['supplierNo']],
            "is_auth" => 1,
            "craft_desc" => '',
            "good_remark" => '',
            "good_img" => '',
            "good_thumb_img" => '',
            "good_info_img" => '',
            "createrid" => $this->uid,
            "creater" => $this->uname,
            "specinfo" => '',
            "work_day" => 0,
            "noble_metal" => 0,
            "good_weight" => 0,
            "config" => "",
            "weight" => 0,
            "supply_area" => 0,
            "is_diff" => 0,
            "pay_way" => 0,
            "send_way" => 0,
            "companyNo" => $param['companyNo'],
            "companyName" => $tmp['data'][$param['companyNo']],
            "addtime" => date("Y-m-d H:i:s"),
            "updatetime" => date("Y-m-d H:i:s"),
        ];
        $orderAddr = [
            "orderCode" => $qrdcode,
            "addr" => $param['addr'],
            "addr_code" => $param['addr_code'],
            "contactor" => $param['contactor'],
            "mobile" => $param['mobile'],
            "arrive_time" => $param['sendtime'],
            "customer_code" => $param['khNo'],
            "receipt_quantity" => $param['goodNum'],
            "addtime" => date("Y-m-d H:i:s"),
            "updatetime" => date("Y-m-d H:i:s"),
        ];
        Db::startTrans();
        try {
            $qrd = Db::name("sale")->insert($qrddata);
            if ($qrd == false) throw new \Exception("销售单生成失败");
            $qrd = Db::name("order_num")->insert($orderCgd);
            if ($qrd == false) throw new \Exception("销售单采购管联生成失败");
            $qrd = Db::name("purchease_order")->insert($cgddata);
            if ($qrd == false) throw new \Exception("采购单生成失败");
            $qrd = Db::name("good_zixun")->insert($goodinfo);
            if ($qrd == false) throw new \Exception("商品信息录入生成失败");
            $qrd = Db::name("order_addr")->insert($orderAddr);
            if ($qrd == false) throw new \Exception("销售单地址生成失败");
            Db::commit();
            return app_show(0, '订单生成成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return error_show(1004, $exception->getMessage());
        }
    }

    public function orderInfo()
    {
        $param = $this->request->param(["orderCode"], "post", "trim");
        if ($param['orderCode'] == '') return error_show(1004, "订单编号不能为空");
        $saleinfo = Db::name("sale")->where(["orderCode" => $param['orderCode']])->findOrEmpty();
        if (empty($saleinfo)) return error_show(1004, "销售单不存在");
        if ($saleinfo['order_source'] != 9) return error_show(1004, "销售单来源不是网络录入");
        $cgd = Db::name("purchease_order")->alias("a")
            ->leftJoin("order_num b", "a.cgdNo=b.cgdNo")
            ->where(["b.orderCode" => $param['orderCode']])
            ->field("a.*")
            ->findOrEmpty();
        if (empty($cgd)) return error_show(1004, "采购单不存在");
        $goodinfo = Db::name("good_zixun")->where(["spuCode" => $saleinfo['good_code']])->findOrEmpty();
        if (empty($goodinfo)) return error_show(1004, "商品信息不存在");
        $addr = Db::name("order_addr")->where(["orderCode" => $param['orderCode']])->findOrEmpty();
        if (empty($addr)) return error_show(1004, "地址信息不存在");
        $addinfo = $addr['addr_code'] != '' ? json_decode($addr['addr_code'], true) ?? $addr['addr_code'] : '';
        if (is_string($addinfo) && $addinfo != '') {
            $addinfo = ["provice_code" => '', "city_code" => '', "area_code" => ''];
            list($addinfo['provice_code'], $addinfo['city_code'], $addinfo['area_code']) = explode(",", $addr['addr_code']);
        }
		$platform = Db::name("platform")->where(["id" => $saleinfo['platform_id']])->field("platform_name,pay_title")
		->findOrEmpty();

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

        $data = [
            "orderCode" => $saleinfo['orderCode'],
            "companyNo" => $saleinfo['supplierNo'],
            "companyName" => $names['data'][$saleinfo['supplierNo']] ?? '',//Db::name("supplier")->where(["code" => $saleinfo['supplierNo']])->value("name", ''),
            "poCode" => $saleinfo['platform_order'],
            "workCode" => $saleinfo['workNo'],
            "platform_id" => $saleinfo['platform_id'],
            "platform_name" =>$platform['platform_name']??"",
            "khNo" => $saleinfo['customer_code'],
            "khName" => $names['data'][$saleinfo['customer_code']] ?? '',//Db::name("customer_info")->where(["companyNo" => $saleinfo['customer_code']])->value("companyName", ''),
            "qrdType" => $saleinfo['order_type'],
            "goodName" => $saleinfo['good_name'],
            "tax" => $goodinfo['tax'],
            "goodUnit" => $goodinfo['good_unit'],
            "unitName" => Db::name("unit")->where(["id" => $goodinfo['good_unit']])->value("unit", ""),
            "goodNum" => $saleinfo['good_num'],
            "goodPrice" => $saleinfo['sale_price'],
            "sale_total" => $saleinfo['total_price'],
            "mobile" => $addr['mobile'],
            "addr" => $addr['addr'],
            "addr_cn" => GetAddr(json_encode($addinfo)),
            "addr_code" => $addr['addr_code'],
            "contactor" => $addr['contactor'],
            "buyerid" => $saleinfo['cgderid'],
            "buyer_name" => $saleinfo['cgder'],
            "sendtime" => $saleinfo['arrive_time'],
            "cat_id" => made($saleinfo['cat_id']),
            "cat_name" => Db::name("cat")->where(["id" => $saleinfo['cat_id']])->value("cat_name", ''),
            "supplierNo" => $cgd['supplierNo'],
            "supplierNanme" => $cgd['supplier_name'],
            "cgd_tax" => round((1 -  $cgd['total_fee']/ $saleinfo['total_price']), 4) * 100,
            "cgdPrice" => $saleinfo['origin_price'],
            "cgd_total" => $cgd['total_fee'],
            "pay_id" => $saleinfo['pay_id'],
            "pay_name" =>$platform['pay_title']??"",
        ];
        return app_show(0, "获取成功", $data);
    }

    public function orderEdit()
    {
        $param = $this->request->param([
            "orderCode" => "",
            "poCode" => "",
            "workCode" => "",
            "tax" => "",
            "goodUnit" => "",
            "mobile" => "",
            "addr" => "",
            "addr_code" => "",
            "contactor" => "",
            "sendtime" => "",
            "supplierNo" => "",
            "cgd_total" => "",
//            "sale_total" => "",
        ], "post", "trim");

        $valid = Validate::rule([
            "orderCode|销售单号" => "require|max:255",
            "supplierNo|供应商公司编号" => "require|max:255|min:1",
            "poCode|PO编号" => "require|max:255|min:1",
            "mobile|联系人电话" => "require|number|mobile",
            "goodUnit|商品单位" => "require|number|gt:0",
            "contactor|联系人" => "require|max:255|min:1",
            "addr|收货地址" => "require|max:255|min:1",
            "sendtime|发货时间" => "require|date",
            "tax|商品利率" => "require|number",
            "cgd_total|采购总额" => "require|float|gt:0",
//            "sale_total|销售总额" => "require|float|gt:0",
        ]);
        if ($valid->check($param) == false) return error_show(1004, $valid->getError());
        $saleinfo = Db::name("sale")->where(["orderCode" => $param['orderCode']])->findOrEmpty();
        if (empty($saleinfo)) return error_show(1004, "销售单不存在");
        if ($saleinfo['order_source'] != 9) return error_show(1004, "销售单来源不是网络录入");
        $cgd = Db::name("purchease_order")->alias("a")
            ->leftJoin("order_num b", "a.cgdNo=b.cgdNo")
            ->where(["b.orderCode" => $param['orderCode']])
            ->field("a.*")
            ->findOrEmpty();
        if (empty($cgd)) return error_show(1004, "采购单不存在");

        $userCommon = \app\admin\common\User::getIns();
        $good = Db::name("good_zixun")->where(["spuCode" => $saleinfo['good_code']])->findOrEmpty();
        if (empty($good)) return error_show(1004, "商品信息不存在");
        $addr = Db::name("order_addr")->where(["orderCode" => $param['orderCode']])->findOrEmpty();
        if (empty($addr)) return error_show(1004, "地址信息不存在");
        $cgdPrice = round($param['cgd_total']/$saleinfo['good_num'],2);
//        $salePrice = round($param['sale_total']/$saleinfo['good_num'],2);
		$supplierinfo = $userCommon->handle("hqInfo",["code"=>$param['supplierNo']]);
		if(!isset($supplierinfo['data'])|| empty($supplierinfo['data'])) return json_show(1004, "未找到供应商公司数据");
		$person =$supplierinfo['data']['child']??["person"=>'',"person_id"=>0];
		 if($cgd['companyNo']== $supplierinfo['data']['relation_code']) return json_show(1004,'供应商和业务公司不能为同一家公司');
        $qrddata = [
            "origin_price" => $cgdPrice,
            "arrive_time" => $param['sendtime'],
            "platform_order" => $param['poCode'],
            "workNo" => $param['workCode'],
            "updatetime" => date("Y-m-d H:i:s"),
            "cgderid" => $person['personid'],
            "cgder" => $person['person']
        ];
        $cgddata = [
            "cgder_id" => $person['personid'],
            'cgder' => $person['person'],
            "good_price" => $cgdPrice,
            "total_fee" => $param['cgd_total'],
            "supplierNo" => $param['supplierNo'],
            "supplier_name" => $supplierinfo['data']['name'],
//			"companyNo"=>$param['companyNo'],
            "updatetime" => date("Y-m-d H:i:s"),
        ];
        $goodinfo = [
            "good_unit" => $param['goodUnit'],
            "tax" => $param['tax'],
            "supplierNo" => $param['supplierNo'],
//            "companyNo" => $param['companyNo'],
            "updatetime" => date("Y-m-d H:i:s"),
        ];
        $orderAddr = [
            "addr" => $param['addr'],
            "addr_code" => $param['addr_code'],
            "contactor" => $param['contactor'],
            "mobile" => $param['mobile'],
            "arrive_time" => $param['sendtime'],
//            "customer_code" => $param['khNo'],
            "updatetime" => date("Y-m-d H:i:s"),
        ];
        Db::startTrans();
        try {
            $qrd = Db::name("sale")->where($saleinfo)->update($qrddata);
            if ($qrd == false) throw new \Exception("销售单更新失败");
            $qrd = Db::name("purchease_order")->where($cgd)->update($cgddata);
            if ($qrd == false) throw new \Exception("采购单更新失败");
            $qrd = Db::name("good_zixun")->where($good)->update($goodinfo);
            if ($qrd == false) throw new \Exception("商品信息更新失败");
            $qrd = Db::name("order_addr")->where($addr)->update($orderAddr);
            if ($qrd == false) throw new \Exception("销售单地址更新失败");
            Db::commit();
            return app_show(0, '订单更新成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return error_show(1004, $exception->getMessage());
        }
    }
}