<?php
namespace App\Http\Controllers\Api\Purchase;

use App\Http\Controllers\Common\CommonController;
use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Exception;
use Excel;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use App\Http\Controllers\Api\Verify\Purchase\VerifyPurchaseOrderController;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Models\Api\WorkOrder;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\AccountSubject;
use App\Http\Models\Services\WarehouseManage\PurchaseOrder;
use App\Http\Models\Services\WarehouseManage\OutinStockLock;
use App\Http\Models\Services\WarehouseManage\WareInorder;
use App\Http\Models\Services\ChannelManage\ChannelUnit;

// 仓储系统 -- 采购管理
class PurchaseOrderController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 采购列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        // $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $shop_id = $user_info->adm_shop_id;

        $where_data = $request->all();
        $page_size  = (int) $request->input('show_count', 10);
        $where_data = RemoveLineFeed($where_data);
        $wareInArr = [];
        $rukuNumArr = [];
        if (!empty($where_data['dh_start']) || !empty($where_data['dh_end'])) { //到货时间
            $wareInorder = Db::table("ware_inorder")
                ->where('rk_type', 1)
                ->where('rk_state', 5)
                ->where('company_id', $user_info->adm_cid)
                ->where('rk_shop_id', $shop_id);
            if (!empty($where_data['dh_start'])) {  //到货开始时间
                $wareInorder = $wareInorder->where('arrival_time', '>=', $where_data['dh_start']);
            }
            if (!empty($where_data['dh_end'])) {  //到货结束时间
                $wareInorder = $wareInorder->where('arrival_time', '<=', $where_data['dh_end'] . " 23:59:59");
            }
            $rukuNumArr = $wareInorder->select("rk_number")->get();
            $wareInArr = $wareInorder
                ->where('rk_waretype', 1)
                ->select('cg_number')
                ->groupBy('cg_number')
                ->get();
            $wareInArr = json_decode(json_encode($wareInArr), true);
            $rukuNumArr = json_decode(json_encode($rukuNumArr), true);
            $wareInArr = array_column($wareInArr, 'cg_number');
            $rukuNumArr = array_column($rukuNumArr, 'rk_number');
        }

        if (!empty($where_data['note_content'])) {
            // 2.删除历史搜索备注
            DB::table('order_goods_temporary')
                ->where('orgt_adm_id', $user_info->adm_id) //与类型所对应的id
                ->where('orgt_type', 3) //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单
                ->delete();
            $note_numberlist = Db::table('note')
                ->where('note_adm_cid', $user_info->adm_cid)
                ->where('note_shop_id', $shop_id)
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_userid'])) {
                        $query->where('note_adm_id', $where_data['cg_userid']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_start'])) {
                        $query->where('note_time', '>=', $where_data['create_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_end'])) {
                        $query->where('note_time', '<=', $where_data['create_end'] . ' 23:59:59');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['note_content'])) {
                        $query->where('note_content', 'like', "%" . $where_data['note_content'] . "%");
                    }
                })
                ->groupBy('note_number')
                ->select('note_number')
                ->get();
            foreach ($note_numberlist as $k => $v) {
                $temp['orgt_order_number'] = $v->note_number;
                $temp['orgt_type'] = '3';
                $temp['orgt_update_time'] = date("Y-m-d H:i:s");
                $temp['orgt_adm_id'] = $user_info->adm_id;
                $res = DB::table('order_goods_temporary')->insert($temp);
            }
            $list = Db::table('purchase_order as puor')
                ->leftjoin('order_goods_temporary as orgt', 'orgt.orgt_order_number', '=', 'puor.cg_number')
                ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'puor.cg_supplyunit')
                ->leftjoin('shop as s', 's.shop_id', '=', 'puor.cg_supplyunit')
                ->where('need_toexamine', '<', 5)
                ->where('orgt_type', 3)
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('is_del', 1)
                ->where('company_id', $user_info->adm_cid)
                ->where('cg_shop_id', $shop_id)
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_state'])) {  //采购状态
                        $query->where('cg_state', $where_data['cg_state']);
                    } else {
                        $query->where('cg_state', '!=', 18);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_number'])) {  //采购单号
                        $query->where('cg_number', 'like', '%' . $where_data['cg_number'] . '%');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['contract_number'])) { //合同号
                        $query->where('contract_number', 'like', '%' . $where_data['contract_number'] . '%');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['goods_name'])) { //包含商品
                        $query->where('goods_name', 'like', '%' . $where_data['goods_name'] . '%');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['chun_unit_name'])) { //采购单位
                        $query->where('chun_unit_name', 'like', '%' . $where_data['chun_unit_name'] . '%');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['puor_supplyunit_type'])) {
                        if ($where_data['puor_supplyunit_type'] == 2) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
                            if (!empty($where_data['shop_id'])) { //采购单位
                                $query->where('shop_id', $where_data['shop_id']);
                            }
                        } else {
                            if (!empty($where_data['chun_unit_name'])) { //采购单位
                                $query->where('chun_unit_name', 'like', '%' . $where_data['chun_unit_name'] . '%');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_wareid'])) { //仓库
                        $query->where('cg_wareid', $where_data['cg_wareid']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_settlementype'])) { //结算状态
                        $query->where('cg_settlementype', $where_data['cg_settlementype']);
                        // if ($where_data['cg_settlementype'] == '4') {
                        //     $cg_state = array(5, 8, 11, 12); //待审核生效状态
                        //     $query->whereIn('cg_state', $cg_state);
                        // }
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_userid'])) {  //创建人
                        $query->where('cg_userid', $where_data['cg_userid']);
                    }
                })
                ->where(function ($query) use ($where_data) {  //采购总额
                    if (!empty($where_data['amount_start'])) {
                        $query->where('cg_amount', '>=', $where_data['amount_start']);
                    }
                })
                ->where(function ($query) use ($where_data) { //采购总额
                    if (!empty($where_data['amount_end'])) {
                        $query->where('cg_amount', '<=', $where_data['amount_end']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_start'])) {
                        $query->where('create_time', '>=', $where_data['create_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_end'])) {
                        $query->where('create_time', '<=', $where_data['create_end'] . ' 23:59:59');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['dh_start'])) {  //到货开始时间
                        $query->where('dh_time', '>=', $where_data['dh_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['dh_end'])) {  //到货结束时间
                        $query->where('dh_time', '<=', $where_data['dh_end']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_supplyunit'])) {
                        $query->where('cg_supplyunit', $where_data['cg_supplyunit']);
                    }
                }) //供货单位
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_paymentype'])) {
                        $query->where('cg_paymentype', $where_data['cg_paymentype']);
                    }
                }) //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天8免费
                ->select('cg_id', 'cg_number', 'cg_yfmoney', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_paytype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'chun_unit_name', 'cg_creator', 'cg_delivertype', 'cg_invoicetype', 'cg_settlementype', 'business_type', 'auditor_user', 'contact_name', 'contact_phone', 'cg_original_number', 'cg_types', 'create_time', 'orgt_order_number', 'puor_supplyunit_type', 'puor_reject_reason')
                ->orderBy('create_time', 'desc')
                ->paginate($page_size);
        } else {
            $list = Db::table('purchase_order as puor')
                ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'puor.cg_supplyunit')
                ->where('need_toexamine', '<', 5)
                ->where('is_del', 1)
                ->where('company_id', $user_info->adm_cid)
                ->where('cg_shop_id', $shop_id)
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_state'])) {  //采购状态
                        $query->where('cg_state', $where_data['cg_state']);
                    } else {
                        $query->where('cg_state', '!=', 18);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_number'])) {  //采购单号
                        $query->where('cg_number', 'like', '%' . $where_data['cg_number'] . '%');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['contract_number'])) { //合同号
                        $query->where('contract_number', 'like', '%' . $where_data['contract_number'] . '%');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['goods_name'])) { //包含商品
                        $query->where('goods_name', 'like', '%' . $where_data['goods_name'] . '%');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['chun_unit_name'])) { //采购单位
                        $query->where('chun_unit_name', 'like', '%' . $where_data['chun_unit_name'] . '%');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['puor_supplyunit_type'])) {
                        if ($where_data['puor_supplyunit_type'] == 2) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
                            if (!empty($where_data['shop_id'])) { //采购单位
                                $query->where('shop_id', $where_data['shop_id']);
                            }
                        } else {
                            if (!empty($where_data['chun_unit_name'])) { //采购单位
                                $query->where('chun_unit_name', 'like', '%' . $where_data['chun_unit_name'] . '%');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_wareid'])) { //仓库
                        $query->where('cg_wareid', $where_data['cg_wareid']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_settlementype'])) { //结算状态
                        $query->where('cg_settlementype', $where_data['cg_settlementype']);
                        // if ($where_data['cg_settlementype'] == '4') {
                        //     $cg_state = array(5, 8, 11, 12); //待审核生效状态
                        //     $query->whereIn('cg_state', $cg_state);
                        // }
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_userid'])) {  //创建人
                        $query->where('cg_userid', $where_data['cg_userid']);
                    }
                })
                ->where(function ($query) use ($where_data) {  //采购总额
                    if (!empty($where_data['amount_start'])) {
                        $query->where('cg_amount', '>=', $where_data['amount_start']);
                    }
                })
                ->where(function ($query) use ($where_data) { //采购总额
                    if (!empty($where_data['amount_end'])) {
                        $query->where('cg_amount', '<=', $where_data['amount_end']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_start'])) {
                        $query->where('create_time', '>=', $where_data['create_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_end'])) {
                        $query->where('create_time', '<=', $where_data['create_end'] . ' 23:59:59');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['dh_start'])) {  //到货开始时间
                        $query->where('dh_time', '>=', $where_data['dh_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['dh_end'])) {  //到货结束时间
                        $query->where('dh_time', '<=', $where_data['dh_end']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_supplyunit'])) {
                        $query->where('cg_supplyunit', $where_data['cg_supplyunit']);
                    }
                }) //供货单位
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_paymentype'])) {
                        $query->where('cg_paymentype', $where_data['cg_paymentype']);
                    }
                }) //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天8免费
                ->select('cg_id', 'cg_number', 'cg_yfmoney', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_paytype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'chun_unit_name', 'cg_creator', 'cg_delivertype', 'cg_invoicetype', 'cg_settlementype', 'business_type', 'auditor_user', 'contact_name', 'contact_phone', 'cg_original_number', 'cg_types', 'create_time', 'puor_supplyunit_type', 'puor_reject_reason')
                ->orderBy('create_time', 'desc')
                ->paginate($page_size);
        }

        $data = $list->items();

        // 分页
        $page_arr = [
            'page_count' => $list->lastPage(),  //总页数
            'page' => $list->currentPage(),     //当前页
            'page_size' => $page_size,          //每页条数
            'data_count' => $list->total(),     //总条数
        ];
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($data) {
            $data = json_decode(json_encode($data), true); //将对象转换为数组
            $warehoust = Db::table('warehouse')->pluck('ware_name', 'ware_id');
            $shop_parent_id = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->value('shop_parent_id');
            $parent_shop = DB::table('shop')
                ->where('shop_id', $shop_parent_id)
                ->select('shop_store_name', 'shop_name', 'shop_phone')
                ->first();
            foreach ($data as $key => $val) {
                if ($val['puor_supplyunit_type'] == 2) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
                    $data[$key]['chun_unit_name'] = $parent_shop->shop_store_name;
                }
                // 赋值仓库名称
                $data[$key]['ware_name'] = $warehoust[$val['cg_wareid']];
                // 获取审核人名称
                if ($val['auditor_user'] == 0) {
                    $data[$key]['auditor_user'] = '';
                } else {
                    if ($val['puor_supplyunit_type'] == 3) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
                        $data[$key]['auditor_user'] = Db::connection('mysql_scm')->table('admin')
                            ->where('adm_id', $val['auditor_user'])
                            ->value('adm_name');
                    } else {
                        $data[$key]['auditor_user'] = Db::table('admin')
                            ->where('adm_id', $val['auditor_user'])
                            ->value('adm_name');
                    }
                }
                $data[$key]['is_financial'] = 1;
                if ($this->isFinancialAudit($user_info, $shop_id)) {
                    $data[$key]['is_financial'] = 2;
                }
                // 获取采购商品
                $goods = DB::table('storage_goods')
                    ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                    ->where('relation_number', $val['cg_number'])
                    ->select('goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'goo_brse_id', 'goo_class', 'goo_unit', 'goo_unta_id', 'goo_unit_conversion')
                    ->orderBy('ruku_num', 'asc')
                    ->get();
                $goods = json_decode(json_encode($goods), true);
                // 查询系列数据
                $goo_brse_id = array_column($goods, 'goo_brse_id');
                $brse_data = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->pluck('brse_name', 'brse_id')
                    ->toArray();
                // 统计采购总数和去除商品名称前的品牌名称（不然商品名称太长了）；
                $goods_num = 0;
                foreach ($goods as $k => $v) {
                    $goods_num = $goods_num + $v['goods_num'];
                    // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                        if (!empty($v['goo_brse_id'])) {
                            if ($v['goo_class'] == 2) {
                                $goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                unset($v['goo_brse_id']);
                            } else {
                                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                    $goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                    unset($v['goo_brse_id']);
                                }
                            }
                        }
                    }
                    // 显示品牌名称
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                        if ($v['goo_class'] == 2) {
                            $goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $goods[$k]['goo_name'];
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $goods[$k]['goo_name'];
                            }
                        }
                    }
                }
                // 获取备注
                $note = DB::table('note')
                    ->where('note_number', $val['cg_number'])
                    ->select('note_id', 'note_content', 'note_time')
                    ->orderBy('note_id', 'desc')
                    ->get();
                if (substr($val['cg_number'], 0, 2) == 'TH') {
                    $data[$key]['goods_count']  = '-' . $goods_num;
                } else {
                    $data[$key]['goods_count']  = $goods_num;
                }

                $data[$key]['storage_goods'] = $goods;
                $data[$key]['note'] = $note;
                //按钮
                $buttonData = [];
                if($val['cg_state'] == 3){
                    $buttonData[] = 'edit';//采购编辑
                    $buttonData[] = 'SubmitReview';//提交审核
                    $buttonData[] = 'delete';//删除采购
                }
                if($val['cg_state'] == 1 && $val['puor_supplyunit_type'] == 1){
                    $buttonData[] = 'audit';//采购审核
                }
                if(in_array($val['cg_state'],[5,8,11,12]) && $val['cg_settlementype'] == 4 && $data[$key]['is_financial'] == 2){
                    $buttonData[] = 'financialAudit';//财务审核
                }
                if($val['cg_state'] == 11){
                    $buttonData[] = 'confirmCompleted';//确认完成
                }
                if($val['cg_state'] == 5 || $val['cg_state'] == 8){
                    $buttonData[] = 'suspend';//终止采购
                }
                if(in_array($val['cg_state'],[8,11,12]) && $val['cg_types'] != 2 && $val['puor_supplyunit_type'] == 1){
                    $buttonData[] = 'returnGoods';//申请退货
                }
                if(in_array($val['cg_state'],[8,11,12,17]) && $val['cg_types'] != 2){
                    $buttonData[] = 'look';//入库记录
                }
                if($val['cg_original_number'] == '' && ($val['cg_settlementype'] == 2 || $val['cg_settlementype'] == 5)){
                    $buttonData[] = 'purchasement';//采购结算
                }
                if($val['cg_original_number'] == '' && $val['cg_settlementype'] == 3 && $val['cg_paytype'] == 1){
                    //$buttonData[] = '';//结算记录
                }
                if($val['cg_state'] == 6 && $val['cg_original_number'] != ''){
                    $buttonData[] = 'cancelrefund';//撤销退货
                }
                $buttonData[] = 'info';//查看详情
                $button = CommonService::getListButton($buttonData,$list_button);
                $data[$key]['button_one'] = $button['button_one']??[];
                $data[$key]['button_two'] = $button['button_two']??[];
                $data[$key]['button_three'] = $button['button_three']??[];
            }
        }
        // 统计各种采购状态下的数量
        $state_count = Db::table('purchase_order')
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where('need_toexamine', '<', 5)
            ->where('is_del', 1)
            ->where('company_id', $user_info->adm_cid)
            ->select(DB::raw('cg_state,count(*) as num'))
            ->groupBy('cg_state')
            ->get()->toArray();
        $state_arr = [1, 2, 3, 5, 6, 8, 11, 12, 14, 17, 18, 19];
        $key_array = array_column($state_count, 'cg_state');
        foreach ($state_arr as $key => $val) {
            if (!in_array($val, $key_array)) {
                $state_count[] = ['cg_state' => $val, 'num' => 0];
            }
        }

        $res_data = ['page'=>$page_arr, 'data'=>$data, 'state_count'=>$state_count, 'list_button'=>$list_button];
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$res_data]);
    }

    // 添加采购单
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->addShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 添加采购单前
        if ($request['type'] == 1) {
            $getdata_res = PurchaseOrder::getPurchaseData($user_info, $shop_id, $request);
            if($getdata_res['code'] == 200){
                $data['data'] = $getdata_res['data'];
            }else{
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
            }
            // 获取当前列表下的按钮
            $list_button = getListButton($request['api_token'], $request['pri_id']);
            $but = [];
            if(!empty($list_button)){
                foreach ($list_button as $k => $v){
                    if(in_array($v['pri_id'],[719,720])){
                        $but[] = $v;
                    }
                }
            }
            $data['list_button'] = $but;
            //获取结算信息
            $data['data']['payment_way'] =  ChannelUnit::getPaymentWayName(2,false);
            $data['data']['deliver_type'] =  ChannelUnit::getDeliverTypeName(false);
            $data['data']['invoice_type'] =  ChannelUnit::getInvoiceTypeName(false);
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
            //return response()->json($getdata_res);
        }

        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }


        $allData = $request->all();
        if(isset($allData['addType']) && $allData['addType']==2) {
//            if(!isset($allData['goods']) || empty($allData['goods']) || !is_array($allData['goods']) ){
//                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>'商品必填']);
//            }
        }else{
//            $allData['goods'] = json_decode($allData['goods'],true);
            if(!isset($allData['goods']) || empty($allData['goods']) || !is_array($allData['goods']) ){
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>'商品必填']);
            }
        }
        // 去除数据中所包含的换行符等特殊符号
        $allData = RemoveLineFeed($allData);

        // 验证采购单号是否重复
        $cg_id = DB::table('purchase_order')
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where('cg_number', $allData['cg_number'])
            ->value('cg_id');
        if ($cg_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'采购单号重复']);
        }

        DB::beginTransaction();
        // DB::connection('mysql_scm')->beginTransaction();
        if(isset($allData['addType']) && $allData['addType']==2) {
            $file = $request->file('file');
        }else{
            $file = '';
        }
        $add_res = PurchaseOrder::add($user_info, $shop_id, $allData, $file);
        if ($add_res['code'] == 200) {
            DB::commit();
            // DB::connection('mysql_scm')->commit();
            Common::addLog($user_info, getRealIp($request), '采购管理', '添加采购单', $allData['cg_number'] . '成功');
            if ($allData['cg_remark'] != '') {
                Common::addNote($user_info, $shop_id, $allData['cg_number'], $allData['cg_remark'], '添加采购单');
            }
        } else {
            DB::rollBack();
            // DB::connection('mysql_scm')->rollBack();
        }
        return response()->json($add_res);
    }

    // 查询供货方信息
    public function searchShopinfo(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->searchShopinfoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if ($request['puor_supplyunit_type'] == 2) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
            $shop_parent_id = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->value('shop_parent_id');
            $data = DB::table('shop')
                ->where('shop_id', $shop_parent_id)
                ->select('shop_id as chun_id', 'shop_store_name as chun_unit_name', 'shop_name as chun_name', 'shop_phone as chun_phone', 'shop_address as chun_address', 'shop_city as chun_city', 'shop_county as chun_county', 'shop_province as chun_province')
                ->first();
        } elseif ($request['puor_supplyunit_type'] == 3) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
            $data = DB::table('channel_unit')
                ->where('chun_shop_id', $user_info->adm_shop_id)
                ->where('chun_class', 2)
                ->where('chun_state', 1)
                ->select('chun_id', 'chun_unit_name', 'chun_name', 'chun_phone', 'chun_class', 'chun_address', 'chun_city', 'chun_county', 'chun_province')
                ->first();
            if (empty($data)) {
                $add_data['chun_cid'] = 1;
                $add_data['chun_superior_shop_id'] = $user_info->adm_shop_id;
                $add_data['chun_shop_id'] = $user_info->adm_shop_id;
                $add_data['chun_adm_id'] = 0;
                $add_data['chun_search_letter'] = 'SDKB';
                $add_data['chun_unit_name'] = '速电快保';
                $add_data['chun_name'] = '张国锋';
                $add_data['chun_phone'] = '18810207681';
                $add_data['chun_state'] = 1;
                $add_data['chun_payment_way'] = 1;
                $add_data['chun_province'] = '北京市';
                $add_data['chun_city'] = '市辖区';
                $add_data['chun_county'] = '大兴区';
                $add_data['chun_address'] = '亦庄经济技术开发区大族广场T3栋1205-09室';
                $add_data['chun_class'] = 2;
                DB::beginTransaction();
                $add_data_res = DB::table('channel_unit')->insertGetId($add_data);
                if (!$add_data_res) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'查无数据']);
                } else {
                    DB::commit();
                }
                $data = DB::table('channel_unit')
                    ->where('chun_shop_id', $user_info->adm_shop_id)
                    ->where('chun_class', 2)
                    ->where('chun_state', 1)
                    ->select('chun_id', 'chun_unit_name', 'chun_name', 'chun_phone', 'chun_class', 'chun_address', 'chun_city', 'chun_county', 'chun_province')
                    ->first();
            }
        }
        if (!empty($data)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'查无数据']);
        }
    }

    // 编辑采购单
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $cg_number = $request->input('cg_number');

        // 获取采购单数据
        $puor_data = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->select('cg_id', 'cg_number', 'cg_yfmoney', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone', 'puor_supplyunit_type')
            ->first();
        $puor_data = json_decode(json_encode($puor_data), true);

        // 编辑前
        if ($request['type'] == 1) {
            $getEditdata = PurchaseOrder::getEditdata($user_info, $puor_data, $cg_number);
            if($getEditdata['code'] == 200){
                $data['data'] = $getEditdata['data'];
            }else{
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
            }
            // 获取当前列表下的按钮
            $list_button = getListButton($request['api_token'], $request['pri_id']);
            $but = [];
            if(!empty($list_button)){
                foreach ($list_button as $k => $v){
                    if(in_array($v['pri_id'],[719,720])){
                        $but[] = $v;
                    }
                }
            }
            $data['list_button'] = $but;
            //获取结算信息
            $data['data']['payment_way'] =  ChannelUnit::getPaymentWayName(2,false);
            $data['data']['deliver_type'] =  ChannelUnit::getDeliverTypeName(false);
            $data['data']['invoice_type'] =  ChannelUnit::getInvoiceTypeName(false);
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
            //return response()->json($getEditdata);
        }

        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $allData = $request->all();
        // 去除数据中所包含的换行符等特殊符号
        $allData = RemoveLineFeed($allData);
        // 验证合同单号是否重复
        $newcg_id = DB::table('purchase_order')
            ->where('cg_id', '!=', $puor_data['cg_id'])
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where('contract_number', $allData['contract_number'])
            ->value('cg_id');
        if ($newcg_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'合同单号重复']);
        }

        DB::beginTransaction();
        $edit_res = PurchaseOrder::edit($user_info, $puor_data, $allData);

        if ($edit_res['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购管理', '编辑采购单', $puor_data['cg_number'] . '成功');
            if ($allData['cg_remark'] != '') {
                Common::addNote($user_info, $shop_id, $allData['cg_number'], $allData['cg_remark'], '编辑采购单');
            }
        } else {
            DB::rollBack();
        }
        return response()->json($edit_res);
    }

    // 提交审核
    public function submitAudit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->submitAuditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $cg_number = (string) $request->input('cg_number');

        // 获取采购单的数据
        $cg_data = Db::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->where('is_del', 1)
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->select('cg_state', 'cg_number', 'cg_id', 'puor_supplyunit_type', 'cg_amount', 'cg_shop_id', 'cg_remark')
            ->first();
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'未找到该采购单']);
        }

        if ($cg_data->cg_state != 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'采购单状态错误,请刷新页面']);
        }

        DB::beginTransaction();
        // DB::connection('mysql_scm')->beginTransaction();
        $submit_audit_res = PurchaseOrder::submitAudit($user_info, $cg_data, $shop_id);
        if ($submit_audit_res['code'] == 200) {
                // 查询自动流程
                $autoNext_data['cg_number'] = $cg_data->cg_number;
                $autoNext_data['now_state'] = 1;
                $autoNext_res = PurchaseOrder::autoNext($user_info,$autoNext_data,$shop_id);
                if ($autoNext_res['code'] != 200) {
                    DB::rollBack();
                    return $autoNext_res;
                }
            DB::commit();
            // DB::connection('mysql_scm')->commit();
            Common::addLog($user_info, getRealIp($request), '采购管理', '提交审核', '提交审核' . $cg_data->cg_number . '成功');
        } else {
            DB::rollBack();
            // DB::connection('mysql_scm')->rollBack();
        }
        return response()->json($submit_audit_res);
    }

    // 审核通过、驳回
    public function audit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->financialAuditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $cg_number = $request->input('cg_number');

        // 基本与编辑一致；
        $cg_data = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->select('cg_id', 'cg_number', 'cg_yfmoney', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone', 'create_time')
            ->first();
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'获取采购单数据失败']);
        }
        $cg_data = json_decode(json_encode($cg_data), true);

        if ($cg_data['cg_state'] != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'状态已发生改变,该单无法审核']);
        }

        // 查询商品信息
        $storage_goods = DB::table('storage_goods')
            ->leftjoin('goods', 'goo_id', '=', 'goods_id')
            ->where('relation_number', $cg_number)
            ->select('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'goo_brse_id', 'goo_class')
            ->get();
        $storage_goods = json_decode(json_encode($storage_goods), true); //将对象转换为数组
        // 查询系列数据
        $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        foreach ($storage_goods as $k => $v) {
            $storage_goods[$k]['num'] = '';
            $storage_goods[$k]['estimate_time'] = date('Y-m-d');
            // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                if (!empty($v['goo_brse_id'])) {
                    if ($v['goo_class'] == 2) {
                        $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($v['goo_class'] == 2) {
                    $storage_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $storage_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goo_name'];
                    }
                }
            }
            unset($storage_goods[$k]['goo_brse_id']);
        }

        // 审核前
        if ($request['type'] == '1') {
            // 查询供货商名称
            $cg_data['supplyunit_name'] = (string) Db::table('channel_unit')
                ->where('chun_id', $cg_data['cg_supplyunit'])
                ->value('chun_unit_name');
            // 查询仓库名称
            $cg_data['ware_name'] = DB::table('warehouse')
                ->where('ware_id', $cg_data['cg_wareid'])
                ->value('ware_name');

            unset($cg_data['cg_state']);
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>['cg_data'=>$cg_data, 'storage_goods'=>$storage_goods]]);
        }

        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->financialAuditsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 审核
        $remarks = $request->input('remarks');

        if ($request['examine_type'] == 1) { //审核通过
            // 不需要财审
            $edit_data['cg_state'] = 5;
            $edit_data['edit_time'] = date('Y-m-d H:i:s');
            $edit_data['auditor_user'] = $user_info->adm_id;
            $edit_data['cg_remark'] = $remarks;
            $res1 = DB::table('purchase_order')
                ->where('cg_number', $cg_number)
                ->update($edit_data);
            // 查询自动流程
            $autoNext_data['cg_number'] = $cg_number;
            $autoNext_data['now_state'] = 2;
            $autoNext_res = PurchaseOrder::autoNext($user_info,$autoNext_data,$shop_id);
            if ($autoNext_res['code'] != 200) {
                return $autoNext_res;
            }
            if ($res1) {
                Common::addLog($user_info, getRealIp($request), '采购管理', '审核采购单', '审核通过' . $cg_data['cg_number'] . '成功');
                if ($remarks != '') {
                    Common::addNote($user_info, $shop_id, $cg_number, $remarks, '采购单审核通过');
                }
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'审核通过成功']);
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核通过失败']);
            }
        } else { //审核驳回
            $edit_data['cg_state'] = 3;
            $edit_data['edit_time'] = date('Y-m-d H:i:s');
            $edit_data['auditor_user'] = $user_info->adm_id;
            $edit_data['cg_remark'] = $remarks;
            $res1 = DB::table('purchase_order')
                ->where('cg_number', $cg_number)
                ->update($edit_data);
            if ($res1) {
                Common::addLog($user_info, getRealIp($request), '采购管理', '审核采购单', '审核驳回' . $cg_data['cg_number'] . '成功');
                if ($remarks != '') {
                    Common::addNote($user_info, $shop_id, $cg_number, $remarks, '采购单审核驳回');
                }
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'驳回成功']);
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'驳回失败']);
            }
        }
    }

    /**
     * 是否需要财务审核   由于表字段的原因请重写该方法
     * @param  [type]  $user_info 用户信息
     * @return boolean           [description]
     */
    private function isFinancialAudit($user_info, $shop_id)
    {
        $shse_financial_audit = Db::table("shop_set")
            ->where("shse_shop_id", $user_info->adm_shop_id)
            ->where("shse_superior_shop_id", $shop_id)
            ->value('shse_financial_audit');
        if ($shse_financial_audit == 2) {
            return true;
        } else {
            return false;
        }
    }

    // 删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->submitAuditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $cg_data = Db::table('purchase_order')
            ->where('cg_number', $request['cg_number'])
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->select('cg_state', 'cg_number')
            ->first();
        $cg_data = json_decode(json_encode($cg_data), true); //将对象转换为数组

        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'未找到该采购单']);
        }
        if (!in_array($cg_data['cg_state'], [1, 3])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'采购单状态错误,只有未审核的采购单才可以删除,请刷新页面']);
        }

        $res = Db::table('purchase_order')
            ->where('cg_number', $request['cg_number'])
            ->whereIn('cg_state', [1, 3])
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->update(['is_del' => 2, 'edit_time' => date('Y-m-d H:i:s')]);
        if ($res) {
            Common::addLog($user_info, getRealIp($request), '采购管理', '删除', '删除采购单' . $request['cg_number'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'删除成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'删除失败']);
        }
    }

    // 终止
    public function suspend(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->suspendValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $cg_number = $request->input('cg_number');
        $remarks   = $request->input('remarks');

        $cg_data = Db::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->first();
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'未找到该采购单']);
        }

        if ($cg_data->cg_state > 8) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'只有未完成的采购单才可以终止']);
        }

        $termin_type = $request->input('termin_type', 1);

        $goods_id = $request->input("goods_id", []);
        if ($termin_type == 2 && empty($goods_id)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择要终止的商品']);
        }

        DB::beginTransaction();

        $this->suspensionCopeWith($cg_data, $user_info, $termin_type, $goods_id);

        if ($termin_type == '1') { //终止类型：1全部终止2商品终止
            $edit_data['cg_state'] = 17;
            $edit_data['cg_remark'] = $remarks;
            $edit_data['edit_time'] = date('Y-m-d H:i:s');

            $res = Db::table('purchase_order')
                ->where('cg_number', $cg_number)
                ->where('company_id', $user_info->adm_cid)
                ->where('cg_superior_shop_id', $shop_id)
                ->update($edit_data);
            $stgo_data['stgo_stop'] = 2;
            $stgo_data['create_time'] = date('Y-m-d H:i:s');
            $stgo_res = DB::table('storage_goods')
                ->where('relation_number', $cg_number)
                ->where('stgo_stop', 1)
                ->update($stgo_data);
        } else { //终止类型：1全部终止2商品终止
            $edit_data['stgo_stop'] = 2;
            $edit_data['create_time'] = date('Y-m-d H:i:s');
            $res = DB::table('storage_goods')
                ->where('relation_number', $cg_number)
                ->whereIn('goods_id', $goods_id)
                ->update($edit_data);

            $cg_goods = DB::table('storage_goods')
                ->where("relation_number", $cg_number)
                ->where("stgo_stop", 1)
                ->whereRaw("ruku_num < goods_num")
                ->select('id')
                ->first();
            if (empty($cg_goods)) {
                Db::table('purchase_order')
                    ->where('cg_number', $cg_number)
                    ->where('is_del', 1)
                    ->where('cg_state', '<=', 8)
                    ->where('company_id', $user_info->adm_cid)
                    ->update(['cg_state' => 12, 'edit_time' => date("Y-m-d H:i:s")]);
            }
        }

        if ($res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购管理', '终止', '终止' . $cg_data->cg_number . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'终止成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'终止失败']);
        }
    }

    /**
     * 终止订单生成应付
     * @param  [type] $cg_data 采购数组
     * @return [type]          [description]
     */
    private function suspensionCopeWith($cg_data, $user_info, $termin_type, $goods_id)
    {
        $storage_goods = DB::table('storage_goods')
            ->where("relation_number", $cg_data->cg_number)
            ->where('stgo_stop', 1)
            ->where(function ($query) use ($goods_id, $termin_type) {
                if ($termin_type == 2) {
                    $query->whereIn('goods_id', $goods_id);
                }
            })
            ->select("goods_id", "goods_number", 'storehouse', "goods_name", "cg_goodsnum", "goods_num", "univalence", "ruku_num", "company_id", "tax_rate", "currency", "money", "estimate_time", "company_unit", 'old_univalence')
            ->get();
        $storage_goods = json_decode(json_encode($storage_goods), true);

        $cope_goods = []; //应付商品数组
        $goods_name = "";
        $cg_amount = 0;
        foreach ($storage_goods as $key => $val) {
            $goods_name = $goods_name . $val['goods_name'] . $val['goods_number'];
            // 只添加未全部入库的商品做应付
            if ($val['goods_num'] - $val['ruku_num'] <= 0) {
                continue;
            }
            $cg_amount = $val['old_univalence'] * abs($val['goods_num'] - $val['ruku_num']) + $cg_amount;
        }

        $chun_unit_name = DB::table('channel_unit')
            ->where('chun_id', $cg_data->cg_supplyunit)
            ->value('chun_unit_name');


        // 查询供应商名称
        $unit_name = DB::table('channel_unit')
            ->where('chun_id', $cg_data->cg_supplyunit)
            ->value('chun_unit_name');
        // 根据采购单号,查询商品
        $find_wogo_data = DB::table('storage_goods')
            ->where('relation_number', $cg_data->cg_number)
            ->where('stgo_stop', 1)
            ->select('storehouse', 'goods_type', 'goods_id', 'goods_num', 'univalence', 'old_univalence')
            ->get()->toArray();
        foreach ($find_wogo_data as $kkkk => $vvvv) {
            // 获取当前月份商品成本价
            $newprice = DB::table('enters_sells_saves')
                ->where('ense_goo_id', $vvvv->goods_id)
                ->where('ense_goo_warehouse', $vvvv->storehouse)
                ->where('ense_goo_waretype', $vvvv->goods_type)
                ->orderBy('ense_id', 'desc')
                ->select('ense_end_price')
                ->first();
            if ($newprice) {
                $cost_price = $newprice->ense_end_price;
            } else {
                $cost_price = 0;
            }
        }
        if ($cg_data->cg_settlementype == '3') { //结算状态2待结算3已结算4待审核5部分结算
            /* // 抵消预付款
            $recr_ress = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                ->where('recr_account_type', '20')
                ->where('recr_original_number', $cg_data->cg_number)
                ->select('recr_settle_price', 'recr_yet_receipt','recr_id')
                ->get();
            $yet_receipt=$cg_amount*100;
            foreach ($recr_ress as $k=>$v) {
                if ($yet_receipt > 0) {
                    if ($yet_receipt + $v->recr_yet_receipt > $v->recr_settle_price) {
                        $receivable_creditsave['recr_yet_receipt'] = $v->recr_settle_price;
                        $yet_receipt = $v->recr_settle_price-$v->recr_yet_receipt;
                    } else {
                        $receivable_creditsave['recr_yet_receipt'] = $v->recr_yet_receipt + $yet_receipt;
                        $yet_receipt = 0;
                    }
                    DB::table('receivable_credit')
                        ->where('recr_cid', $user_info->adm_cid)
                        ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                        ->where('recr_id', $v->recr_id)
                        ->update($receivable_creditsave);
                }
            } */
            // 应付
            $createBill = ReceivableBill::create(
                $user_info, //用户信息
                16, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $cg_data->cg_id, //原始id(订单id)
                $cg_data->cg_number, //应收账款单号/原始号(订单编号)
                2, //客户类型：1.门店零售 2.来往单位
                $cg_data->cg_supplyunit, //会员id/来往单位id
                $chun_unit_name, //来往单位名称
                $cg_amount * 100, //结算金额
                date('Y-m-d H:i:s'), //结款时间
                '', //会计科目id
                $cg_amount * 100, //实际金额
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                $cg_amount * 100, //已收金额
                '', //截止时间
                1, //金额正负1正   2负值
                19, //显示类型：18采购单
                2, //是否合并代收：1是2否
                $cg_data->create_time,
                0
            );
            // 添加结款明细记录
            $content = ' ';
            $acset_res = AccountingSettlement::add(
                $user_info,                 // [用户信息]
                24,                          // 单据类型24采购款到发货(预付款)
                $cg_data->cg_id,          // [与单据类型对应的id]
                $cg_data->cg_number, // [与单据类型对应的单号]
                2,                     // [买家类型1门店零售2来往单位]
                $cg_data->cg_supplyunit,       // [会员/客户id]
                $chun_unit_name,     // [来往单位名称]
                '22',         // [会计科目id]
                1,                                // [类型1收入2支出]
                $cg_amount * 100,                 // [实际金额](此次的实收金额)
                $cg_amount * 100,                 // [合计金额](此次的应收金额)
                0,                                // [欠收金额](此次结款后还应收金额)
                0,                                // [抹零金额]
                $content                                // [备注]
            );
            // 添加结款明细业务凭证
            $volo_data[0]['acsl_acset_id'] = $acset_res; //结款明细凭证id
            $volo_data[0]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
            $volo_data[0]['acsl_type'] = 1; //类型1借方2贷方
            $volo_data[0]['acsl_borrow_subject'] = '220201'; //借方科目
            $volo_data[0]['acsl_borrow_subject_name'] = '应付账款'; //借方科目名称
            $volo_data[0]['acsl_borrow_price'] = $cg_amount; //借方金额
            $volo_data[0]['acsl_loan_subject'] = '1001'; //贷方科目
            $volo_data[0]['acsl_loan_subject_name'] = '库存现金'; //贷方科目名称
            $volo_data[0]['acsl_loan_price'] = $cg_amount; //贷方金额
            $volo_data[1]['acsl_acset_id'] = $acset_res; //结款明细凭证id
            $volo_data[1]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
            $volo_data[1]['acsl_type'] = 1; //类型1借方2贷方
            $volo_data[1]['acsl_borrow_subject'] = ''; //借方科目
            $volo_data[1]['acsl_borrow_subject_name'] = ''; //借方科目名称
            $volo_data[1]['acsl_borrow_price'] = 0; //借方金额
            $volo_data[1]['acsl_loan_subject'] = ''; //贷方科目
            $volo_data[1]['acsl_loan_subject_name'] = ''; //贷方科目名称
            $volo_data[1]['acsl_loan_price'] = 0; //贷方金额
            $volo_id = DB::table('accounting_settlement_loan')->insert($volo_data);
        } elseif ($cg_data->cg_settlementype == '2' || $cg_data->cg_settlementype == '4') { //结算状态2待结算3已结算4待审核5部分结算
            $pudata['cg_settlementype'] = '5';
            if ($cg_amount == $cg_data->cg_amount) {
                $pudata['cg_settlementype'] = '3';
            }
            $pudata['cg_zdnumber'] = $cg_amount;

            $ord_res = DB::table('purchase_order')
                ->where('cg_id', $cg_data->cg_id)
                ->update($pudata);
        } elseif ($cg_data->cg_settlementype == '5') { //结算状态2待结算3已结算4待审核5部分结算
            if ($cg_amount + $cg_data->cg_yfmoney < $cg_data->cg_amount) {
                 // 采购单的终止，加上之前终止的金额
                 if (!empty($cg_data->cg_zdnumber)) {
                    $cg_amount = $cg_amount + $cg_data->cg_zdnumber;
                }
                $pudata['cg_zdnumber'] = $cg_amount;
                $ord_res = DB::table('purchase_order')
                    ->where('cg_id', $cg_data->cg_id)
                    ->update($pudata);
            } elseif ($cg_amount + $cg_data->cg_yfmoney == $cg_data->cg_amount) {
                $pudata['cg_zdnumber'] = $cg_amount;
                $pudata['cg_settlementype'] = '3';
                $ord_res = DB::table('purchase_order')
                    ->where('cg_id', $cg_data->cg_id)
                    ->update($pudata);
            } else {
                $moling = $cg_data->cg_amount - $cg_data->cg_yfmoney;
                $pudata['cg_zdnumber'] = $cg_amount;
                $pudata['cg_settlementype'] = '3';
                $ord_res = DB::table('purchase_order')
                    ->where('cg_id', $cg_data->cg_id)
                    ->update($pudata);
                $amount = $cg_amount - $moling;
                /* // 抵消预付款
                $recr_ress = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                    ->where('recr_account_type', '20')
                    ->where('recr_original_number', $cg_data->cg_number)
                    ->select('recr_settle_price', 'recr_yet_receipt','recr_id')
                    ->get();
                $yet_receipt = $amount * 100;
                foreach ($recr_ress as $k=>$v) {
                    if ($yet_receipt > 0) {
                        if ($yet_receipt + $v->recr_yet_receipt > $v->recr_settle_price) {
                            $receivable_creditsave['recr_yet_receipt'] = $v->recr_settle_price;
                            $yet_receipt = $v->recr_settle_price-$v->recr_yet_receipt;
                        } else {
                            $receivable_creditsave['recr_yet_receipt'] = $v->recr_yet_receipt + $yet_receipt;
                            $yet_receipt=0;
                        }
                        DB::table('receivable_credit')
                            ->where('recr_cid', $user_info->adm_cid)
                            ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                            ->where('recr_id', $v->recr_id)
                            ->update($receivable_creditsave);
                    }
                } */
                // 应付
                $createBill = ReceivableBill::create(
                    $user_info, //用户信息
                    16, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    0, //应收账款id
                    $cg_data->cg_id, //原始id(订单id)
                    $cg_data->cg_number, //应收账款单号/原始号(订单编号)
                    2, //客户类型：1.门店零售 2.来往单位
                    $cg_data->cg_supplyunit, //会员id/来往单位id
                    $chun_unit_name, //来往单位名称
                    $amount * 100, //结算金额
                    date('Y-m-d H:i:s'), //结款时间
                    '', //会计科目id
                    $amount * 100, //实际金额
                    0, //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    '',  //备注
                    $amount * 100, //已收金额
                    '', //截止时间
                    1, //金额正负1正   2负值
                    19, //显示类型：18采购单
                    2, //是否合并代收：1是2否
                    $cg_data->create_time,
                    0
                );
                // 添加结款明细记录
                $content = ' ';
                $acset_res = AccountingSettlement::add(
                    $user_info,                 // [用户信息]
                    24,                          // 单据类型24采购款到发货(预付款)
                    $cg_data->cg_id,          // [与单据类型对应的id]
                    $cg_data->cg_number, // [与单据类型对应的单号]
                    2,                     // [买家类型1门店零售2来往单位]
                    $cg_data->cg_supplyunit,       // [会员/客户id]
                    $chun_unit_name,     // [来往单位名称]
                    '22',         // [会计科目id]
                    1,                                // [类型1收入2支出]
                    $amount * 100,                 // [实际金额](此次的实收金额)
                    $amount * 100,                 // [合计金额](此次的应收金额)
                    0,                                // [欠收金额](此次结款后还应收金额)
                    0,                                // [抹零金额]
                    $content                                // [备注]
                );
                // 添加结款明细业务凭证
                $volo_data[0]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                $volo_data[0]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                $volo_data[0]['acsl_type'] = 1; //类型1借方2贷方
                $volo_data[0]['acsl_borrow_subject'] = '220201'; //借方科目
                $volo_data[0]['acsl_borrow_subject_name'] = '应付账款'; //借方科目名称
                $volo_data[0]['acsl_borrow_price'] = $amount; //借方金额
                $volo_data[0]['acsl_loan_subject'] = '1001'; //贷方科目
                $volo_data[0]['acsl_loan_subject_name'] = '库存现金'; //贷方科目名称
                $volo_data[0]['acsl_loan_price'] = $amount; //贷方金额
                $volo_data[1]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                $volo_data[1]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                $volo_data[1]['acsl_type'] = 1; //类型1借方2贷方
                $volo_data[1]['acsl_borrow_subject'] = ''; //借方科目
                $volo_data[1]['acsl_borrow_subject_name'] = ''; //借方科目名称
                $volo_data[1]['acsl_borrow_price'] = 0; //借方金额
                $volo_data[1]['acsl_loan_subject'] = ''; //贷方科目
                $volo_data[1]['acsl_loan_subject_name'] = ''; //贷方科目名称
                $volo_data[1]['acsl_loan_price'] = 0; //贷方金额
                $volo_id = DB::table('accounting_settlement_loan')->insert($volo_data);
            }
        }
        // 添加结款明细记录
        /* $acset_res = AccountingSettlement::add(
            $user_info,                 // [用户信息]
            22,                          // 单据类型1订单结算2订单账单3工单账单4采购账单5销售账单6预收款7采购入库单现金8预付款9订单代收
            $cg_data->cg_id,          // [与单据类型对应的id]
            $cg_data->cg_number, // [与单据类型对应的单号]
            2,                     // [买家类型1门店零售2来往单位]
            $cg_data->cg_supplyunit,       // [会员/客户id]
            $chun_unit_name,     // [来往单位名称]
            '',         // [会计科目id]
            2,                                // [类型1收入2支出]
            $cg_amount * 100,                 // [实际金额](此次的实收金额)
            $cg_amount * 100,                 // [合计金额](此次的应收金额)
            0,                                // [欠收金额](此次结款后还应收金额)
            0,                                // [抹零金额]
            ''                                // [备注]
        );*/
    }

    // 查看
    public function look(Request $request)
    {
        $cg_number = $request->input('cg_number');
        if (empty($cg_number)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'采购单号不能为空']);
        }

        // 获取当前账号操作信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询采购单数据
        $cg_data = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->where('is_del', 1)
            ->select('cg_id', 'cg_number', 'cg_yfmoney', 'cg_creator', 'contract_number', 'create_time', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone')
            ->first();
        $cg_data = json_decode(json_encode($cg_data), true);
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'获取采购单数据失败']);
        }

        // 查询供货商名称
        $cg_data['supplyunit_name'] = Db::table('channel_unit')
            ->where('chun_id', $cg_data['cg_supplyunit'])
            ->value('chun_unit_name');

        // 查询采购的商品
        $storage_goods = DB::table('storage_goods as stgo')
            ->leftjoin('goods', 'goo_id', '=', 'goods_id')
            ->where('relation_number', $cg_number)
            ->select('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type as goo_type', 'stgo_stop', 'goo_brse_id', 'goo_class')
            ->get()->toArray();
        $storage_goods = json_decode(json_encode($storage_goods), true);
        // 查询系列数据
        $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        $goods_num = 0;
        foreach ($storage_goods as $k => $v) {
            $goods_num = $v['goods_num'] + $goods_num;
            // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                if (!empty($v['goo_brse_id'])) {
                    if ($v['goo_class'] == 2) {
                        $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($v['goo_class'] == 2) {
                    $storage_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $storage_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goo_name'];
                    }
                }
            }
            unset($storage_goods[$k]['goo_class']);
            unset($storage_goods[$k]['goo_brse_id']);
        }
        $cg_data['goods_count'] = $goods_num;

        // 获取采购仓库名称
        $cg_data['ware_name'] = DB::table('warehouse')
            ->where('ware_id', $cg_data['cg_wareid'])
            ->value('ware_name');

        $cg_numberArr[] = $cg_data['cg_number'];

        // 获取入库单列表
        $ware_inorderData = Db::table('ware_inorder')
            ->where('cg_number', $cg_data['cg_number'])
            ->select('rk_number', 'rk_waretype', 'rk_inputid', 'arrival_time', 'rk_remarks', 'rk_image', 'rk_amount')
            ->get();
        $ware_inorderData = json_decode(json_encode($ware_inorderData), true);
        $rk_num = 0;  //采购总数
        $df_num = 0;  //代发总数
        $th_num = 0;  //退货总数
        $hh_num = 0;  //换货总数
        // 查询入库单的数据
        foreach ($ware_inorderData as $key => $val) {
            $cg_numberArr[] = $val['rk_number'];
            $ware_inorderData[$key]['inware_user'] = Db::table('admin')
                ->where('adm_id', $val['rk_inputid'])
                ->value('adm_name');

            // 获取入库单商品数据
            $ware_goods = DB::table('storage_goods')
                ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                ->where('relation_number', $val['rk_number'])
                ->where('ruku_num', '!=', 0)
                ->select('id as stgo_id', 'goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'edit_time as dh_time', 'company_unit', 'goods_type', 'stgo_stop', 'goo_brse_id', 'goo_class')
                ->get()->toArray();
            $ware_goods = json_decode(json_encode($ware_goods), true);
            $stgo_id = array_column($ware_goods, 'stgo_id');
            // 查询仓位商品出入库表
            $find_wfog_data = DB::table('warehouse_freight_outin_goods as wfog')
                ->leftjoin('warehouse_freight as wafr', 'wafr.wafr_id', '=', 'wfog.wfog_wafr_id')
                ->where('wfog_shop_id', $user_info->adm_shop_id)
                ->whereIn('wfog_primary_id', $stgo_id)
                ->select('wfog_id', 'wfog_wafr_id', 'wfog_primary_id', 'wafr_name')
                ->get()->toArray();
            $find_wfog_data = array_column($find_wfog_data, null, 'wfog_primary_id');
            // 查询系列数据
            $goo_brse_id = array_column($ware_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            $ware_num = 0;
            foreach ($ware_goods as $k => $v) {
                if ($val['rk_waretype'] == 3) {
                    $df_num = $df_num + $v['ruku_num'];
                } elseif ($val['rk_waretype'] == 1) {
                    $rk_num = $rk_num + $v['ruku_num'];
                } elseif ($val['rk_waretype'] == 2) {
                    $th_num = $th_num + $v['ruku_num'];
                    $ware_goods[$k]['dh_time'] = '';
                    $ware_goods[$k]['estimate_time'] = '';
                } elseif ($val['rk_waretype'] == 4) {
                    $hh_num = $hh_num + $v['ruku_num'];
                    $ware_goods[$k]['dh_time'] = '';
                    $ware_goods[$k]['estimate_time'] = '';
                }
                $ware_num = $ware_num + $v['ruku_num'];

                if ($v['dh_time'] != '0000-00-00 00:00:00') {
                    $ware_goods[$k]['dh_time'] = date("Y-m-d", strtotime($v['dh_time']));
                } else {
                    $ware_goods[$k]['dh_time'] = '0000-00-00';
                }
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($v['goo_brse_id'])) {
                        if ($v['goo_class'] == 2) {
                            $ware_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                            unset($ware_goods[$k]['goo_brse_id']);
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $ware_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                unset($ware_goods[$k]['goo_brse_id']);
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($v['goo_class'] == 2) {
                        $ware_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $ware_goods[$k]['goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $ware_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $ware_goods[$k]['goo_name'];
                        }
                    }
                }
                if (isset($find_wfog_data[$v['stgo_id']])) {
                    $ware_goods[$k]['wafr_name'] = $find_wfog_data[$v['stgo_id']]->wafr_name;
                } else {
                    $ware_goods[$k]['wafr_name'] = '';
                }
                unset($ware_goods[$k]['goo_class']);
            }
            $ware_inorderData[$key]['ware_num'] = $ware_num;
            $ware_inorderData[$key]['ware_goods'] = $ware_goods;
        }
        $cg_data['rk_num'] = $rk_num + $th_num + $hh_num;
        $cg_data['df_num'] = $df_num;
        $cg_data['th_num'] = $th_num;
        $cg_data['hh_num'] = $hh_num;

        // 获取操作备注
        $note = DB::table('note')
            ->whereIn('note_number', $cg_numberArr)
            ->select('note_number', 'note_content', 'note_time', 'note_type')
            ->orderBy('note_id', 'desc')
            ->get();

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>['cg_data'=>$cg_data, 'storage_goods'=>$storage_goods, 'ware_inorderData'=>$ware_inorderData, 'note'=>$note]]);
    }

    // 导出
    public function exportExcel(Request $request)
    {
        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $where_data = $request->all();
        $wareInArr = [];
        $rukuNumArr = [];
        if (!empty($where_data['dh_start']) || !empty($where_data['dh_end'])) { //到货时间
            $wareInorder = Db::table("ware_inorder")
                ->where('rk_type', 1)
                ->where('rk_state', 5)
                ->where('company_id', $user_info->adm_cid)
                ->where('rk_superior_shop_id', $shop_id);
            if (!empty($where_data['dh_start'])) {  //到货开始时间
                $wareInorder = $wareInorder->where('arrival_time', '>=', $where_data['dh_start']);
            }
            if (!empty($where_data['dh_end'])) {  //到货结束时间
                $wareInorder = $wareInorder->where('arrival_time', '<=', $where_data['dh_end'] . " 23:59:59");
            }
            $rukuNumArr = $wareInorder->select("rk_number")->get();
            $wareInArr = $wareInorder
                ->where('rk_waretype', 1)
                ->select('cg_number')
                ->groupBy('cg_number')
                ->get();
            $wareInArr = json_decode(json_encode($wareInArr), true);
            $rukuNumArr = json_decode(json_encode($rukuNumArr), true);
            $wareInArr = array_column($wareInArr, 'cg_number');
            $rukuNumArr = array_column($rukuNumArr, 'rk_number');
        }
        if (!empty($where_data['note_content'])) {
            // 2.删除历史搜索备注
            DB::table('order_goods_temporary')
                ->where('orgt_adm_id', $user_info->adm_id) //与类型所对应的id
                ->where('orgt_type', 3) //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单
                ->delete();
            $note_numberlist = Db::table('note')
                ->where('note_adm_cid', $user_info->adm_cid)
                ->where('note_shop_id', $shop_id)
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_userid'])) {
                        $query->where('note_adm_id', $where_data['cg_userid']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_start'])) {
                        $query->where('note_time', '>=', $where_data['create_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_end'])) {
                        $query->where('note_time', '<=', $where_data['create_end'] . ' 23:59:59');
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['note_content'])) {
                        $query->where('note_content', 'like', "%" . $where_data['note_content'] . "%");
                    }
                })
                ->groupBy('note_number')
                ->select('note_number')
                ->get();
            foreach ($note_numberlist as $k => $v) {
                $temp['orgt_order_number'] = $v->note_number;
                $temp['orgt_type'] = '3';
                $temp['orgt_update_time'] = date("Y-m-d H:i:s");
                $temp['orgt_adm_id'] = $user_info->adm_id;
                $res = DB::table('order_goods_temporary')->insert($temp);
            }
            // 基本与查询一致
            DB::connection()->enableQueryLog();#开启执行日志
            $data = Db::table('purchase_order as puor')
                ->leftjoin('order_goods_temporary as orgt', 'orgt.orgt_order_number', '=', 'puor.cg_number')
                ->leftjoin('storage_goods as stgo', 'stgo.relation_number', 'puor.cg_number')
                ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'puor.cg_supplyunit')
                ->leftjoin('warehouse as ware', 'ware.ware_id', '=', 'puor.cg_wareid')
                ->where('orgt_type', 3)
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('puor.need_toexamine', '<', 5)
                ->where('is_del', 1)
                ->where('puor.company_id', $user_info->adm_cid)
                ->where('puor.cg_superior_shop_id', $shop_id)
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_state'])) {  //采购状态
                        $query->where('cg_state', $where_data['cg_state']);
                    } else {
                        $query->where('cg_state', '!=', 18);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_number'])) {  //采购单号
                        $query->where('cg_number', 'like', "%" . $where_data['cg_number'] . "%");
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['contract_number'])) { //合同号
                        $query->where('contract_number', 'like', "%" . $where_data['contract_number'] . "%");
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['goods_name'])) { //包含商品
                        $query->where('goods_name', 'like', "%" . $where_data['goods_name'] . "%");
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_supplyunit'])) { //采购单位
                        $query->where('cg_supplyunit', $where_data['cg_supplyunit']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_wareid'])) { //仓库
                        $query->where('cg_wareid', $where_data['cg_wareid']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_settlementype'])) { //结算状态
                        $query->where('cg_settlementype', $where_data['cg_settlementype']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_userid'])) {  //创建人
                        $query->where('cg_userid', $where_data['cg_userid']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['amount_start'])) {
                        $query->where('cg_amount', '>=', $where_data['amount_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['amount_end'])) {
                        $query->where('cg_amount', '<=', $where_data['amount_end']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_start'])) {
                        $query->where('puor.create_time', '>=', $where_data['create_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_end'])) {
                        $query->where('puor.create_time', '<=', $where_data['create_end'] . ' 23:59:59');
                    }
                })
                ->where(function ($query) use ($where_data, $wareInArr) {
                    if (!empty($where_data['dh_start']) || !empty($where_data['dh_end'])) {  //判断是否有到货时间，如果有到货时间，则添加该判断
                        $query->whereIn('cg_number', $wareInArr);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_paymentype'])) {
                        $query->where('cg_paymentype', $where_data['cg_paymentype']);
                    }
                }) //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天8免费
                ->select('puor.*','puor.cg_number', 'contract_number', 'cg_state', 'puor.create_time', 'chun_unit_name','cg_paymentype', 'business_type','ware_name')
                ->orderBy('cg_id', 'desc')
                ->get()->toArray();
        } else {
            DB::connection()->enableQueryLog();#开启执行日志
            // 基本与查询一致
            $data = Db::table('purchase_order as puor')
                ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'puor.cg_supplyunit')
                ->leftjoin('warehouse as ware', 'ware.ware_id', '=', 'puor.cg_wareid')
                ->where('puor.need_toexamine', '<', 5)
                ->where('is_del', 1)
                ->where('puor.company_id', $user_info->adm_cid)
                ->where('puor.cg_superior_shop_id', $shop_id)
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_state'])) {  //采购状态
                        $query->where('cg_state', $where_data['cg_state']);
                    } else {
                        $query->where('cg_state', '!=', 18);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_number'])) {  //采购单号
                        $query->where('puor.cg_number', 'like', "%" . $where_data['cg_number'] . "%");
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['contract_number'])) { //合同号
                        $query->where('contract_number', 'like', "%" . $where_data['contract_number'] . "%");
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['goods_name'])) { //包含商品
                        $query->where('goods_name', 'like', "%" . $where_data['goods_name'] . "%");
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_supplyunit'])) { //采购单位
                        $query->where('cg_supplyunit', $where_data['cg_supplyunit']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_wareid'])) { //仓库
                        $query->where('cg_wareid', $where_data['cg_wareid']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_settlementype'])) { //结算状态
                        $query->where('cg_settlementype', $where_data['cg_settlementype']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_userid'])) {  //创建人
                        $query->where('cg_userid', $where_data['cg_userid']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['amount_start'])) {
                        $query->where('cg_amount', '>=', $where_data['amount_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['amount_end'])) {
                        $query->where('cg_amount', '<=', $where_data['amount_end']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_start'])) {
                        $query->where('puor.create_time', '>=', $where_data['create_start']);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['create_end'])) {
                        $query->where('puor.create_time', '<=', $where_data['create_end'] . ' 23:59:59');
                    }
                })
                ->where(function ($query) use ($where_data, $wareInArr) {
                    if (!empty($where_data['dh_start']) || !empty($where_data['dh_end'])) {  //判断是否有到货时间，如果有到货时间，则添加该判断
                        $query->whereIn('cg_number', $wareInArr);
                    }
                })
                ->where(function ($query) use ($where_data) {
                    if (!empty($where_data['cg_paymentype'])) {
                        $query->where('cg_paymentype', $where_data['cg_paymentype']);
                    }
                }) //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天8免费
                ->select('puor.*','puor.cg_number', 'contract_number', 'cg_state', 'puor.create_time', 'chun_unit_name', 'cg_paymentype', 'business_type', 'ware_name')
                ->orderBy('cg_id', 'desc')
                ->get()->toArray();
        }
        $data['sqls'] = DB::getQueryLog()[0];
        $sqls = $data['sqls'];
        $excel = new CommonController();
        $amp_id = $where_data['amp_id']??0;
        return $excel->getExcelOut($amp_id,$user_info,$where_data['pri_id'], $sqls, $where_data['api_token']);
        if (!empty($data)) {
            // 将对象转为数组
            $data = json_decode(json_encode($data), true);
            $goods_ids = array_column($data, 'goods_id');
            // 根据商品id查询商品数据
            $find_goo_data = DB::table('goods')
                ->whereIn('goo_id', $goods_ids)
                ->select('goo_bra_name', 'goo_brse_id', 'goo_class', 'goo_id')
                ->get()->toArray();
            $goo_data = array_column($find_goo_data, null, 'goo_id');
            $goo_brse_id = array_column($find_goo_data, 'goo_brse_id', 'goo_id');
            // 查询系列数据
            $find_brse_id = array_column($find_goo_data, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $find_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($data as $key => $value) {
                // 采购单状态1审核中3驳回编辑5未入库8部分入库11完成(9待结算10待审核)15申请终止17中止
                if ($value['cg_state'] == 1) {
                    $data[$key]['cg_state'] = '审核中';
                }
                if ($value['cg_state'] == 2) {
                    $data[$key]['cg_state'] = '财审中';
                }
                if ($value['cg_state'] == 3) {
                    $data[$key]['cg_state'] = '待处理';
                }
                if ($value['cg_state'] == 5) {
                    $data[$key]['cg_state'] = '未入库';
                }
                if ($value['cg_state'] == 6) {
                    $data[$key]['cg_state'] = '未出库';
                }
                if ($value['cg_state'] == 8) {
                    $data[$key]['cg_state'] = '部分入库';
                }
                if ($value['cg_state'] == 9) {
                    $data[$key]['cg_state'] = '待结算';
                }
                if ($value['cg_state'] == 10) {
                    $data[$key]['cg_state'] = '待审核';
                }
                if ($value['cg_state'] == 11) {
                    $data[$key]['cg_state'] = '完成';
                }
                if ($value['cg_state'] == 12) {
                    $data[$key]['cg_state'] = '确认完成';
                }
                if ($value['cg_state'] == 14) {
                    $data[$key]['cg_state'] = '已封账';
                }
                if ($value['cg_state'] == 17) {
                    $data[$key]['cg_state'] = '终止';
                }
                // 付款方式
                if ($value['cg_paymentype'] == 1) {
                    $data[$key]['cg_paymentype'] = '现金';
                }
                if ($value['cg_paymentype'] == 2) {
                    $data[$key]['cg_paymentype'] = '定期';
                }
                if ($value['cg_paymentype'] == 3) {
                    $data[$key]['cg_paymentype'] = '款到发货';
                }
                if ($value['cg_paymentype'] == 4) {
                    $data[$key]['cg_paymentype'] = '货到付款';
                }
                if ($value['cg_paymentype'] == 5) {
                    $data[$key]['cg_paymentype'] = '月结15天';
                }
                if ($value['cg_paymentype'] == 6) {
                    $data[$key]['cg_paymentype'] = '月结30天';
                }
                if ($value['cg_paymentype'] == 7) {
                    $data[$key]['cg_paymentype'] = '月结60天';
                }
                if ($value['cg_paymentype'] == 8) {
                    $data[$key]['cg_paymentype'] = '免费';
                }
                // 业务类型
                if ($value['business_type'] == 0) {
                    $data[$key]['business_type'] = '无';
                }
                if ($value['business_type'] == 1) {
                    $data[$key]['business_type'] = '普通采购';
                }
                if ($value['business_type'] == 2) {
                    $data[$key]['business_type'] = '样品采购';
                }
                if ($value['business_type'] == 3) {
                    $data[$key]['business_type'] = '厂家返利';
                }
                // 入库单状态
                if ($value['rk_state'] == 1) {
                    $data[$key]['rk_state'] = '待入库';
                }
                if ($value['rk_state'] == 3) {
                    $data[$key]['rk_state'] = '待审核';
                }
                if ($value['rk_state'] == 4) {
                    $data[$key]['rk_state'] = '驳回';
                }
                if ($value['rk_state'] == 5) {
                    $data[$key]['rk_state'] = '已完成';
                }
                if ($value['rk_state'] == 8) {
                    $data[$key]['rk_state'] = '作废';
                }
                // 入库类型
                if ($value['rk_type'] == 1) {
                    $data[$key]['rk_type'] = '普通采购';
                }
                if ($value['rk_type'] == 2) {
                    $data[$key]['rk_type'] = '采购退货';
                }
                if ($value['rk_type'] == 3) {
                    $data[$key]['rk_type'] = '采购换货';
                }
                if ($value['rk_type'] == 4) {
                    $data[$key]['rk_type'] = '代发采购';
                }
                // 检索编码
                $data[$key]['goods_number'] = "\t" . $value['goods_number'];
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($goo_brse_id[$value['goods_id']])) {
                        // 显示系列名称
                        if ($goo_data[$value['goods_id']]->goo_class == 2) {
                            $data[$key]['goods_name'] = $brse_data[$goo_brse_id[$value['goods_id']]] . ' ' . $value['goods_name'];
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $data[$key]['goods_name'] = $brse_data[$goo_brse_id[$value['goods_id']]] . ' ' . $value['goods_name'];
                                unset($goo_brse_id[$value['goods_id']]);
                            }
                        }
                        unset($goo_brse_id[$value['goods_id']]);
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($goo_data[$value['goods_id']]->goo_class == 2) {
                        $data[$key]['goods_name'] = $goo_data[$value['goods_id']]->goo_bra_name . ' ' . $data[$key]['goods_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $data[$key]['goods_name'] = $goo_data[$value['goods_id']]->goo_bra_name . ' ' . $data[$key]['goods_name'];
                        }
                    }
                }
                unset($data[$key]['goods_id']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无导出数据']);
        }

        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

        $streamFileRand = '采购单' . time() . rand(1000, 9999) . '.xls';
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;

        $where['action_name'] = '采购单';
        $where['field_name'] = ['采购单号', '合同单号', '采购状态', '创建时间', '供应商', '商品名称', '商品编码', '数量', '采购单价', '金额', '付款方式', '业务类型', '入库单号', '入库时间', '仓库名称', '入库状态', '入库类型', '入库数量'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($pathName)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

    // 财务审核
    public function financialAudit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->financialAuditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $cg_number = $request->input('cg_number');

        // 与审核返回数据一致；请粘贴复制或直接写公共方法
        $cg_data = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->where('cg_settlementype', '4')
            ->select('cg_id', 'cg_number', 'cg_yfmoney', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone', 'create_time', 'cg_userid')
            ->first();
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'获取采购单数据失败']);
        }

        // 获取商品数据
        $storage_goods = DB::table('storage_goods')
            ->leftjoin('goods', 'goo_id', '=', 'goods_id')
            ->where('relation_number', $cg_number)
            ->select('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'old_univalence', 'goods_type as goo_type', 'goo_brse_id', 'goo_class')
            ->get();
        $storage_goods = json_decode(json_encode($storage_goods), true); //将对象转换为数组
        // 查询系列数据
        $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        $cg_data->cg_nums = '0';
        foreach ($storage_goods as $k => $v) {
            $cg_data->cg_nums = $cg_data->cg_nums + $v['goods_num'];
            // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                if (!empty($v['goo_brse_id'])) {
                    if ($v['goo_class'] == 2) {
                        $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($v['goo_class'] == 2) {
                    $storage_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $storage_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goo_name'];
                    }
                }
            }
            unset($storage_goods[$k]['goo_brse_id']);
        }
        $goods_ids = array_column($storage_goods, null, 'goods_id');

        // 审核前
        if ($request['type'] == '1') {
            // 获取供应商名称
            $cg_data->supplyunit_name = (string)Db::table('channel_unit')
                ->where('chun_id', $cg_data->cg_supplyunit)
                ->value('chun_unit_name');
            // 获取仓库名称
            $cg_data->ware_name = DB::table('warehouse')
                ->where('ware_id', $cg_data->cg_wareid)
                ->value('ware_name');

            unset($cg_data->cg_state);

            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>['cg_data'=>$cg_data, 'storage_goods'=>$storage_goods]]);
        }

        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->financialAuditsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 审核
        $remarks = $request->input('remarks');

        if ($request['examine_type'] == 1) {
            // 审核通过
            // 判断是否更改价格  高献昌
            $goodsresultarray = DB::table('storage_goods')
                ->where('relation_number', $cg_number)
                ->select('goods_id', 'univalence', 'ruku_num')
                ->get();
            $goodsresultarray = json_decode(json_encode($goodsresultarray), true);
            foreach ($goodsresultarray as $k => $v) {
                $goodsarray[$v['goods_id']]['univalence'] = $v['univalence'];
                $goodsarray[$v['goods_id']]['ruku_num'] = $v['ruku_num'];
            }
            foreach ($request['goods'] as $k => $v) {
                if ($goodsarray[$v['goods_id']]['ruku_num'] != '0') {
                    if ($v['univalence'] != $goodsarray[$v['goods_id']]['univalence']) {
                        // 更新最终结余
                        $goodsprice = ($goodsarray[$v['goods_id']]['univalence'] - $v['univalence']) * $v['ruku_num']; //编辑前后相差商品金额
                        $enters_sells_savesres = DB::table('enters_sells_saves')
                            ->where('ense_goo_id', $v['goods_id'])
                            ->where('ense_goo_warehouse', $request['cg_wareid'])
                            ->where('ense_goo_waretype', '1')
                            ->orderBy('ense_id', 'desc')
                            ->select('ense_id', 'ense_end_amount', 'ense_end_inventory')
                            ->first();
                        $enters_sells_savesarr['ense_end_amount'] = $enters_sells_savesres->ense_end_amount - $goodsprice;
                        if ($enters_sells_savesres->ense_end_inventory == '0') {
                            $enters_sells_savesarr['ense_end_price'] = '0';
                        } else {
                            $enters_sells_savesarr['ense_end_price'] = $enters_sells_savesarr['ense_end_amount'] / $enters_sells_savesres->ense_end_inventory;
                        }
                        DB::table('enters_sells_saves')
                            ->where('ense_id', $enters_sells_savesres->ense_id)
                            ->update($enters_sells_savesarr);
                        // 更新已入库数据
                        $enters_sells_savesresult = DB::table('enters_sells_saves')
                            ->where('ense_goo_id', $v['goods_id'])
                            ->where('ense_goo_warehouse', $request['cg_wareid'])
                            ->where('ense_goo_waretype', '1')
                            ->where('ense_order_number', $cg_number)
                            ->select('ense_id', 'ense_end_amount', 'ense_end_inventory', 'ense_in_price', 'ense_in_amount', 'ense_in_num')
                            ->get();
                        $enters_sells_savesresult = json_decode(json_encode($enters_sells_savesresult), true);
                        foreach ($enters_sells_savesresult as $kk => $vv) {
                            $savesresult['ense_in_price'] = $v['univalence'];
                            $savesresult['ense_in_amount'] = $v['univalence'] * $vv['ense_in_num'];
                            $savesresult['ense_end_amount'] = $vv['ense_end_amount'] - $vv['ense_in_amount'] + $savesresult['ense_in_amount'];
                            if ($vv['ense_end_inventory'] == '0') {
                                $savesresult['ense_end_price'] = '0';
                            } else {
                                $savesresult['ense_end_price'] = $savesresult['ense_end_amount'] / $vv['ense_end_inventory'];
                            }
                            DB::table('enters_sells_saves')
                                ->where('ense_id', $vv['ense_id'])
                                ->update($savesresult);
                        }
                    }
                }
            }
            // 编辑采购商品表
            foreach ($request['goods'] as $k => $v) {
                $pugoods_data['goods_num'] = $v['goods_num'];
                $pugoods_data['univalence'] = $v['univalence'];
                $pugoods_data['money'] = $v['money'];
                $pugoodsres = DB::table('storage_goods')
                    ->where('relation_number', $cg_number)
                    ->where('goods_id', $v['goods_id'])
                    ->update($pugoods_data);
                unset($pugoods_data);
            }
            // 编辑采购单表
            //$update_data['cg_state'] = 5;//采购单状态:未入库
            $update_data['cg_settlementype'] = 2; //结算状态2待结算3已结算4待审核5部分结算
            $update_data['cg_paymentype'] = $request['cg_paymentype']; //结算方式
            $update_data['cg_invoicetype'] = $request['cg_invoicetype']; //票据类型
            $update_data['cg_delivertype'] = $request['cg_delivertype']; //交货方式
            $update_data['cg_amount'] = $request['cg_amount']; //采购总额
            $update_data['cg_remark'] = $remarks;
            $update_data['edit_time'] = date('Y-m-d H:i:s');
            $update_data['financial_user'] = $user_info->adm_id; //财审人
            $update_data['cg_paytype'] = 1; //是否账单结算1否是
            if ($update_data['cg_paymentype'] == '3') {
                if ($request['cg_yfmoney'] == $request['cg_amount']) {
                    $update_data['cg_settlementype'] = 3; //结算状态2待结算3已结算4待审核5部分结算
                } else {
                    $update_data['cg_settlementype'] = 5; //结算状态2待结算3已结算4待审核5部分结算
                }
                $update_data['cg_yfmoney'] = $request['cg_yfmoney']; //预付金额
            } else {
                $update_data['cg_yfmoney'] = 0; //预付金额
            }
            $res = DB::table('purchase_order')
                ->where('cg_number', $cg_number)
                ->update($update_data);
            $user_info = $user_info;
            $user_info->adm_id = $cg_data->cg_userid;
            if ($request['cg_paymentype'] == '3') {
                $cw_amount = $request['yfmoney'];   //应收总额
                /*foreach ($goods_ids as $key => $val) {
                    $temp = $goods_ids[$val['goods_id']];
                    $cw_amount = $cw_amount + ((float)$temp['old_univalence']*(int)$temp['goods_num']);
                }*/
                // 根据供应商id,查找供应商名称
                $chun_unit_name = DB::table('channel_unit')
                    ->where('chun_id', $cg_data->cg_supplyunit)
                    ->value('chun_unit_name');

                if ($request['cg_paymentype'] == '3') { //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天8免费
                    // 添加结款明细记录
                    $acset_res = AccountingSettlement::add(
                        $user_info,                 // [用户信息]
                        24,                          // 单据类型24采购款到发货(预付款)
                        $cg_data->cg_id,          // [与单据类型对应的id]
                        $cg_data->cg_number, // [与单据类型对应的单号]
                        2,                     // [买家类型1门店零售2来往单位]
                        $cg_data->cg_supplyunit,       // [会员/客户id]
                        $chun_unit_name,     // [来往单位名称]
                        '',         // [会计科目id]
                        2,                                // [类型1收入2支出]
                        $request['cg_yfmoney'] * 100,                 // [实际金额](此次的实收金额)
                        $request['cg_yfmoney'] * 100,                 // [合计金额](此次的应收金额)
                        0,                                // [欠收金额](此次结款后还应收金额)
                        0,                                // [抹零金额]
                        ''                                // [备注]
                    );
                    // 生成应付
                    $createBill = ReceivableBill::create(
                        $user_info, //用户信息
                        17, //类型：17.采购款到发货(预付款)
                        0, //应收账款id
                        $acset_res, //原始id(采购入库单id)
                        $cg_data->cg_number, //应收账款单号/原始号(入库单号)
                        2, //客户类型：1.门店零售 2.来往单位
                        $cg_data->cg_supplyunit, //会员id/来往单位id
                        $chun_unit_name, //来往单位名称
                        $request['cg_yfmoney'] * 100, //结算金额
                        '', //结款时间
                        '', //会计科目id
                        0, //实际金额
                        0, //抹零金额
                        1,  //状态：1.未核销 2.已核销
                        1,  //应收账单id是否是自己 1.不是 2.是
                        '',  //备注
                        0, //已收金额
                        '', //截止时间
                        1, //金额正负1正   2负值
                        20, //显示类型：20.采购款到发货（预付款）
                        2, //是否合并代收：1是2否
                        $cg_data->create_time,
                        0 //技师是否收钱：0未选择1是2否
                    );
                    // 添加结款明细业务凭证
                    $volo_data[0]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                    $volo_data[0]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                    $volo_data[0]['acsl_type'] = 1; //类型1借方2贷方
                    $volo_data[0]['acsl_borrow_subject'] = '220201'; //借方科目
                    $volo_data[0]['acsl_borrow_subject_name'] = '应付账款'; //借方科目名称
                    $volo_data[0]['acsl_borrow_price'] = $request['cg_yfmoney']; //借方金额
                    $volo_data[0]['acsl_loan_subject'] = '1001'; //贷方科目
                    $volo_data[0]['acsl_loan_subject_name'] = '库存现金'; //贷方科目名称
                    $volo_data[0]['acsl_loan_price'] = $request['cg_yfmoney']; //贷方金额
                    /*$volo_data[1]['acsl_acset_id'] = $acset_res;//结款明细凭证id
                    $volo_data[1]['acsl_shop_id'] = $user_info->adm_shop_id;//门店id
                    $volo_data[1]['acsl_type'] = 1;//类型1借方2贷方
                    $volo_data[1]['acsl_borrow_subject'] = '';//借方科目
                    $volo_data[1]['acsl_borrow_subject_name'] = '';//借方科目名称
                    $volo_data[1]['acsl_borrow_price'] = 0;//借方金额
                    $volo_data[1]['acsl_loan_subject'] = '';//贷方科目
                    $volo_data[1]['acsl_loan_subject_name'] = '';//贷方科目名称
                    $volo_data[1]['acsl_loan_price'] = 0;//贷方金额*/
                    $volo_id = DB::table('accounting_settlement_loan')->insert($volo_data);
                }
            } else {
                $acset_res = true;
            }
            if ($res && $acset_res) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '采购管理', '财审采购单', '审核通过' . $cg_number . '成功');
                if ($remarks != "") {
                    Common::addNote($user_info, $shop_id, $cg_number, "通过备注：" . $remarks, '财审采购单通过');
                }
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'审核成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败']);
            }
        } else {
            // 审核驳回
            $update_data['cg_state'] = 3; //采购单状态:未入库
            $update_data['cg_remark'] = $remarks;
            $update_data['edit_time'] = date('Y-m-d H:i:s');
            $update_data['financial_user'] = $user_info->adm_id; //财审人
            $res = DB::table('purchase_order')
                ->where('cg_number', $cg_number)
                ->update($update_data);
            if ($res) {
                Common::addLog($user_info, getRealIp($request), '采购管理', '财审采购单', '审核驳回' . $cg_number . '成功');
                if ($remarks != "") {
                    Common::addNote($user_info, $shop_id, $cg_number, "驳回备注：" . $remarks, '财审采购单驳回');
                }
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'驳回成功']);
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'驳回失败']);
            }
        }
    }

    // 确认完成
    public function confirmCompleted(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->financialAuditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);

        // 与审核返回数据一致；请粘贴复制或直接写公共方法
        $cg_data = DB::table('purchase_order')
            ->where('cg_number', $request['cg_number'])
            ->select('cg_id', 'cg_number', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone')
            ->first();
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'获取采购单数据失败']);
        }
        // 审核前
        if ($request['type'] == '1') {
            // 获取供应商名称
            $cg_data->supplyunit_name = (string)Db::table('channel_unit')
                ->where('chun_id', $cg_data->cg_supplyunit)
                ->value('chun_unit_name');
            // 获取仓库名称
            $cg_data->ware_name = DB::table('warehouse')
                ->where('ware_id', $cg_data->cg_wareid)
                ->value('ware_name');

            // 获取商品数据
            $storage_goods = DB::table('storage_goods')
                ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                ->where('relation_number', $request['cg_number'])
                ->select('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type as goo_type', 'goo_brse_id', 'goo_class')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($storage_goods as $k => $v) {
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($v->goo_brse_id)) {
                        if ($v->goo_class == 2) {
                            $storage_goods[$k]->goo_name = $brse_data[$v->goo_brse_id] . ' ' . $v->goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $storage_goods[$k]->goo_name = $brse_data[$v->goo_brse_id] . ' ' . $v->goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($v->goo_class == 2) {
                        $storage_goods[$k]->goo_name = $v->goo_bra_name . ' ' . $storage_goods[$k]->goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $storage_goods[$k]->goo_name = $v->goo_bra_name . ' ' . $storage_goods[$k]->goo_name;
                        }
                    }
                }
                unset($storage_goods[$k]->goo_brse_id);
            }
            unset($cg_data->cg_state);

            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>['cg_data'=>$cg_data, 'storage_goods'=>$storage_goods]]);
        }

        $update_data['cg_state'] = 12; //采购单状态:确认完成
        $update_data['edit_time'] = date('Y-m-d H:i:s');
        $res = DB::table('purchase_order')
            ->where('cg_number', $request['cg_number'])
            ->update($update_data);

        if ($res) {
            Common::addLog($user_info, getRealIp($request), '采购管理', '采购单', '确认完成' . $request['cg_number'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'操作成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'操作失败']);
        }
    }

    // 撤销退货单
    public function cancelrefund(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->returnGoodValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 查询采购单数据
        $find_puor = DB::table('purchase_order')
            ->where('cg_id', $request['cg_id'])
            ->select('cg_id', 'cg_number', 'cg_original_number', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone')
            ->first();
        $find_puor = json_decode(json_encode($find_puor), true); //将对象转为数组
        if ($find_puor['cg_state'] == 11) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前退货单已出库，无法撤销！！！']);
        }
        // 获取商品数据
        $storage_goods = DB::table('storage_goods')
            ->where('relation_number', $find_puor['cg_number'])
            ->select('id', 'goods_id', 'goods_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'stgo_return_goods_quantity', 'goods_number')
            ->get();
        $storage_goods = json_decode(json_encode($storage_goods), true);

        DB::beginTransaction();

        foreach ($storage_goods as $k => $v) {
            $storage_good = DB::table('storage_goods')
                ->where('relation_number', $find_puor['cg_original_number'])
                ->where('goods_id', $v['goods_id'])
                ->select('id', 'stgo_return_goods_quantity')
                ->first();
            $stodata['stgo_return_goods_quantity'] = $storage_good->stgo_return_goods_quantity - $v['goods_num'];
            $savedata = DB::table('storage_goods')
                ->where('id', $storage_good->id)
                ->update($stodata);
            $deldata = DB::table('storage_goods')
                ->where('id', $v['id'])
                ->delete();
            if (!$deldata || !$savedata) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'撤销失败']);
            }
        }
        $delpudata = DB::table('purchase_order')
            ->where('cg_id', $request['cg_id'])
            ->delete();
        if ($delpudata) {
            Common::addLog($user_info, getRealIp($request), '采购列表', '撤销退货', '采购退货单:' . $find_puor['cg_original_number'] . ' 撤销成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'撤销成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'撤销失败']);
        }
    }

    // 添加退货单
    public function returnGoods(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->returnGoodValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 查询采购单数据
        $find_puor = DB::table('purchase_order')
            ->where('cg_id', $request['cg_id'])
            ->select('cg_id', 'cg_number', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone')
            ->first();
        $find_puor = json_decode(json_encode($find_puor), true); //将对象转为数组
        // 获取商品数据
        $storage_goods = DB::table('storage_goods as stgo')
            ->leftjoin('goods as goo', 'goo.goo_id', '=', 'stgo.goods_id')
            ->where('relation_number', $find_puor['cg_number'])
            ->select('goods_id', 'goods_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'stgo_return_goods_quantity', 'goods_number as goo_goods_encode', 'goo_brse_id', 'goo_class', 'goo_bra_name')
            ->get();
        $storage_goods = json_decode(json_encode($storage_goods), true);
        // 查询系列数据
        $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        foreach ($storage_goods as $k => $v) {
            // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                if (!empty($v['goo_brse_id'])) {
                    if ($v['goo_class'] == 2) {
                        $storage_goods[$k]['goods_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goods_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $storage_goods[$k]['goods_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goods_name'];
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($v['goo_class'] == 2) {
                    $storage_goods[$k]['goods_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goods_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $storage_goods[$k]['goods_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goods_name'];
                    }
                }
            }
            unset($storage_goods[$k]['goo_brse_id']);
        }

        // 添加退货单前
        if ($request['type'] == 1) {
            // 生成退货单号
            $rule_data = DB::table('order_rule')
                ->where('orru_type', 3) //类型：1.订单编号规则 2.工单编号规则 3.采购单号规则 4.退货单号规则
                ->where('orru_cid', $user_info->adm_cid)
                ->where('orru_superior_id', $shop_id) //总店
                ->first(['orru_number', 'orru_date', 'orru_id']);
            if ($rule_data) {
                // 有此总店的数据 判断是不是今天的
                if ($rule_data->orru_date == date('Y-m-d')) {
                    // 退货单总量+1
                    $order_rule = DB::table('order_rule')
                        ->where('orru_id', $rule_data->orru_id)
                        ->increment('orru_number');

                    $today_order = $rule_data->orru_number + 1; //今天的退货单总量
                } else {
                    // 修改日期为今天 退货单总量从1开始
                    $orru_data['orru_date'] = date('Y-m-d');
                    $orru_data['orru_number'] = 1;
                    $orru_data['orru_update_time'] = date('Y-m-d H:i:s');
                    $order_rule = DB::table('order_rule')
                        ->where('orru_id', $rule_data->orru_id)
                        ->update($orru_data);

                    $today_order = 1; //今天的退货单总量
                }
            } else {
                // 新增一条数据
                $orru_data['orru_cid'] = $user_info->adm_cid;
                $orru_data['orru_superior_id'] = $shop_id;
                $orru_data['orru_shop_id'] = $user_info->adm_shop_id;
                $orru_data['orru_type'] = 4; //类型：1.订单编号规则 2.工单编号规则3.采购单号规则4.退货单号规则
                $orru_data['orru_date'] = date('Y-m-d');
                $orru_data['orru_number'] = 1;
                $order_rule = DB::table('order_rule')->insert($orru_data);

                $today_order = 1; //今天的工单总量
            }
            // 年月日时分秒是14位 退货单编号共20位 所以补零的位数为6位
            $data['cg_number'] = 'TH' . date('YmdHis') . str_pad($today_order, 4, '0', STR_PAD_LEFT);

            // 获取供应商名称
            $find_puor['supplyunit_name'] = Db::table('channel_unit')
                ->where('chun_id', $find_puor['cg_supplyunit'])
                ->value('chun_unit_name');
            // 获取仓库名称
            $find_puor['ware_name'] = DB::table('warehouse')
                ->where('ware_id', $find_puor['cg_wareid'])
                ->value('ware_name');

            unset($find_puor['cg_state']);
            $data['cg_data'] = $find_puor;
            $data['cg_goods'] = $storage_goods;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->returnGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 添加退货单
        $allData = $request->all();
        // 去除数据中所包含的换行符等特殊符号
        $allData = RemoveLineFeed($allData);
        // 验证退货单号是否重复
        $cg_id = DB::table('purchase_order')
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where('cg_number', $allData['cg_number'])
            ->value('cg_id');
        if ($cg_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'退货单号重复']);
        }

        $goods_data = $allData['goods'];
        unset($allData['goods']);

        // 给采购表的数据赋值
        $cg_data = [];
        $cg_data['cg_number']      = $allData['cg_number']; //退货单号
        $cg_data['cg_original_number'] = $find_puor['cg_number']; //原始单号
        $cg_data['cg_amount']      = $allData['cg_amount']; //退换总金额
        $cg_data['cg_purchasetime'] = $find_puor['cg_purchasetime']; //退换日期
        $cg_data['cg_supplyunit']  = $find_puor['cg_supplyunit']; //供货单位
        $cg_data['cg_invoicetype'] = $find_puor['cg_invoicetype']; //票据类型0不开票1普通发票2专用发票
        $cg_data['cg_paymentype']  = $find_puor['cg_paymentype']; //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天
        $cg_data['cg_delivertype'] = $find_puor['cg_delivertype']; //交货方式1送货上门2自提
        $cg_data['cg_wareid']      = $find_puor['cg_wareid']; //仓库id
        $cg_data['cg_waon_class']  = $find_puor['cg_waon_class']; //仓库类别1货物仓2非货物仓3旧货仓4临时仓
        $cg_data['contract_number'] = $find_puor['contract_number']; //合同单号
        $cg_data['contact_phone']  = $find_puor['contact_phone']; //联系电话
        $cg_data['cg_remark']      = $allData['cg_remark']; //备注
        $cg_data['contact_name']   = $find_puor['contact_name']; //联系人
        $cg_data['cg_settlementype']   = 2; //结算状态2待结算3已结算4待审核5部分结算
        $cg_data['create_time'] = date('Y-m-d H:i:s'); //创建时间
        $cg_data['cg_state']   = 6; //采购单状态1审核中3驳回编辑5未入库6未出库7部分出库8部分入库11完成(9待结算10待审核)15申请终止17中止
        $cg_data['company_id'] = $user_info->adm_cid;
        $cg_data['cg_userid']  = $user_info->adm_id;
        $cg_data['cg_creator'] = $user_info->adm_name;
        $cg_data['cg_superior_shop_id'] = $shop_id;
        $cg_data['cg_shop_id'] = $user_info->adm_shop_id;
        $cg_data['cg_type'] = 2; //出库单
        $cg_data['cg_types'] = 2; //采购退货

        // 处理数组的商品，因为退货有全部退货这个操作所以需要重新计算库存；
        $storage_goods = array_column($storage_goods, null, 'goods_id');
        $total_value = 0;
        // 处理商品数据
        foreach ($goods_data as $key => $val) {
            if (!isset($storage_goods[$val['goods_id']])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'无法退货非本采购单商品']);
            }

            $temp = $storage_goods[$val['goods_id']];

            if ($temp['ruku_num'] < $goods_data[$key]['goods_num']) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'退货数量不可超过入库数量']);
            }

            $total_value += $goods_data[$key]['goods_num'] * $temp['univalence'];
        }

        $purchase_goods = [];
        $goods_name = '';
        foreach ($goods_data as $key => $val) {
            if ($val['goods_num'] < 1) {
                continue;
            }

            $temp = $storage_goods[$val['goods_id']];

            // 提前将每个商品的分算平均后的价格计算完毕；  如果采购单价或采购总价为0 则赋值为0
            if ($cg_data['cg_amount'] <= '0' || $temp['univalence'] <= '0') {
                $old_univalence = 0;
            } else {
                $old_univalence = round($cg_data['cg_amount'] / $total_value * $temp['univalence'], 2); //分算平均后的单价
            }
            // 搜索商品id对应的商品名称、商品编号
            $find_goods_data = DB::table('goods')
                ->where('goo_id', $temp['goods_id'])
                ->select('goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_price', 'goo_fid', 'goo_class')
                ->first();
            if ($find_goods_data->goo_class == 1) { //类型：1自营商品2系统商品
                // 查询商品附属表
                $goaf_another_name = DB::table('goods_affiliate')
                    ->where('goaf_goo_id', $temp['goods_id'])
                    ->where('goaf_shop_id', $user_info->adm_shop_id)
                    ->value('goaf_another_name');
                if (!empty($goaf_another_name)) {
                    $find_goods_data->goo_name = $goaf_another_name;
                }
            } else {
                // 查询系统商品属性表
                $gosa_another_name = DB::table('goods_system_affiliate')
                    ->where('gosa_goo_id', $temp['goods_id'])
                    ->where('gosa_shop_id', $user_info->adm_shop_id)
                    ->value('gosa_another_name');
                if (!empty($gosa_another_name)) {
                    $find_goods_data->goo_name = $gosa_another_name;
                }
            }
            $temp['goods_name'] = $find_goods_data->goo_name;
            $goods_name = $goods_name . ',' . $temp['goods_name'] . $temp['goo_goods_encode'];
            $purchase_goods[] = [
                'company_id' => $user_info->adm_cid,
                'stgo_superior_shop_id' => $shop_id,
                'stgo_shop_id' => $user_info->adm_shop_id,
                'goods_id' => $val['goods_id'],
                'relation_number' => $allData['cg_number'],
                'goods_number' => $temp['goo_goods_encode'],
                'goods_name' => $temp['goods_name'],
                'storehouse' => $cg_data['cg_wareid'],
                'cg_goodsnum' => $val['goods_num'],
                'goods_num' => $val['goods_num'],
                'stgo_return_goods_quantity' => $val['goods_num'],
                'univalence' => $temp['univalence'],
                'creator' => $user_info->adm_name,
                'create_time' => date('Y-m-d H:i:s'),
                'ruku_num' => 0,
                'tax_rate' => (int)$temp['tax_rate'],
                'currency' => $temp['currency'],
                'money' => $temp['univalence'] * $val['goods_num'],
                'company_unit' => $temp['company_unit'],
                'old_univalence' => $old_univalence,
                'goods_type' => $val['goods_type']
            ];
            $update_data['stgo_return_goods_quantity'] = $temp['stgo_return_goods_quantity'] + $val['goods_num'];
            // 调整原来的采购单号的退货数量
            $stgo_res = DB::table('storage_goods')
                ->where('relation_number', $find_puor['cg_number'])
                ->where('goods_id', $val['goods_id'])
                ->update($update_data);
            if (!$stgo_res) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'退货失败']);
            }
        }

        if (empty($storage_goods)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品不能为空,请重新填写采购退货单']);
        }

        $cg_data['goods_name'] = $goods_name;
        DB::beginTransaction();

        DB::connection()->enableQueryLog();
        // 新增采购退货单
        $res1 = DB::table('purchase_order')->insert($cg_data);
        // 新增商品数据
        $res2 = DB::table('storage_goods')->insert($purchase_goods);

        // 门店版 查询门店版本
        $shop_versions = DB::table('shop')
            ->where('shop_id', $shop_id)
            ->value('shop_versions');
        if ($shop_versions == 1) {
            $request_del['api_token'] = $request['api_token'];
            $request_del['rk_remark'] = $cg_data['cg_remark'];
            $request_del['cg_number'] = $cg_data['cg_number'];
            $request_del['goods'] = $goods_data;
            $request_del['type'] = 2;
            $deli_return = $this->delivery($request_del);
            $deli_return = json_decode($deli_return->content(), true);
            if ($deli_return['code'] == 200 && $res1 && $res2) {
                $deli_res = true;
                Common::addLog($user_info, getRealIp($request), '出入库列表', '采购出库', $deli_return['rk_number'] . '成功');
            } else {
                return response()->json($deli_return);
            }
        } else {
            $deli_res = true;
        }
        if ($res1 && $res2 && $deli_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购管理', '添加退货采购单', $cg_data['cg_number'] . '成功');
            if ($cg_data['cg_remark'] != '') {
                Common::addNote($user_info, $shop_id, $cg_data['cg_number'], $cg_data['cg_remark'], '采购退货');
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'退货成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'退货失败']);
        }
    }

    // 出库
    private function delivery($request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $cg_number = $request['cg_number'];
        // 获取采购单的数据
        $cg_data = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->select('cg_id', 'cg_number', 'cg_original_number', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone', 'create_time')
            ->first();
        $cg_data = json_decode(json_encode($cg_data), true); //将对象转换为数组
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该状态下无法操作']);
        }
        if (empty($cg_data) || !in_array($cg_data['cg_state'], [6, 7])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该状态下无法出库']);
        }

        $rk_remarks = $request['rk_remark'];

        // 出库
        $goods_data = $request['goods'];
        foreach ($goods_data as $key => $val) {
            if (!isset($val['goods_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品格式有误']);
            }
            if (!isset($val['goods_num'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品格式有误']);
            }
            if ((int) $val['goods_num'] < 1) {
                unset($goods_data[$key]);
                continue;
            }
        }
        if (empty($goods_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品数量不能为空']);
        }
        // 查询采购商品的数据
        $storage_goods = DB::table('storage_goods')
            ->where('relation_number', $cg_number)
            ->select('goods_id', 'goods_number', 'storehouse', 'goods_name', 'cg_goodsnum', 'goods_num', 'univalence', 'ruku_num', 'company_id', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'old_univalence')
            ->get()->toArray();
        $storage_goods = json_decode(json_encode($storage_goods), true); //将对象转换为数组

        $storage_goods = array_column($storage_goods, null, 'goods_id');

        $rk_number = 'CK' . rand(10, 99) . date('mdHis') . rand(100000, 999999); //入库单号

        $goods_id = array_column($goods_data, 'goods_id');

        DB::beginTransaction();

        $goods_name = '';
        $cw_amount = 0;  //应收总额
        $ruku_goods = []; //出库商品数组
        $actual_count = 0; //实际出库总数量
        $osld_out_key = 0;
        foreach ($goods_data as $key => $value) {
            if (!isset($storage_goods[$value['goods_id']])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'无法出库非本退货单商品']);
            }

            $temp = $storage_goods[$value['goods_id']];

            if ($value['goods_num'] + $temp['ruku_num'] > $temp['goods_num']) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'出库数量不可超过入库数量']);
            }

            $temp['company_id'] = $user_info->adm_cid;
            $temp['stgo_superior_shop_id']        = $shop_id;
            $temp['stgo_shop_id']    = $user_info->adm_shop_id;
            $temp['relation_number'] = $rk_number;             //单号
            $temp['creator']        = $user_info->adm_name; //创建人
            $temp['create_time']    = date('Y-m-d H:i:s');    //创建时间
            $temp['ruku_num']       = 0 - $value['goods_num'];      //数量

            $cw_amount = $cw_amount + ((float)$temp['univalence'] * (int)$value['goods_num']);

            $goods_name = $goods_name . $temp['goods_name'] . $temp['goods_number'];

            // 变更出库数量 和到货时间，并将库存减上去
            $res1 = DB::table('storage_goods')
                ->where('relation_number', $cg_number)
                ->where('goods_id', $value['goods_id'])
                ->decrement('ruku_num', $value['goods_num']);

            $goo_actual_count[$value['goods_id']] = $value['goods_num']; //商品id对应的实际出库的数量
            $goo_actual_id[] = $value['goods_id'];
            $goo_inventory[] = 1;

            $oure_goods_data[$value['goods_id']]['goo_quantity'] = $value['goods_num']; //出入库商品数量
            $oure_goods_data[$value['goods_id']]['goo_inventory'] = 1; //出入库商品类型，类型1良品2优先，页面没有用到这个，暂定1

            // 出入库记录需要
            $oure_goods_id[$value['goods_id']] = $value['goods_id']; //出入库商品id
            $oure_goods_quantity[$value['goods_id']] = $value['goods_num']; //出入库商品数量
            $oure_goods_inventory[$value['goods_id']] = 1; //出入库商品类型，类型1良品2优先，页面没有用到这个，暂定1

            $actual_count -= $value['goods_num']; //实际出库总数量

            if (!$res1) {
                throw new Exception('更新出库数量失败');
            }
            $ruku_goods[] = $temp;

            // 库存锁定-出入库记录表
            $osld_goo_datas[$osld_out_key]['goo_waon_class'] = $cg_data['cg_waon_class']; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
            $osld_goo_datas[$osld_out_key]['goo_id'] = $value['goods_id']; //商品id
            $osld_goo_datas[$osld_out_key]['goo_number'] = $value['goods_num']; //商品数量
            $osld_goo_datas[$osld_out_key]['goo_out_in_type'] = 1; //出入库类型：1出库2入库3锁定4取消锁定
            $osld_goo_datas[$osld_out_key]['goo_inventory'] = 1; //类型1良品2优先3待检测
            // 查询仓库商品库存数量
            $find_in_wago_data = DB::table('warehouse_goods')
                ->where('wago_ware_id', $cg_data['cg_wareid'])
                ->where('wago_class', $cg_data['cg_waon_class'])
                ->where('wago_goo_id', $value['goods_id'])
                ->select('wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                ->first();
            $osld_goo_datas[$osld_out_key]['old_stock_number'] = $find_in_wago_data->wago_stock_number; //旧的商品良品库存数量
            $osld_goo_datas[$osld_out_key]['old_stock_lock_number'] = $find_in_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
            $osld_goo_datas[$osld_out_key]['old_priority_number'] = $find_in_wago_data->wago_priority_stock_number; //旧的商品优先库存数量
            $osld_goo_datas[$osld_out_key]['old_priority_lock_number'] = $find_in_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
            $osld_goo_datas[$osld_out_key]['old_unchecked_number'] = $find_in_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量
            $osld_goo_datas[$osld_out_key]['new_stock_number'] = $find_in_wago_data->wago_stock_number - $value['goods_num']; //新的商品良品库存数量
            $osld_goo_datas[$osld_out_key]['new_stock_lock_number'] = $find_in_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
            $osld_goo_datas[$osld_out_key]['new_priority_number'] = $find_in_wago_data->wago_priority_stock_number; //新的商品优先库存数量
            $osld_goo_datas[$osld_out_key]['new_priority_lock_number'] = $find_in_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
            $osld_goo_datas[$osld_out_key]['new_unchecked_number'] = $find_in_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
            $osld_goo_datas[$osld_out_key]['osld_update_time'] = date('Y-m-d H:i:s'); //更新时间
            $osld_goo_datas[$osld_out_key] = (Object)$osld_goo_datas[$osld_out_key];
            $osld_out_key++;
        }

        // 出库单数组
        $ruku_data = [];
        $ruku_data['rk_number'] = $rk_number; //单号
        $ruku_data['cg_number'] = $cg_data['cg_number']; //采购单号
        $ruku_data['rk_wareid'] = $cg_data['cg_wareid']; //仓库id
        $ruku_data['rk_waon_class'] = $cg_data['cg_waon_class']; //仓库类别
        $ruku_data['rk_state'] = 5;
        $ruku_data['rk_type']  = 2; //采购退货
        $ruku_data['rk_creator'] = $user_info->adm_name;
        $ruku_data['create_time'] = date('Y-m-d H:i:s');
        $ruku_data['company_id'] = $user_info->adm_cid;
        $ruku_data['rk_userid'] = $user_info->adm_id;
        $ruku_data['rk_inputid'] = $user_info->adm_id;
        $ruku_data['rk_remarks'] = (string) $rk_remarks;
        $ruku_data['supplyunit'] = $cg_data['cg_supplyunit'];
        $ruku_data['arrival_time'] = date('Y-m-d H:i:s');
        $ruku_data['rk_waretype'] = 1;

        $ruku_data['rk_superior_shop_id'] = $shop_id;
        $ruku_data['rk_shop_id'] = $user_info->adm_shop_id;
        $ruku_data['rk_amount'] = $cw_amount;

        $edit_cgdata = [];

        $cg_goods = DB::table('storage_goods')
            ->where('relation_number', $cg_number)
            ->whereRaw('ruku_num < goods_num')
            ->select('id')
            ->first();
        $cg_goods = json_decode(json_encode($cg_goods), true);
        $edit_cgdata['cg_state'] = 11;
        $edit_cgdata['dh_time']  = date('Y-m-d H:i:s');
        $edit_cgdata['edit_time'] = date('Y-m-d H:i:s');

        DB::connection()->enableQueryLog();

        $res3 = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->update($edit_cgdata);

        // 添加出库单
        $res1 = Db::table('ware_inorder')->insertGetId($ruku_data);

        // 2. 查询仓库的库存数量
        $find_waon = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $cg_data['cg_wareid'])
            ->where('waon_class', $cg_data['cg_waon_class'])
            ->select('waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();
        // 更改仓库库存总数量
        $waon_data['waon_all_amount'] = $find_waon->waon_all_amount + $actual_count; //商品总库存
        $waon_data['waon_stock_fine_amount'] = $find_waon->waon_stock_fine_amount + $actual_count; //良品总库存
        $waon_res = DB::table('warehouse_onhand')
            ->where('waon_id', $find_waon->waon_id)
            ->update($waon_data);

        // 3.生成出入库记录
        $oure_res = OutinRecord::addition(
            $user_info, //用户信息
            $cg_data['cg_id'], //原始单的关联id
            $cg_data['cg_number'], //原始单的关联单号
            3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
            2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            $cg_data['cg_supplyunit'], //选择的客户id,会员id/单位id
            $rk_number, //原始单号，旧货回收单单号
            0, //入库仓库id
            $cg_data['cg_wareid'], //出库仓库id
            abs($actual_count), //出库的商品总数量
            2, //类型 5.退换回收单 9发货单 11换货出库12换货入库13退货入库14退货出库
            3, //操作类型：1锁定库存2出库3入库4调货5发货
            $find_waon->waon_stock_fine_amount, //良品总库存
            $find_waon->waon_lock_fine_amount, //良品锁定数量
            $find_waon->waon_stock_priority_amount, //优先总库存
            $find_waon->waon_lock_priority_amount, //优先锁定数量
            $find_waon->waon_stock_unchecked_amount, //待检测总库存
            1, //出入库类型：1出库，2入库
            $cg_data['cg_waon_class'], //仓库类别
            $oure_goods_id, //商品id
            $oure_goods_quantity, //商品数量
            $oure_goods_inventory //出库类型1良品2优先
        );
        // 库存锁定-出入库记录
        $oslr_out_res = OutinStockLock::addition(
            $user_info, //用户信息
            $cg_data['cg_id'], //原始单的关联id
            $cg_data['cg_number'], //原始单的关联单号
            3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
            2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            $cg_data['cg_supplyunit'], //选择的客户id,会员id/单位id
            $rk_number, //原始单号
            $cg_data['cg_wareid'], //入库的仓库id
            abs($actual_count), //入库总数量
            17, //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库
            $find_waon->waon_stock_fine_amount, //良品总库存
            $find_waon->waon_lock_fine_amount, //良品锁定数量
            $find_waon->waon_stock_priority_amount, //优先总库存
            $find_waon->waon_lock_priority_amount, //优先锁定数量
            $find_waon->waon_stock_unchecked_amount, //待检测总库存
            1, //出入库类型：1出库，2入库
            $osld_goo_datas
        );
        unset($osld_goo_datas);
        // 4.2 查询仓库商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $cg_data['cg_wareid'])
            ->where('wago_class', $cg_data['cg_waon_class'])
            ->whereIn('wago_goo_id', $goods_id)
            ->get(['wago_id', 'wago_stock_number', 'wago_goo_id']);
        $warehouse_goods = json_decode(json_encode($warehouse_goods), true); //将对象转换为数组

        // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
        $sql = 'UPDATE `faster_warehouse_goods` SET ';
        $stock_number_sql = '';
        $update_time_sql = '';
        $ids = '';
        foreach ($warehouse_goods as $key => $value) {
            // 判断库存数量
            $surplus_quantity = $value['wago_stock_number'] - $goo_actual_count[$value['wago_goo_id']];
            if ($surplus_quantity < 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓库内库存数量不足']);
            }

            // 要更改的商品库存数量
            $stock_number = $value['wago_stock_number'] - $goo_actual_count[$value['wago_goo_id']];
            // 更改商品库存数量
            $stock_number_sql = $stock_number_sql . ' WHEN ' . $value['wago_id'];
            $stock_number_sql = $stock_number_sql . ' THEN ' . $stock_number;
            // 更改时间
            $update_time_sql = $update_time_sql . ' WHEN ' . $value['wago_id'];
            $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

            $ids = $ids . $value['wago_id'] . ',';

            // 删除已更改的商品数据
            unset($goo_actual_count[$value['wago_goo_id']]);
        }

        if (!empty($stock_number_sql)) {
            $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $stock_number_sql . ' END,';
            $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
            $ware_edit_res = DB::update($sql);
        } else {
            $ware_edit_res = true;
        }

        // 根据供应商id,查找供应商名称
        $chun_unit_name = DB::table('channel_unit')
            ->where('chun_id', $cg_data['cg_supplyunit'])
            ->value('chun_unit_name');

        // 应收
        $createBill = ReceivableBill::create(
            $user_info, //用户信息
            16, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
            0, //应收账款id
            $cg_data['cg_id'], //原始id(订单id)
            $cg_data['cg_number'], //应收账款单号/原始号(订单编号)
            2, //客户类型：1.门店零售 2.来往单位
            $cg_data['cg_supplyunit'], //会员id/来往单位id
            $chun_unit_name, //来往单位名称
            $cw_amount * 100, //结算金额
            date('Y-m-d H:i:s'), //结款时间
            '', //会计科目id
            0, //实际金额
            0, //抹零金额
            1,  //状态：1.未核销 2.已核销
            1,  //应收账单id是否是自己 1.不是 2.是
            '',  //备注
            0, //已收金额
            '', //截止时间
            1, //金额正负1正   2负值
            19, //显示类型：18采购退货单
            2, //是否合并代收：1是2否
            $cg_data['create_time'],
            0 //技师是否收钱：0未选择1是2否
        );
        // 查询供应商名称
        $unit_name = DB::table('channel_unit')
            ->where('chun_id', $cg_data['cg_supplyunit'])
            ->value('chun_unit_name');

        // 生成凭证单据
        $vore_data = WorkOrder::voucherReceipts($user_info, $user_info->adm_shop_id, 5, 0, '', $cg_data['cg_id'], $cg_data['cg_number'], $cg_data['cg_amount'] * 100, 0, 0, '', '1', 2, $cg_data['cg_supplyunit'], $unit_name);
        if (!$vore_data) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'出库失败']);
        }

        // 添加商品表
        $res2 = Db::table('storage_goods')->insert($ruku_goods);
        if ($res1 && $res2 && $res3 && $waon_res && $oure_res && $ware_edit_res && $createBill && $oslr_out_res) {
            DB::commit();
            if ($rk_remarks != '') {
                Common::addNote($user_info, $shop_id, $ruku_data['rk_number'], $rk_remarks, '添加出库单');
            }
            return response()->json(['code'=>200, 'msg'=>'error', 'data'=>'出库成功', 'rk_number'=>$rk_number]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'出库失败']);
        }
    }

    // 查看详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info  = Common::getUserInfo($request['api_token']);

        // 获取采购单数据
        $puor_data = DB::table('purchase_order')
            ->where('cg_id', $request['cg_id'])
            ->select('cg_id', 'cg_number', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone')
            ->first();
        $puor_data = json_decode(json_encode($puor_data), true);

        if ($puor_data['cg_paymentype'] != '4') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'只有货到付款的可以改价']);
        }

        $acset_state = DB::table('accounting_settlement')
            ->where('acset_original_number', $request['number'])
            ->value('acset_state');
        if ($acset_state != '1') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'只有财务未核对的可以改价']);
        }

        // 查询入库单的数据
        $wain_data = DB::table('ware_inorder')
            ->where('rk_number', $request['number'])
            ->select('rk_number', 'cg_number', 'rk_amount', 'rk_id')
            ->first();
        $allData = $request->all();
        // 去除数据中所包含的换行符等特殊符号
        $allData = RemoveLineFeed($allData);

        $goods_data = $allData['goods'];
        unset($allData['goods']);
        $update_data['cg_change_adm_id'] = $user_info->adm_id; //改价人
        $update_data['cg_change_amount'] = $allData['cg_change_amount']; //改价总额
        $update_data['cg_remark'] = isset($allData['cg_remark']) ? $allData['cg_remark'] : ''; //备注
        $update_data['cg_change_time'] = date('Y-m-d H:i:s'); //改价时间
        $update_data['edit_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();

        $total_value = 0;
        foreach ($goods_data as $key => $val) {
            $total_value = $total_value + ((int)$val['goods_num'] * (float)$val['univalence']);
        }

        $storage_goods = DB::table('storage_goods')
            ->where('relation_number', $request['number'])
            ->select('goods_id', 'goods_number', 'storehouse', 'goods_name', 'cg_goodsnum', 'goods_num', 'univalence', 'ruku_num', 'company_id', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'old_univalence', 'create_time')
            ->orderBy('ruku_num', 'asc')
            ->get();
        $storage_goods = json_decode(json_encode($storage_goods), true); //将对象转换为数组

        $goods_ids = array_column($storage_goods, null, 'goods_id');

        $cw_amount = 0;
        foreach ($goods_data as $key => $val) {
            $temp = $goods_ids[$val['goods_id']];
            // 改价后的总金额
            $cw_amount = $val['univalence'] * $val['goods_num'];
            $current_money = $wain_data->rk_amount - $temp['money'] + $cw_amount;
            $sssg_update_data['sssg_surplus_average_cost'] = $val['univalence'] * 100;
            $sssg_update_data['sssg_surplus_cost'] = $cw_amount * 100;
            $sssg_update_data['sssg_month_enter_cost'] = $cw_amount * 100; //月入成本
            $sssg_update_data['sssg_surplus_cost_calculate'] = $cw_amount * 100; //进销存结余成本
            $sssg_update_res = DB::table('stock_sell_storage_goods')
                ->where('sssg_goo_id', $val['goods_id'])
                ->where('sssg_ware_id', $temp['storehouse'])
                ->where('sssg_waon_class', $temp['goods_type'])
                ->update($sssg_update_data);
            // 进销存记录更改     高献昌
            // 旧记录查询
            $staretime['start_time'] = date("Y-m-d H:i:s", (strtotime($temp['create_time']) - 1));
            $staretime['end_time'] = date("Y-m-d H:i:s", (strtotime($temp['create_time']) + 2));
            // 修改该入库记录
            $ense_result = DB::table('enters_sells_saves')
                ->where('ense_order_number', $puor_data['cg_number'])
                ->where('ense_goo_id', $val['goods_id'])
                ->where('ense_goo_waretype', $puor_data['cg_waon_class'])
                ->where('ense_goo_warehouse', $puor_data['cg_wareid'])
                ->where(function ($query) use ($staretime) {
                    $query->whereBetween('ense_time', [$staretime['start_time'], $staretime['end_time']]);
                })
                ->select('ense_id', 'ense_end_inventory', 'ense_end_amount', 'ense_in_price', 'ense_in_amount')
                ->first();
            $purg_data['ense_in_price'] = $val['univalence'];
            $purg_data['ense_in_amount'] = $cw_amount;
            $purg_data['ense_end_amount'] = $ense_result->ense_end_amount - $ense_result->ense_in_amount + $cw_amount;
            if ($ense_result->ense_end_inventory == '0') {
                $purg_data['ense_end_price'] = '0';
            } else {
                $purg_data['ense_end_price'] = sprintf("%.4f", $purg_data['ense_end_amount'] / $ense_result->ense_end_inventory);
            }
            $pure_res = DB::table('enters_sells_saves')
                ->where('ense_id', $ense_result->ense_id)
                ->update($purg_data);
            // 修改最后一条记录
            $ense_end_result = DB::table('enters_sells_saves')
                ->where('ense_goo_id', $val['goods_id'])
                ->where('ense_goo_waretype', $puor_data['cg_waon_class'])
                ->where('ense_goo_warehouse', $puor_data['cg_wareid'])
                ->orderBy('ense_id', 'desc')
                ->select('ense_id', 'ense_end_inventory', 'ense_end_amount')
                ->first();
            $ense_enddate['ense_end_amount'] = $ense_end_result->ense_end_amount - $ense_result->ense_in_amount + $cw_amount;
            if ($ense_end_result->ense_end_inventory == '0') {
                $ense_enddate['ense_end_price'] = '0';
            } else {
                $ense_enddate['ense_end_price'] = sprintf("%.4f", $ense_enddate['ense_end_amount'] / $ense_end_result->ense_end_inventory);
            }
            DB::table('enters_sells_saves')
                ->where('ense_id', $ense_end_result->ense_id)
                ->update($ense_enddate);
            if (!$sssg_update_res || !$pure_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败']);
            }
        }

        // 修改商品表
        $sql = 'UPDATE `faster_storage_goods` SET ';
        $univalence_sql = '';
        $old_univalence_sql = '';
        $money_sql = '';
        //$update_time_sql = '';
        $ids = '';
        foreach ($goods_data as $key => $val) {
            // 更改价格
            $univalence_sql = $univalence_sql . ' WHEN ' . $val['goods_id'];
            $univalence_sql = $univalence_sql . ' THEN ' . $val['univalence'];

            // 提前分算平均，如果采购总价为0或者单品为0 则赋值为0；
            if ($val['univalence'] <= 0) {
                $old_univalence_sql = $old_univalence_sql . ' WHEN ' . $val['goods_id'];
                $old_univalence_sql = $univalence_sql . ' THEN 0';
            } else {
                $old_univalence_sql = $old_univalence_sql . ' WHEN ' . $val['goods_id'];
                $old_univalence_sql = $old_univalence_sql . ' THEN ' . round($allData['cg_change_amount'] / $total_value * $val['univalence'], 2);
            }

            // 更改价格
            $money_sql = $money_sql . ' WHEN ' . $val['goods_id'];
            $money_sql = $money_sql . ' THEN ' . $val['univalence'] * $val['goods_num'];

            // 更改时间
            //$update_time_sql = $update_time_sql . ' WHEN ' . $val['goods_id'];
            //$update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

            $ids = $ids . $val['goods_id'] . ',';
        }
        $sql = $sql . ' `univalence` = CASE `goods_id`' . $univalence_sql . ' END,'; //商品售价
        $sql = $sql . ' `old_univalence` = CASE `goods_id`' . $old_univalence_sql . ' END,'; //商品代收金额
        $sql = $sql . ' `money` = CASE `goods_id`' . $money_sql . ' END'; //商品总金额
        //$sql = $sql . ' `create_time`=  CASE `goods_id` ' . $update_time_sql . ' END';
        $sql = $sql . ' WHERE `relation_number` = "' . $request['number'] . '" AND `goods_id` IN (' . trim($ids, ',') . ')';
        $stgo_res = DB::update($sql);

        // 修改采购单表
        $puor_res = DB::table('purchase_order')
            ->where('cg_id', $request['cg_id'])
            ->update($update_data);
        // 修改入库表的总金额
        $wain_update_data['rk_amount'] = $current_money;
        $wain_update_data['edit_time'] = date('Y-m-d H:i:s');
        $wain_res = DB::table('ware_inorder')
            ->where('rk_number', $request['number'])
            ->update($wain_update_data);

        if ($stgo_res && $puor_res && $wain_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购管理', '采购改价', $request['number'] . '改价成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'改价成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'改价失败']);
        }
    }

    // 解除封账期
    public function relieveAccount(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->relieveAccountValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $puor_data = DB::table('purchase_order')
            ->where('cg_id', $request['cg_id'])
            ->select('cg_state', 'cg_number')
            ->first();
        if ($puor_data->cg_state != '14') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'只有封账状态下才能解封']);
        }

        $update_data['cg_state'] = 11;
        $update_data['edit_time'] = date('Y-m-d H:i:s');
        $res = DB::table('purchase_order')
            ->where('cg_id', $request['cg_id'])
            ->update($update_data);
        if ($res) {
            // 获取当前操作账号信息
            $user_info  = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '采购管理', '采购单', '解除封账' . $puor_data->cg_number . '成功');
            return response()->json(['code'=>200, 'msg'=>'error', 'data'=>'解除封账成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'解除封账失败']);
        }
    }

    // 获取待生成账单列表
    public function getList(Request $request)
    {
        $user_info  = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $cg_data = Db::table('purchase_order')
            ->where('cg_shop_id', $shop_id)
            ->where('is_del', 1)
            ->whereIn('cg_state', array('11', '12'))
            ->where('cg_settlementype', '2')
            ->where('cg_supplyunit', $request['cg_supplyunit'])
            ->where(function ($query) use ($request) {
                $query->whereBetween('create_time', [$request['start_time'], $request['end_time'] . " 23:59:59"]);
            })
            ->select('cg_id', 'cg_number', 'cg_amount', 'create_time', 'cg_settlementype')
            ->orderby('create_time', 'asc')
            ->get();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$cg_data]);
    }

    // 生成账单管理
    public function generateBill(Request $request)
    {
        DB::beginTransaction();
        try {
            $user_info  = Common::getUserInfo($request['api_token']);

            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

            $cg_numberArr = $request->input('cg_number');
            if (!isset($cg_numberArr) || !is_array($cg_numberArr)) {
                throw new Exception('参数格式错误', 1);
            }
            $cg_data = Db::table('purchase_order')
                ->whereIn('cg_number', $cg_numberArr)
                ->where('is_del', 1)
                ->whereIn('cg_state', array('11', '12'))
                ->where('cg_settlementype', '2')
                ->select('cg_id', 'cg_number', 'cg_state', 'cg_amount', 'cg_supplyunit', 'create_time', 'cg_settlementype')
                ->orderby('create_time', 'asc')
                ->get();
            $cg_data = json_decode(json_encode($cg_data), true);
            // 如果为空，代表没有完成的采购单
            if (empty($cg_data)) {
                throw new Exception('只有“已完成”的采购单才能生成账单');
            }
            // 如果不等，代表存在没有完成的采购单
            if (count($cg_data) != count($cg_numberArr)) {
                throw new Exception('只有“已完成”的采购单才能生成账单！');
            }

            $number = 'CZ' . time() . rand(1000000, 9999999);
            $goods_data = Db::table('storage_goods')
                ->whereIn('relation_number', $cg_numberArr)
                ->select('relation_number', 'goods_num')
                ->get();
            $goods_data = json_decode(json_encode($goods_data), true);
            $add_data['orbi_goods_sum'] = 0; //商品总量
            foreach ($goods_data as $k => $v) {
                if (substr($v['relation_number'], 0, 2) == 'TH') {
                    $add_data['orbi_goods_sum'] = abs($add_data['orbi_goods_sum'] - $v['goods_num']);
                } else {
                    $add_data['orbi_goods_sum'] = $add_data['orbi_goods_sum'] + $v['goods_num'];
                }
            }
            // 生成账单数据
            $add_data['orbi_cid'] = $user_info->adm_cid;
            $add_data['orbi_shop_id'] = $user_info->adm_shop_id;
            $add_data['orbi_superior_shop_id'] = $shop_id;
            $add_data['orbi_number'] = $number;
            $add_data['orbi_order_amount'] = count($cg_data); //单量
            $add_data['orbi_start_time'] = $cg_data[0]['create_time']; //开始日期
            $add_data['orbi_state'] = 3; //待审核
            $add_data['orbi_type'] = 2;
            $add_data['orbi_client_id'] = (int) $cg_data[0]['cg_supplyunit']; //渠道/客户id
            // 获取到商品总量/合计金额/结算金额
            $add_data['orbi_total_price'] = 0; //合计金额

            $cg_supplyunit = $cg_data[0]['cg_supplyunit'];
            $add_data['orbi_create_type'] = 5; //账单类型
            $add_data['orbi_create_adm_id'] = $user_info->adm_id;
            // 判断供货单位是否一致
            foreach ($cg_data as $key => $val) {
                $add_data['orbi_end_time'] = $val['create_time'];
                if (substr($val['cg_number'], 0, 2) == 'TH') {
                    $add_data['orbi_total_price'] -= $val['cg_amount']; //金额
                } else {
                    $add_data['orbi_total_price'] += $val['cg_amount']; //金额
                }

                if ($val['cg_settlementype'] != 2) {
                    throw new Exception($val['cg_number'] . ',已生成结算单');
                }
                if ($cg_supplyunit != $val['cg_supplyunit']) {
                    throw new Exception('供货单位不一致,无法生成账单', 1);
                }
            }
            if ($add_data['orbi_total_price'] > 0) {
                $add_data['orbi_plus_minus'] = 2; //金额正负1正
            } else {
                $add_data['orbi_total_price'] = substr($add_data['orbi_total_price'], 1);
                if (empty($add_data['orbi_total_price'])) {
                    $add_data['orbi_total_price'] = 0;
                }
                $add_data['orbi_plus_minus'] = 1; //金额正负1正
            }
            $add_data['orbi_total_price'] = $add_data['orbi_total_price'] * 100;
            $add_data['orbi_bill_price'] = $add_data['orbi_total_price']; //结算金额
            $add_data['orbi_actual_price'] = $add_data['orbi_total_price']; //实收金额
            $prbi_id = DB::table('order_bill')->insertGetId($add_data);
            $edit_pur = Db::table('purchase_order')
                ->whereIn('cg_number', $cg_numberArr)
                ->update(['cg_settlementype' => 3, 'cg_paytype' => 2, 'cg_zdnumber' => $number, 'edit_time' => date('Y-m-d H:i:s')]);
            if ($prbi_id && $edit_pur) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '采购管理', '生成账单', $add_data['orbi_number'] . '成功');
                $res_data = ['code'=>200, 'msg'=>'success', 'data'=>'生成账单成功'];
                return response()->json($res_data);
            } else {
                throw new Exception('生成账单失败');
            }
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$e->getMessage()]);
        }
    }

    // 获取供货商信息
    public function getChannelUnit(Request $request)
    {
        $search_data = $request->all();
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $list_data =  DB::table('channel_unit as chun')
            // ->leftjoin('channel_type as chty', 'chun.chun_chty_id', '=', 'chty.chty_id')
            ->where('chun_cid', $user_info->adm_cid)
            ->where('chun_superior_shop_id', $shop_id)
            ->where('chun_state', 1)
            ->where('chun_class', 1)
            // ->where('chty_system_type', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('chun_unit_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('chun_search_letter', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('chun_id', 'chun_chty_id', 'chun_unit_name', 'chun_name', 'chun_phone', 'chun_province', 'chun_city', 'chun_county', 'chun_address', 'chun_class', 'chun_payment_way', 'chun_delivertype', 'chun_invoicetype')
            ->orderBy('chun_id', 'desc')
            ->paginate($this->show_count);

        $find_data['current_page'] = $list_data->currentPage();  //当前页面页码
        $find_data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $find_data['total'] = $list_data->total();               //总数据个数
        $find_data['current_number'] = $this->show_count;       //一页显示多少个
        $find_data['data'] = $list_data->items();                //返回数据
        //结算方式对应关系
        $unit_data_list = ChannelUnit::getPaymentWayName(1,true);
        //交货方式对应关系
        $unit_deliver_type = ChannelUnit::getDeliverTypeName(true);
        //票据类型对应关系
        $unit_invoice_type = ChannelUnit::getInvoiceTypeName(true);

        //数据处理
        if (!empty($find_data['data'])) {
            foreach($find_data['data'] as $key => $value) {
                $find_data['data'][$key]->chun_payment_way_name = empty($value->chun_payment_way) ? '' : $unit_data_list[$value->chun_payment_way];
                $find_data['data'][$key]->chun_delivertype_name = empty($value->chun_delivertype) ? '' : $unit_deliver_type[$value->chun_delivertype];
                if($value->chun_invoicetype == ''){
                    $find_data['data'][$key]->chun_invoicetype_name = '';
                }else{
                    $find_data['data'][$key]->chun_invoicetype_name = $unit_invoice_type[$value->chun_invoicetype];
                }
            }
        }
        return response()->json(["code"=>200, 'msg'=>'success', 'data'=>$find_data]);
    }

    // 生成凭证【暂时用不到】
    public function purchaseVoucher(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        ignore_user_abort();
        set_time_limit(0);

        // 查询已经入库的采购单凭证
        $find_wain_data = DB::table('ware_inorder as wain')
            ->leftjoin('purchase_order as puor', 'puor.cg_number', '=', 'wain.cg_number')
            ->where('wain.company_id', $user_info->adm_cid)
            ->where('wain.rk_superior_shop_id', $shop_id)
            ->where('is_del', 1)
            ->whereIn('cg_state', [8, 11, 12])
            ->select('puor.cg_id', 'puor.cg_number', 'rk_id', 'wain.company_id', 'wain.rk_superior_shop_id', 'wain.rk_shop_id', 'rk_number', 'cg_state', 'cg_supplyunit', 'cg_creator', 'contact_name', 'contact_phone', 'rk_type', 'rk_amount', 'rk_creator', 'wain.create_time', 'puor.cg_amount')
            ->get()->toArray();

        DB::beginTransaction();

        foreach ($find_wain_data as $key => $value) {
            if ($value->rk_type == '1') {
                // 凭证单据报表
                // 判断凭证单据是否存在
                $vore_id = DB::table('voucher_receipts')
                    ->where('vore_cid', $user_info->adm_cid)
                    ->where('vore_shop_id', $user_info->adm_shop_id)
                    ->where('vore_ord_id', $value->cg_id)
                    ->where('vore_ord_number', $value->cg_number)
                    ->where('vore_order_type', 3)
                    ->where('vore_state', 1)
                    ->select('vore_id', 'vore_ord_id', 'vore_ord_number')
                    ->first();
                if (empty($vore_id)) {
                    $vore_data['vore_cid'] = $value->company_id; //公司id
                    $vore_data['vore_superior_shop_id'] = $value->rk_superior_shop_id; //总店id
                    $vore_data['vore_shop_id'] = $value->rk_shop_id; //门店id
                    $vore_data['vore_create_id'] = $value->rk_creator; //创建人
                    $vore_data['vore_order_type'] = 3; //单号类型1.订单2.工单3.采购单4.销售单
                    $vore_data['vore_ord_id'] = $value->cg_id; //采购id
                    $vore_data['vore_ord_number'] = $value->cg_number; //采购单号
                    if ($value->cg_amount < 0) {
                        $vore_data['vore_plus_minus'] = 2; //金额正负1正值2负值
                    } else {
                        $vore_data['vore_plus_minus'] = 1; //金额正负1正值2负值
                    }
                    $vore_data['vore_actual_price'] = abs($value->cg_amount); //结算金额
                    $vore_data['vore_type'] = 2; //单位类型1会员零售2客户单位3速电派单
                    $vore_data['vore_client_id'] = $value->cg_supplyunit; //客户单位/客户id
                    $vore_data['vore_create_time'] = $value->create_time;
                    // 根据客户单位id,查找客户名称
                    $channel_unit = DB::table('channel_unit')
                        ->where('chun_id', $value->cg_supplyunit)
                        ->value('chun_unit_name');
                    $vore_data['vore_channel_unit'] = $channel_unit ? $channel_unit : '';
                    $vore_id = DB::table('voucher_receipts')->insertGetId($vore_data);
                    // 凭证借贷表
                    $volo_data['volo_shop_id'] = $value->rk_shop_id;
                    $volo_data['volo_vore_id'] = $vore_id;
                    $volo_data['volo_type'] = 1; //类型1借方2贷方
                    $volo_data['volo_borrow_subject'] = '140501'; //借方科目
                    $volo_data['volo_borrow_subject_name'] = '库存商品'; //借方科目名称
                    $volo_data['volo_borrow_price'] = abs($value->cg_amount); //借方金额
                    $volo_data['volo_loan_subject'] = '220201'; //贷方科目
                    $volo_data['volo_loan_subject_name'] = '应付账款'; //贷方科目名称
                    $volo_data['volo_loan_price'] = abs($value->cg_amount); //贷方金额

                    $volo_data['volo_update_time'] = $value->create_time; //更新时间
                    $volo_id = DB::table('voucher_loan')->insert($volo_data);
                } else {
                    $vore_id = true;
                    $volo_id = true;
                }
            } elseif ($value->rk_type == '2') {
                // 凭证单据报表
                // 判断凭证单据是否存在
                $vore_id = DB::table('voucher_receipts')
                    ->where('vore_cid', $user_info->adm_cid)
                    ->where('vore_shop_id', $user_info->adm_shop_id)
                    ->where('vore_ord_id', $value->cg_id)
                    ->where('vore_ord_number', $value->cg_number)
                    ->where('vore_order_type', 5)
                    ->where('vore_state', 1)
                    ->select('vore_id', 'vore_ord_id', 'vore_ord_number')
                    ->first();
                if (empty($vore_id)) {
                    $vore_data['vore_cid'] = $value->company_id; //公司id
                    $vore_data['vore_superior_shop_id'] = $value->rk_superior_shop_id; //总店id
                    $vore_data['vore_shop_id'] = $value->rk_shop_id; //门店id
                    $vore_data['vore_create_id'] = $value->rk_creator; //创建人
                    $vore_data['vore_order_type'] = 5; //单号类型1.订单2.工单3.采购单4.销售单
                    $vore_data['vore_ord_id'] = $value->cg_id; //采购id
                    $vore_data['vore_ord_number'] = $value->cg_number; //采购单号
                    if ($value->rk_amount < 0) {
                        $vore_data['vore_plus_minus'] = 2; //金额正负1正值2负值
                    } else {
                        $vore_data['vore_plus_minus'] = 1; //金额正负1正值2负值
                    }
                    $vore_data['vore_actual_price'] = abs($value->rk_amount); //结算金额
                    $vore_data['vore_type'] = 2; //单位类型1会员零售2客户单位3速电派单
                    $vore_data['vore_client_id'] = $value->cg_supplyunit; //客户单位/客户id
                    $vore_data['vore_create_time'] = $value->create_time;
                    // 根据客户单位id,查找客户名称
                    $channel_unit = DB::table('channel_unit')
                        ->where('chun_id', $value->cg_supplyunit)
                        ->value('chun_unit_name');
                    $vore_data['vore_channel_unit'] = $channel_unit ? $channel_unit : '';
                    $vore_id = DB::table('voucher_receipts')->insertGetId($vore_data);
                    // 凭证借贷表
                    $volo_data['volo_shop_id'] = $value->rk_shop_id;
                    $volo_data['volo_vore_id'] = $vore_id;
                    $volo_data['volo_type'] = 1; //类型1借方2贷方
                    $volo_data['volo_borrow_subject'] = '220201'; //借方科目
                    $volo_data['volo_borrow_subject_name'] = '应付账款'; //借方科目名称
                    $volo_data['volo_borrow_price'] = abs($value->rk_amount); //借方金额
                    $volo_data['volo_loan_subject'] = '140501'; //贷方科目
                    $volo_data['volo_loan_subject_name'] = '库存商品'; //贷方科目名称
                    $volo_data['volo_loan_price'] = abs($value->rk_amount); //贷方金额

                    $volo_data['volo_update_time'] = $value->create_time; //更新时间
                    $volo_id = DB::table('voucher_loan')->insert($volo_data);
                } else {
                    $vore_id = true;
                    $volo_id = true;
                }
            }
        }
        if ($vore_id && $volo_id) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'生成凭证成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成凭证失败']);
        }
    }

    // 采购结算
    public function purchasement(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if ($request['type'] == '1') {
            $purchaseresult = DB::table('purchase_order as a')
                ->leftJoin('channel_unit as b', 'b.chun_id', '=', 'a.cg_supplyunit')
                ->where('cg_number', $request['cg_number'])
                ->whereIn('cg_settlementype', [2, 5])
                ->where('is_del', 1)
                ->select('cg_id', 'cg_amount', 'cg_yfmoney', 'cg_zdnumber', 'cg_moling', 'cg_supplyunit', 'cg_number', 'create_time', 'chun_unit_name', 'cg_userid', 'puor_supplyunit_type')
                ->first();
            DB::beginTransaction();
            if ($request['moling_type'] == '2') { //少付
                $request['cg_moling'] = 0 - $request['cg_moling'];
            }
            $purchase_data['cg_yfmoney'] = $purchaseresult->cg_yfmoney + $request['cg_yfmoney']; //结算金额
            $purchase_data['cg_moling'] = $purchaseresult->cg_moling + $request['cg_moling'];
            $request['cg_moling'] = abs($request['cg_moling']);
            if ($purchaseresult->cg_zdnumber == '') { //已付金额
                $purchase_data['cg_zdnumber'] = '0';
            } else {
                $purchase_data['cg_zdnumber'] = $purchaseresult->cg_zdnumber;
            }
            if ($purchase_data['cg_yfmoney'] + $purchase_data['cg_moling'] + $purchase_data['cg_zdnumber'] == $purchaseresult->cg_amount) {
                $purchase_data['cg_settlementype'] = '3'; //结算状态2待结算3已结算4待审核5部分结算
            } else {
                $purchase_data['cg_settlementype'] = '5'; //结算状态2待结算3已结算4待审核5部分结算
            }

            if ($request['moling_type'] == '1') {
                $jsje = $request['cg_yfmoney'] - $request['cg_moling'];
                $purchase_data['cg_settlementype'] = '3'; //结算状态2待结算3已结算4待审核5部分结算
            } elseif ($request['moling_type'] == '2') { //少付
                $jsje = $request['cg_yfmoney'] + $request['cg_moling'];
                $purchase_data['cg_settlementype'] = '3'; //结算状态2待结算3已结算4待审核5部分结算
            } else {
                $jsje = $request['cg_yfmoney'];
            }
            $purchase_save = DB::table('purchase_order')
                ->where('cg_number', $request['cg_number'])
                ->where('is_del', 1)
                ->update($purchase_data);
            // 添加结款明细记录
            if ($request['content'] == '') {
                $request['content'] = ' ';
            }
            $user_info->adm_id = $purchaseresult->cg_userid;
            if ($purchaseresult->puor_supplyunit_type == 2) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
                $purchaseresult->chun_unit_name = DB::table('shop')
                    ->where('shop_id', $purchaseresult->cg_supplyunit)
                    ->value('shop_store_name');
            }
            $acset_res = AccountingSettlement::add(
                $user_info,                 // [用户信息]
                24,                          // 单据类型24采购款到发货(预付款)
                $purchaseresult->cg_id,          // [与单据类型对应的id]
                $purchaseresult->cg_number, // [与单据类型对应的单号]
                2,                     // [买家类型1门店零售2来往单位]
                $purchaseresult->cg_supplyunit,       // [会员/客户id]
                $purchaseresult->chun_unit_name,     // [来往单位名称]
                $request['ac_id'],         // [会计科目id]
                2,                                // [类型1收入2支出]
                $request['cg_yfmoney'] * 100,                 // [实际金额](此次的实收金额)
                $jsje * 100,                 // [合计金额](此次的应收金额)
                0,                                // [欠收金额](此次结款后还应收金额)
                $request['cg_moling'] * 100,                                // [抹零金额]
                $request['content']                                // [备注]
            );
            // 生成应付
            $createBill = ReceivableBill::create(
                $user_info, //用户信息
                17, //类型：17.采购款到发货(预付款)
                0, //应收账款id
                $acset_res, //原始id(采购入库单id)
                $purchaseresult->cg_number, //应收账款单号/原始号(入库单号)
                2, //客户类型：1.门店零售 2.来往单位
                $purchaseresult->cg_supplyunit, //会员id/来往单位id
                $purchaseresult->chun_unit_name, //来往单位名称
                $jsje * 100, //结算金额
                '', //结款时间
                '', //会计科目id
                0, //实际金额
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                0, //已收金额
                '', //截止时间
                1, //金额正负1正   2负值
                20, //显示类型：20.采购款到发货（预付款）
                2, //是否合并代收：1是2否
                $purchaseresult->create_time,
                0 //技师是否收钱：0未选择1是2否
            );
            // 添加结款明细业务凭证
            // 根据银行账户id，查询对应的名称
            $find_acti_data = DB::table('account_title')
                ->where('acti_id', $request['ac_id'])
                ->where('acti_shop_id', $user_info->adm_shop_id)
                ->select('acti_subject_code', 'acti_course_title')
                ->first();
            // 判断是否有抹零金额
            if ($request['cg_moling'] == '0') {
                $volo_data[0]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                $volo_data[0]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                $volo_data[0]['acsl_type'] = 1; //类型1借方2贷方
                $volo_data[0]['acsl_borrow_subject'] = '220201'; //借方科目
                $volo_data[0]['acsl_borrow_subject_name'] = '应付账款'; //借方科目名称
                $volo_data[0]['acsl_borrow_price'] = $request['cg_yfmoney']; //借方金额
                $volo_data[0]['acsl_loan_subject'] = $find_acti_data->acti_subject_code; //贷方科目
                $volo_data[0]['acsl_loan_subject_name'] = $find_acti_data->acti_course_title; //贷方科目名称
                $volo_data[0]['acsl_loan_price'] = $request['cg_yfmoney']; //贷方金额
                $volo_data[1]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                $volo_data[1]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                $volo_data[1]['acsl_type'] = 1; //类型1借方2贷方
                $volo_data[1]['acsl_borrow_subject'] = ''; //借方科目
                $volo_data[1]['acsl_borrow_subject_name'] = ''; //借方科目名称
                $volo_data[1]['acsl_borrow_price'] = 0; //借方金额
                $volo_data[1]['acsl_loan_subject'] = ''; //贷方科目
                $volo_data[1]['acsl_loan_subject_name'] = ''; //贷方科目名称
                $volo_data[1]['acsl_loan_price'] = 0; //贷方金额
            } else {
                $volo_data[0]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                $volo_data[0]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                $volo_data[0]['acsl_type'] = 1; //类型1借方2贷方
                $volo_data[0]['acsl_borrow_subject'] = '220201'; //借方科目
                $volo_data[0]['acsl_borrow_subject_name'] = '应付账款'; //借方科目名称
                $volo_data[0]['acsl_borrow_price'] = $request['cg_yfmoney']; //借方金额
                $volo_data[0]['acsl_loan_subject'] = $find_acti_data->acti_subject_code; //贷方科目
                $volo_data[0]['acsl_loan_subject_name'] = $find_acti_data->acti_course_title; //贷方科目名称
                $volo_data[0]['acsl_loan_price'] = $jsje; //贷方金额
                $volo_data[1]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                $volo_data[1]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                $volo_data[1]['acsl_type'] = 1; //类型1借方2贷方
                $volo_data[1]['acsl_borrow_subject'] = '640101'; //借方科目
                $volo_data[1]['acsl_borrow_subject_name'] = '主营业务成本'; //借方科目名称
                $volo_data[1]['acsl_borrow_price'] = $request['cg_moling']; //借方金额
                $volo_data[1]['acsl_loan_subject'] = ''; //贷方科目
                $volo_data[1]['acsl_loan_subject_name'] = ''; //贷方科目名称
                $volo_data[1]['acsl_loan_price'] = 0; //贷方金额
            }
            $volo_id = DB::table('accounting_settlement_loan')->insert($volo_data);
            $request['acset_id'] = $acset_res;
            $request['acset_with_time'] = date('Y-m-d H:i:s');
            if ($user_info->shop_versions == 1) {
                $check_res = $this->check($request, $user_info);
                if ($check_res['code'] == 200) {
                    $check_result = true;
                } else {
                    $check_result = false;
                    return response()->json($check_res);
                }
            } else {
                $check_result = true;
            }
            $remark = $request['content'];
            DB::table('accounting_settlement')
                ->where('acset_id', $acset_res)
                ->update(['acset_remark' => $remark, 'acset_update_time' => date('Y-m-d H:i:s')]);
            if ($purchase_save && $check_result) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '采购管理', '采购单', $request['cg_number'] . '结算成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'结算成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结算失败']);
            }
        } else {
            $purchaseresult = DB::table('purchase_order as a')
                ->leftJoin('channel_unit as b', 'b.chun_id', '=', 'a.cg_supplyunit')
                ->where('cg_number', $request['cg_number'])
                ->where('is_del', 1)
                ->select('cg_id', 'cg_creator', 'cg_amount', 'cg_zdnumber', 'cg_yfmoney', 'cg_moling', 'cg_supplyunit', 'cg_number', 'create_time', 'chun_unit_name')
                ->first();
            $inorderresult = DB::table('accounting_settlement as acse')
                ->leftJoin('admin as adm', 'adm.adm_id', '=', 'acse.acset_adm_id')
                ->where('acset_original_number', $request['cg_number'])
                ->select('acset_id', 'acset_original_number', 'acset_inex_type', 'acset_state', 'acset_price', 'acset_remit_time as acset_with_time', 'acset_adm_id', 'adm_name')
                ->get()->toArray();
            foreach ($inorderresult as $k => $v) {
                if ($v->acset_state == '1') {
                    $inorderresult[$k]->adm_name = '--';
                }
            }
            if ($purchaseresult->cg_zdnumber == '') {
                $purchaseresult->cg_zdnumber = '0';
            }
            $purchaseresult->cg_wfmoney = $purchaseresult->cg_amount - $purchaseresult->cg_yfmoney + $purchaseresult->cg_moling - $purchaseresult->cg_zdnumber;
            if ($purchaseresult->cg_wfmoney < 0) {
                $purchaseresult->cg_wfmoney = 0;
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'cg_data'=>$purchaseresult, 'inorder_data'=>$inorderresult]);
        }
    }

    // 结款明细核对
    private function check($request, $user_info)
    {
        // 判断当前结款明细是否存在
        $settlement_data = DB::table('accounting_settlement')
            ->where('acset_id', $request['acset_id'])
            ->first(['acset_id', 'acset_original_number', 'acset_type', 'acset_state', 'acset_original_id', 'acset_inex_type', 'acset_actual_price', 'acset_zero_price', 'acset_acti_id', 'acset_payment_type', 'acset_merge_type', 'acset_price', 'acset_number', 'acset_zero_plus_minus', 'acset_price']);
        if (empty($settlement_data)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前结款明细不存在'];
        }
        if ($settlement_data->acset_state == 2) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前结款明细已核对'];
        }
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 结款明细核对需要做的有
        // 1. 更改状态、汇款时间、备注
        $update_data['acset_state'] = 2; //状态：1未核对2已核对
        $update_data['acset_affirm_time'] = date('Y-m-d H:i:s'); //确认时间
        $update_data['acset_remit_time'] = $request['acset_with_time']; //汇款时间
        $update_data['acset_remark'] = $request['acset_remark'] ? $request['acset_remark'] : ''; //备注
        $update_data['acset_update_time'] = date('Y-m-d H:i:s'); //更新时间
        $update_data['acset_adm_id'] = $user_info->adm_id;
        $acset_res = DB::table('accounting_settlement')
            ->where('acset_id', $request['acset_id'])
            ->update($update_data);
        // 是否操作科目数据1操作  2不操作
        $deduction = 1;
        // acset_payment_type 结款类型1.抹零 2.分期结款 3.预收款抵账4正常5收款6还款
        // acset_type 单据类型1订单结算2订单账单3工单账单4采购账单5销售账单6预收款7采购入库单现金8预付款9订单代收10采购入库单预付款11订单退款12工单代收13订单完成后结算14非实物开单15.订单冲单16.加盟店订单收款17.加盟店订单代收18.工单结算19.旧货回收20售后单结算21销售出库单22采购单23采购退货单24采购款到发货(预付款)
        if ($settlement_data->acset_payment_type == 3 || $settlement_data->acset_type == 10 || $settlement_data->acset_type == 21 || $settlement_data->acset_type == 22 || $settlement_data->acset_type == 23) {
            $deduction = 2;
        }
        // $deduction 1操作科目数据  2不操作科目数据
        if ($deduction == 1) {
            // 2. 将结款明细中的金额，在对应的科目中添加/减去，是以汇款时间为准
            $acti_res = AccountSubject::Subject(
                $user_info, //用户信息
                $settlement_data->acset_inex_type, //类型：1借(汇入)2贷(汇出)
                $settlement_data->acset_actual_price, //金额
                // $settlement_data->acset_acti_id,//科目id
                !empty($request['recr_acti_id']) ? $request['recr_acti_id'] : $settlement_data->acset_acti_id, //科目id
                $request['acset_with_time'] //汇款时间
            );
            if ($acti_res['code'] == 500) {
                return $acti_res;
            } else {
                $acti_res = true;
            }
        } else {
            $acti_res = true;
        }
        $recr_account_type = 0;
        switch ($settlement_data->acset_type) {
            case '4':
                $recr_type = 104; //采购账单对应，应付款，核销是在采购账单的结款中，没有放到结款明细中
                break;
            case '7': //采购入库单现金
                $recr_type = 107;
                break;
            case '10': //采购入库单预付款
                $recr_type = 110;
                break;
            case '22': //22采购单
                $recr_type = 15; //采购单
                $recr_account_type = 18; //采购单
                break;
            case '23': //23采购退货单
                $recr_type = 16; //采购退货单
                $recr_account_type = 19; //采购退货单
                break;
            case '24': //24采购款到发货(预付款)
                $recr_type = 17; //采购款到发货(预付款)
                $recr_account_type = 20; //采购款到发货(预付款)
                break;
            default:
                return ['code'=>500, 'msg'=>'error', 'data'=>'核对失败1'];
                break;
        }
        if ($recr_type == 15) { //采购单
            $recr_settle_price = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', $recr_type)
                ->where('recr_original_id', $settlement_data->acset_original_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->value('recr_settle_price');
            $recr_update['recr_acti_id'] = $request['recr_acti_id']; //会计科目id(银行账号)
            $recr_update['recr_yet_receipt'] = $recr_settle_price;
            $recr_update['recr_state'] = 2; //状态1未核销2已核销
            $recr_update['recr_update_time'] = date('Y-m-d H:i:s');
            $recr_res = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', $recr_type)
                ->where('recr_original_id', $settlement_data->acset_original_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->update($recr_update);
            $puor_data['cg_settlementype'] = 3; //结算状态2待结算3已结算4待审核5部分结算
            $puor_data['edit_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('purchase_order')
                ->where('company_id', $user_info->adm_cid)
                ->where('cg_superior_shop_id', $shop_id)
                ->where('cg_id', $settlement_data->acset_original_id)
                ->where('cg_number', $settlement_data->acset_original_number)
                ->update($puor_data);
            // 2. 将结款明细中的金额，在对应的科目中添加/减去，是以汇款时间为准
            $acti_res = AccountSubject::Subject(
                $user_info, //用户信息
                $settlement_data->acset_inex_type, //类型：1借(汇入)2贷(汇出)
                $recr_settle_price, //金额
                $request['recr_acti_id'], //科目id
                $request['acset_with_time'] //汇款时间
            );
            if ($acti_res['code'] == 500) {
                return $acti_res;
            } else {
                $acti_res = true;
            }
            $acset_data['acset_acti_id'] = $request['recr_acti_id'];
            $acset_update_res = DB::table('accounting_settlement')
                ->where('acset_id', $request['acset_id'])
                ->update($acset_data);
        } elseif ($recr_type == 16) { //采购退货单
            $recr_settle_price = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', $recr_type)
                ->where('recr_original_id', $settlement_data->acset_original_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->value('recr_settle_price');
            $recr_update['recr_yet_receipt'] = $recr_settle_price;
            $recr_update['recr_state'] = 2; //状态1未核销2已核销
            $recr_update['recr_update_time'] = date('Y-m-d H:i:s');
            $recr_res = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', $recr_type)
                ->where('recr_original_id', $settlement_data->acset_original_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->update($recr_update);
            $puor_data['cg_settlementype'] = 3; //结算状态2待结算3已结算4待审核5部分结算
            $puor_data['edit_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('purchase_order')
                ->where('company_id', $user_info->adm_cid)
                ->where('cg_superior_shop_id', $shop_id)
                ->where('cg_id', $settlement_data->acset_original_id)
                ->where('cg_number', $settlement_data->acset_original_number)
                ->update($puor_data);
            $acset_data['acset_acti_id'] = $request['recr_acti_id'];
            $acset_update_res = DB::table('accounting_settlement')
                ->where('acset_id', $request['acset_id'])
                ->update($acset_data);
            // 2. 将结款明细中的金额，在对应的科目中添加/减去，是以汇款时间为准
            $acti_res = AccountSubject::Subject(
                $user_info, //用户信息
                $settlement_data->acset_inex_type, //类型：1借(汇入)2贷(汇出)
                $recr_settle_price, //金额
                $request['recr_acti_id'], //科目id
                $request['acset_with_time'] //汇款时间
            );
            if ($acti_res['code'] == 500) {
                return $acti_res;
            } else {
                $acti_res = true;
            }
        } elseif ($recr_type == 17) { //采购单款到发货(预付款)
            $stase = "1";
            // 查找采购单
            $purchaseresult = DB::table('purchase_order')
                ->where('cg_number', $settlement_data->acset_original_number)
                ->select('cg_id', 'cg_settlementype', 'cg_amount', 'cg_yfmoney', 'cg_moling', 'cg_state')
                ->first();
            if ($purchaseresult->cg_state == '17') {
                $inorderresult = DB::table('accounting_settlement')
                    ->where('acset_original_number', $settlement_data->acset_original_number)
                    ->where('acset_state', '1')
                    ->select('acset_id')
                    ->first();
                if (!$inorderresult) {
                    $stase = "2";
                }
            }
            if ($purchaseresult->cg_state == '11' || $purchaseresult->cg_state == '12') {
                if ($purchaseresult->cg_settlementype == '3') { //结算状态2待结算3已结算4待审核5部分结算
                    $inorderresult = DB::table('accounting_settlement')
                        ->where('acset_original_number', $settlement_data->acset_original_number)
                        ->where('acset_state', '1')
                        ->select('acset_id')
                        ->first();
                    if (!$inorderresult) {
                        $stase = "2";
                    }
                }
            }

            // 更新本次应付记录
            $recr_resdata = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_original_id', $settlement_data->acset_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->select('recr_settle_price')->first();
            $edit_data['recr_acti_id'] = $request['recr_acti_id'];
            $edit_data['recr_settle_id'] = $user_info->adm_id;
            //$edit_data['recr_yet_receipt'] = $recr_resdata->recr_settle_price;
            $edit_data['recr_state'] = 4;
            $edit_data['recr_update_time'] = date('Y-m-d H:i:s');
            $edit_data['recr_settle_time'] = date('Y-m-d H:i:s');
            $recr_ressave = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_original_id', $settlement_data->acset_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->update($edit_data);
            unset($edit_data);
            // 更新该采购单所有应付记录
            if ($stase == '2') {
                $recr_dat = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $shop_id)
                    //->where('recr_original_id', $v['rk_id'])
                    //->where('recr_id', $recr_dat->recr_id)
                    ->where('recr_original_number', $settlement_data->acset_original_number)
                    ->select('recr_settle_price', 'recr_id')->get();
                foreach ($recr_dat  as $k => $v) {
                    $editrk_data['recr_yet_receipt'] = $v->recr_settle_price;
                    $editrk_data['recr_state'] = 2;
                    $editrk_data['recr_acti_id'] = $request['recr_acti_id'];
                    $editrk_data['recr_settle_id'] = $user_info->adm_id;
                    $editrk_data['recr_update_time'] = date('Y-m-d H:i:s');
                    $editrk_data['recr_settle_time'] = date('Y-m-d H:i:s');
                    $recr_ress = DB::table('receivable_credit')
                        ->where('recr_cid', $user_info->adm_cid)
                        ->where('recr_shop_superior_id', $shop_id)
                        ->where('recr_id', $v->recr_id)
                        ->where('recr_original_number', $settlement_data->acset_original_number)
                        ->update($editrk_data);
                }
            }
            //$acset_data['acset_with_time'] = $request['acset_with_time'];
            $acset_data['acset_acti_id'] = $request['recr_acti_id'];
            $acset_update_res = DB::table('accounting_settlement')
                ->where('acset_id', $request['acset_id'])
                ->update($acset_data);
            $recr_res = true;
            // 生成付款单记录
            $add_data['acsd_acset_id'] = $request['acset_id'];
            $add_data['acsd_number'] = 'FK' . rand(100, 999) . time() . rand(10000, 99999);
            $add_data['acsd_type'] = 1; //类型1采购单款到发货(预付款)
            $add_data['acsd_adm_id'] = $user_info->adm_id; //创建人id
            $add_data['acsd_price'] = $request['recr_yet_receipt'] * 100; //付款金额
            $acsd_id = DB::table('accounting_settlement_details')->insert($add_data);
        } elseif (in_array($recr_type, [104, 107, 110])) {
            // 采购账单
            // 采购账单类型的，要判断账单是否全部结款，全部结款之后才可以把对应账单的应付款改为核销状态
            // 判断结款明细表中是否还有未核对的账单结款明细
            // 如果还有，说明当前的账单还有未核对的结款明细，不用核销应付账款中的数据
            $find_account = DB::table('accounting_settlement')
                ->where('acset_type', $settlement_data->acset_type)
                ->where('acset_original_id', $settlement_data->acset_original_id)
                ->where('acset_state', 1)
                ->first(['acset_id']);
            if ($find_account) {
                $recr_res = true;
            } else {
                switch ($recr_type) {
                    case '104': //采购账单
                        $acpa_type = 15; //1.预付款 2.采购账单 3.现结 4.采购入库单
                        break;
                    case '107': //采购入库单现结
                        $acpa_type = 3; //1.预付款 2.采购账单 3.现结 4.采购入库单
                        break;
                    case '110': //采购入库单预付款
                        $acpa_type = 4; //1.预付款 2.采购账单 3.现结 4.采购入库单
                        break;
                }
                // 3.2.2 如果没有，说明账单的结款明细都已核对
                // 需要去应付账款表查询当前账单是否都已结款，
                // 如果应付账款都已结款，可以把账单相关的应付账款改为已核销状态
                // 3.2.3 当前账单的最后一条应付账款就是账单的最后的结款记录
                // 如果最后一条的结款记录中的 已收金额+抹零金额=结算金额，说明已全部结款，可以改为核销状态
                // 否则就没有全部结款，不能改为核销状态
                // 查询应付总金额
                $recr_data = DB::table('receivable_credit')
                    ->where('recr_type', '15')
                    ->where('recr_account_type', '22')
                    ->where('recr_original_id', $settlement_data->acset_original_id)
                    ->select('recr_settle_price', 'recr_id', 'recr_original_number')
                    ->first();
                // 查询已付总金额
                $accdata = DB::table('accounting_settlement')
                    ->where('acset_original_number', $recr_data->recr_original_number)
                    ->where('acset_state', '2')
                    ->select('acset_price')
                    ->get();
                $acset_price = '0';
                foreach ($accdata as $k => $v) {
                    $acset_price = $acset_price + $v->acset_price;
                }
                if ($acset_price == $recr_data->recr_settle_price) {
                    $edit_data['recr_state'] = 2; //状态：1.未核销 2.已核销
                    $edit_data['recr_update_time'] = date('Y-m-d H:i:s');
                    $edit_data['recr_settle_time'] = date('Y-m-d H:i:s');
                    $edit_data['recr_yet_receipt'] = $recr_data->recr_settle_price;
                    $recr_res = DB::table('receivable_credit')
                        ->where(function ($query) use ($acpa_type, $settlement_data) {
                            $query->where('recr_type', $acpa_type)
                                ->where('recr_account_type', '22')
                                ->where('recr_original_id', $settlement_data->acset_original_id);
                        }) //账单相关的应收账款
                        ->update($edit_data);
                } else {
                    $recr_res = true;
                }
            }
        }
        if ($acset_res && $acti_res && $recr_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'核对成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'核对失败'];
        }
    }

    // 一键入库
    public function akeyProcurement(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->addShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 添加采购单前
        if ($request['type'] == 1) {
            $getdata_res = PurchaseOrder::getPurchaseData($user_info, $shop_id, $request);
            return response()->json($getdata_res);
        }

        $allData = $request->all();
        // 去除数据中所包含的换行符等特殊符号
        $allData = RemoveLineFeed($allData);

        $rk_number = 'RK' . rand(10, 99) . date('mdHis') . rand(100000, 999999); //单号

        // 验证采购单号是否重复
        $cg_id = DB::table('purchase_order')
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where('cg_number', $allData['cg_number'])
            ->value('cg_id');
        if ($cg_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'采购单号重复']);
        }
        if (!is_array($request['goods'])) {
            $goods_data = json_decode($request['goods'], true); //入库商品数据
        } else {
            $goods_data = $request['goods']; //入库商品数据
        }
        if (empty($goods_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择采购入库商品!']);
        }

        $now_time = date('Y-m-d H:i:s');
        // 给采购表的数据赋值
        $cg_data = [];
        // 基本信息
        $cg_data['company_id'] = $user_info->adm_cid;
        $cg_data['cg_userid']  = $user_info->adm_id;
        $cg_data['cg_creator'] = $user_info->adm_name;
        $cg_data['cg_superior_shop_id'] = $shop_id;
        $cg_data['cg_shop_id'] = $user_info->adm_shop_id;
        $cg_data['cg_number']      = $allData['cg_number']; //采购单号
        $cg_data['contract_number'] = $allData['contract_number']; //合同单号
        $cg_data['cg_purchasetime'] = $allData['cg_purchasetime']; //采购日期
        $cg_data['business_type']  = $allData['business_type']; //业务类型1普通采购2样品采购
        $cg_data['cg_wareid']      = $allData['cg_wareid']; //仓库id
        $cg_data['cg_waon_class']  = $allData['cg_waon_class']; //仓库类别1货物仓2非货物仓3旧货仓4临时仓
        $cg_data['cg_remark']      = $allData['cg_remark']; //采购依据(备注)
        // 供货方
        $cg_data['cg_supplyunit']  = $allData['cg_supplyunit']; //供货单位
        $cg_data['contact_name']   = $allData['contact_name']; //联系人
        $cg_data['contact_phone']  = $allData['contact_phone']; //联系电话
        // 结算信息
        $cg_data['cg_paytype'] = 1; //是否账单结算1否2是
        $cg_data['cg_paymentype']  = $allData['cg_paymentype']; //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天
        if ($allData['cg_paymentype'] == '3') {
            $cg_data['cg_yfmoney'] = $allData['cg_yfmoney']; //预付金额
        } else {
            $cg_data['cg_yfmoney'] = 0; //预付金额
        }
        $cg_data['cg_delivertype'] = $allData['cg_delivertype']; //交货方式1送货上门2自提
        $cg_data['cg_invoicetype'] = $allData['cg_invoicetype']; //票据类型1普通发票2专用发票
        $cg_data['cg_amount']      = $allData['cg_amount']; //采购金额
        $cg_data['cg_settlementype']   = 2; //结算状态2待结算3已结算4待审核5部分结算
        $cg_data['need_toexamine'] = 1;
        $cg_data['cg_state']   = 12; //采购单状态：1.审核中 2.财务审核 3.驳回编辑5.未入库 6.未出库 8.部分入库 11.完成  ( 9.待结算10.待审核)  12.确认完成  14.已封账  15.申请终止17.终止 18.代发采购19.修正中
        $cg_data['cg_type'] = 1; //入库单
        $cg_data['cg_types'] = 1; //普通采购
        $cg_data['puor_supplyunit_type']  = $allData['puor_supplyunit_type']; //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
        $cg_data['create_time']  = $now_time; //创建时间

        $total_value = 0;
        foreach ($goods_data as $key => $val) {
            $goods_data[$key]['num'] = (int)$val['goods_num'];
            $goods_data[$key]['wafr_id'] = (int)$val['goods_num'];
            $goods_data[$key]['estimate_time'] = date('Y-m-d H:i:s');
            $val['num'] = $val['goods_num'];
            $total_value = $total_value + ((int)$val['num'] * (float)$val['univalence']);
        }

        DB::beginTransaction();

        // 商品信息
        $goods_name = '';
        $storage_goods = [];
        $sell_count = 0; //出库总数量
        // 处理商品数据
        foreach ($goods_data as $key => $val) {
            // 采购
            $temp = [];
            $temp['goods_id']     = $val['goods_id'];
            $temp['tax_rate']     = $val['tax_rate'];
            $temp['currency']     = $val['currency'];
            $temp['company_unit'] = empty($val['company_unit']) ? '' : $val['company_unit'];
            $temp['univalence']   = (float) $val['univalence'];
            $temp['money']        = (float) $val['money'];
            $temp['goods_num']    = (int) $val['num'];
            $temp['cg_goodsnum']  = $temp['goods_num'];
            // 提前将每个商品的分算平均后的价格计算完毕；  如果采购单价或采购总价为0 则赋值为0
            if ($cg_data['cg_amount'] <= '0' || $temp['univalence'] <= '0') {
                $temp['old_univalence'] = 0;
            } else {
                $temp['old_univalence'] = round($cg_data['cg_amount'] / $total_value * $temp['univalence'], 2);
            }

            if ($temp['goods_num'] < 1) {
                continue;
            }
            $temp['relation_number'] = $cg_data['cg_number']; //系统编号(入库单号,采购单号,调拨单号)
            $temp['storehouse']     = $cg_data['cg_wareid']; //仓库id
            $temp['ruku_num']       = 0; //入库数量
            $temp['goods_type']     = $val['goo_type']; //商品类型1正常商品2赠送商品3活动商品4旧货商品
            $temp['creator']        = $user_info->adm_name;
            $temp['create_time'] = $now_time;
            $temp['company_id'] = $user_info->adm_cid;
            $temp['stgo_superior_shop_id'] = $shop_id;
            $temp['stgo_shop_id'] = $user_info->adm_shop_id;

            // 查询商品名称和检索编码
            $goods_arr = Db::table('goods')
                ->where('goo_id', $val['goods_id'])
                ->select('goo_name', 'goo_goods_encode', 'goo_class')
                ->first();
            if ($goods_arr->goo_class == 1) { //类型：1自营商品2系统商品
                // 查询商品附属表
                $goaf_another_name = DB::table('goods_affiliate')
                    ->where('goaf_goo_id', $val['goods_id'])
                    ->where('goaf_shop_id', $user_info->adm_shop_id)
                    ->value('goaf_another_name');
                if (!empty($goaf_another_name)) {
                    $goods_arr->goo_name = $goaf_another_name;
                }
            } else {
                // 查询系统商品属性表
                $gosa_another_name = DB::table('goods_system_affiliate')
                    ->where('gosa_goo_id', $val['goods_id'])
                    ->where('gosa_shop_id', $user_info->adm_shop_id)
                    ->value('gosa_another_name');
                if (!empty($gosa_another_name)) {
                    $goods_arr->goo_name = $gosa_another_name;
                }
            }
            if (!$goods_arr) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'未知的商品,请重新填写采购单']);
            }
            if ($goods_arr->goo_class == '2') {
                $sell_count += $val['num']; //出库总数量
            }

            $temp['goods_number'] = $goods_arr->goo_goods_encode;
            $temp['goods_name']  = $goods_arr->goo_name;
            $goods_name = $goods_name . ',' . $goods_arr->goo_name . $goods_arr->goo_goods_encode;
            $storage_goods[] = $temp;
            $goods_id[] = $val['goods_id'];
        }
        
        // 采购
        $puor_id = DB::table('purchase_order')->insertGetId($cg_data);
        $cg_data['cg_id'] = $puor_id;
        $stgo_id = DB::table('storage_goods')->insert($storage_goods);

        $cg_data['goods_name'] = $goods_name;
        $cg_data = json_decode(json_encode($cg_data), true);

        // 查询采购单的商品数数据
        $storage_goods = DB::table('storage_goods')
            ->where('relation_number', $request['cg_number'])
            ->select('goods_id', 'goods_number', 'storehouse', 'goods_name', 'cg_goodsnum', 'goods_num', 'univalence', 'ruku_num', 'company_id', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'old_univalence', 'stgo_stop')
            ->get()->toArray();
        $storage_goods = json_decode(json_encode($storage_goods), true); //将对象转换为数组
        $storage_goods = array_column($storage_goods, null, 'goods_id'); //商品id当做数组键值
        $goods_id = array_unique(array_column($goods_data, 'goods_id')); //前端提交入库数据的商品id

        $warehousing_retrun = WareInorder::warehousing(
            $user_info, //用户信息
            $shop_id, //门店id
            $request->all(), //用户信息
            $goods_data, //提交的商品数据
            $storage_goods, //查询采购单商品信息
            $goods_id, //前端提交入库数据的商品id
            $cg_data, //查询的采购单信息
            $rk_number //入库单号
        );

        // 记录日志
        $log_data['user_info'] = $user_info;
        $log_data['rk_number'] = $request['rk_number'];
        $log_data['rk_type'] = '采购入库';
        $log_data['request'] = $request->all();
        $log_data['warehousing_retrun'] = $warehousing_retrun;
        Common::write_record_log($log_data, 'pc/AppletWareInorderController.txt', 'warehousing');

        if ($puor_id && $stgo_id && $warehousing_retrun['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购管理', '一键采购', $cg_data['cg_number'] . '成功');
            if ($request['rk_remark'] != '') {
                Common::addNote($user_info, $shop_id, $rk_number, $request['rk_remark'], '一键采购');
            }
            return response()->json($warehousing_retrun);
        } else {
            DB::rollBack();
            return response()->json($warehousing_retrun);
        }
    }

    // 搜索商品
    public function searchGoods(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->searchGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $adm_cid = $user_info->adm_cid;
        if ($request['puor_supplyunit_type'] == 1) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
            $post['string'] = 'goo_';
            $post['user_info'] = $user_info;
            $type = 3;
            $where_data = whereFunction($post,$type);
            if (!empty($request['ware_id'])) {
                $search_data['goo_id'] = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $request['ware_id'])
                    ->where(function ($query) use ($request) {
                        if (!empty($request['waon_class'])) {
                            $query->where('wago_class', $request['waon_class']);
                        }
                    })
                    ->pluck('wago_goo_id')->toArray();
            }
            $search_data = $request->all();
            if (!empty($request['waon_class'])) {
                if ($request['waon_class'] == 1) {
                    $goo_type = 1;
                } elseif ($request['waon_class'] == 2) {
                    $goo_type = 2;
                } elseif ($request['waon_class'] == 3) {
                    $goo_type = 4;
                } else {
                    $goo_type = 1;
                }
            } else {
                $goo_type = isset($request['goo_type']) ? $request['goo_type'] : 1; //商品类型 1正常商品2赠品商品3活动商品4旧货商品
            }
            
            $list_data = DB::table('goods')
                ->where(function ($query) use ($adm_cid) {
                    $query->where('goo_cid', $adm_cid);
                })
                ->whereIn($where_data['string'], $where_data['shop_id'])
                ->where('goo_type', $goo_type)
                ->where('goo_delete', 1)
                ->where('goo_state', 1)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_name'])) {
                        $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                            ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_bra_id'])) {
                        $query->where('goo_bra_id', $search_data['goo_bra_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_id'])) {
                        $query->where('goo_id', $search_data['goo_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_unta_id'])) {
                        $query->where('goo_unta_id', $search_data['goo_unta_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_cate_id'])) {
                        $query->where('goo_cate_id', $search_data['goo_cate_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_class'])) {
                        $query->where('goo_class', $search_data['goo_class']);
                    }
                }) //类型：1自营商品2系统商品
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_brse_id'])) {
                        $query->where('goo_brse_id', $search_data['goo_brse_id']);
                    }
                }) //品牌系列id
                ->select('goo_class', 'goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_price', 'goo_purchase_price', 'goo_unit', 'goo_brse_id', 'goo_bra_name', 'goo_unta_id', 'goo_unit_conversion')
                //->orderBy('goo_goods_encode', 'desc')
                ->orderBy('goo_id', 'desc')
                ->paginate($this->show_count);

            $data = $list_data->items();
            $data = json_decode(json_encode($data), true);
            $goo_id = array_column($data, 'goo_id');
            // 查询入库仓库的商品的预警值
            $wago_data = DB::table('warehouse_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->where('wago_class', $request['waon_class'])
                ->whereIn('wago_goo_id', $goo_id)
                ->pluck('wago_min_warn', 'wago_goo_id')
                ->toArray();
            foreach ($data as $key => $value) {
                if (isset($wago_data[$value['goo_id']])) { //仓库商品预警值
                    $data[$key]['wago_min_warn'] = $wago_data[$value['goo_id']];
                } else {
                    $data[$key]['wago_min_warn'] = 0;
                }
                unset($data[$key]['goo_class']);
            }
            $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
            $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $data_info['total'] = $list_data->total();               //总数据个数
            $data_info['current_number'] = $this->show_count;       //一页显示多少个
            $data_info['data'] = $data;                //返回数据
            $data_info['brse_data'] = []; //品牌系列数据
            if ($data_info['data']) {
                // 查询品牌系列数据
                $goo_brse_id = array_filter(array_unique(array_column($data_info['data'], 'goo_brse_id')));
                if ($goo_brse_id) {
                    $data_info['brse_data'] = DB::table('brand_serie')
                        ->whereIn('brse_id', $goo_brse_id)
                        ->select('brse_id', 'brse_name')
                        ->get();
                }
            }
        } elseif ($request['puor_supplyunit_type'] == 2) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
            $parent_shop_id = DB::table('shop')
                ->where('shop_id', $shop_id)
                ->value('shop_parent_id');
            $adm_cid = DB::table('shop')->where('shop_id', $parent_shop_id)->value('shop_cid');

            $search_data = $request->all();
            $search_data['goo_class'] = 2; //系统商品
            if (!empty($request['waon_class'])) {
                if ($request['waon_class'] == 1) {
                    $goo_type = 1;
                } elseif ($request['waon_class'] == 2) {
                    $goo_type = 2;
                } elseif ($request['waon_class'] == 3) {
                    $goo_type = 4;
                } else {
                    $goo_type = 1;
                }
            } else {
                $goo_type = isset($request['goo_type']) ? $request['goo_type'] : 1;
            }
            $shop_state = true;
            if (in_array($parent_shop_id, config('apisystem.NO_SHOPID'))) {
                $shop_state = false;
            }
            $list_data = DB::table('goods')
                ->where(function ($query) use ($adm_cid, $shop_state) {
                    if ($shop_state) {
                        $query->where('goo_cid', 0)
                            ->orwhere('goo_cid', $adm_cid);
                    } else {
                        $query->where('goo_cid', $adm_cid);
                    }
                })
                ->where(function ($query) use ($parent_shop_id, $shop_state) {
                    if ($shop_state) {
                        $query->where('goo_shop_id', 0)
                            ->orwhere('goo_shop_id', $parent_shop_id);
                    } else {
                        $query->where('goo_shop_id', $parent_shop_id);
                    }
                })
                ->where('goo_type', $goo_type)
                ->where('goo_delete', 1)
                ->where('goo_state', 1)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_name'])) {
                        $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                            ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_bra_id'])) {
                        $query->where('goo_bra_id', $search_data['goo_bra_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_id'])) {
                        $query->where('goo_id', $search_data['goo_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_unta_id'])) {
                        $query->where('goo_unta_id', $search_data['goo_unta_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_cate_id'])) {
                        $query->where('goo_cate_id', $search_data['goo_cate_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_class'])) {
                        $query->where('goo_class', $search_data['goo_class']);
                    }
                }) //类型：1自营商品2系统商品
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_brse_id'])) {
                        $query->where('goo_brse_id', $search_data['goo_brse_id']);
                    }
                }) //品牌系列id
                ->select('goo_class', 'goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_price', 'goo_wholesale_price as goo_purchase_price', 'goo_unit', 'goo_brse_id', 'goo_bra_name')
                ->orderBy('goo_goods_encode', 'desc')
                ->paginate($this->show_count);

            $data = $list_data->items();
            $data = json_decode(json_encode($data), true);
            $goo_id = array_column($data, 'goo_id');
            // 查询商品附属表信息
            $goaf_data = DB::table('goods_affiliate')
                ->where('goaf_shop_id', $parent_shop_id)
                ->whereIn('goaf_goo_id', $goo_id)
                ->pluck('goaf_another_name', 'goaf_goo_id')
                ->toArray();
            // 查询入库仓库的商品的预警值
            $wago_data = DB::table('warehouse_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->where('wago_class', $request['waon_class'])
                ->whereIn('wago_goo_id', $goo_id)
                ->pluck('wago_min_warn', 'wago_goo_id')
                ->toArray();
            foreach ($data as $key => $value) {
                if ($value['goo_class'] == 2) {
                    $gosa_where['gosa_shop_id'] = $parent_shop_id;
                    $gosa_where['gosa_goo_id'] = $value['goo_id'];
                    $gosa_res = DB::table('goods_system_affiliate')
                        ->where($gosa_where)
                        ->select('gosa_purchase_price', 'gosa_another_name', 'gosa_wholesale_price')
                        ->first();
                    if ($gosa_res) {
                        $data[$key]['goo_purchase_price'] = $gosa_res->gosa_wholesale_price;
                        if (!empty($gosa_res->gosa_another_name)) {
                            $data[$key]['goo_name'] = $gosa_res->gosa_another_name;
                        }
                    } else {
                        $data[$key]['goo_purchase_price'] = 0;
                    }
                }
                if (isset($goaf_data[$value['goo_id']]) && !empty($goaf_data[$value['goo_id']])) { // 商品别名
                    $data[$key]['goo_name'] = $goaf_data[$value['goo_id']];
                }
                if (isset($wago_data[$value['goo_id']])) { //仓库商品预警值
                    $data[$key]['wago_min_warn'] = $wago_data[$value['goo_id']];
                } else {
                    $data[$key]['wago_min_warn'] = 0;
                }
                unset($data[$key]['goo_class']);
            }
            $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
            $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $data_info['total'] = $list_data->total();               //总数据个数
            $data_info['current_number'] = $this->show_count;       //一页显示多少个
            $data_info['data'] = $data;                //返回数据
            $data_info['brse_data'] = []; //品牌系列数据
            if ($data_info['data']) {
                // 查询品牌系列数据
                $goo_brse_id = array_filter(array_unique(array_column($data_info['data'], 'goo_brse_id')));
                if ($goo_brse_id) {
                    $data_info['brse_data'] = DB::table('brand_serie')
                        ->whereIn('brse_id', $goo_brse_id)
                        ->select('brse_id', 'brse_name')
                        ->get();
                }
            }
        } elseif ($request['puor_supplyunit_type'] == 3) { //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

            if (!empty($request['ware_id'])) {
                $search_data['goo_id'] = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $request['ware_id'])
                    ->where(function ($query) use ($request) {
                        if (!empty($request['waon_class'])) {
                            $query->where('wago_class', $request['waon_class']);
                        }
                    })
                    ->pluck('wago_goo_id')->toArray();
            }
            $search_data = $request->all();
            if (!empty($request['waon_class'])) {
                if ($request['waon_class'] == 1) {
                    $goo_type = 1;
                } elseif ($request['waon_class'] == 2) {
                    $goo_type = 2;
                } elseif ($request['waon_class'] == 3) {
                    $goo_type = 4;
                } else {
                    $goo_type = 1;
                }
            } else {
                $goo_type = isset($request['goo_type']) ? $request['goo_type'] : 1; //商品类型 1正常商品2赠品商品3活动商品4旧货商品
            }
            $shop_state = true;
            if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
                $shop_state = false;
            }
            $list_data = DB::table('goods')
                ->where(function ($query) use ($adm_cid, $shop_state) {
                    if ($shop_state) {
                        $query->where('goo_cid', 0)
                            ->orwhere('goo_cid', $adm_cid);
                    } else {
                        $query->where('goo_cid', $adm_cid);
                    }
                })
                ->where(function ($query) use ($shop_id, $shop_state) {
                    if ($shop_state) {
                        $query->where('goo_shop_id', 0)
                            ->orwhere('goo_shop_id', $shop_id);
                    } else {
                        $query->where('goo_shop_id', $shop_id);
                    }
                })
                ->where('goo_type', $goo_type)
                ->where('goo_delete', 1)
                ->where('goo_state', 1)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_name'])) {
                        $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                            ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_bra_id'])) {
                        $query->where('goo_bra_id', $search_data['goo_bra_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_id'])) {
                        $query->where('goo_id', $search_data['goo_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_unta_id'])) {
                        $query->where('goo_unta_id', $search_data['goo_unta_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_cate_id'])) {
                        $query->where('goo_cate_id', $search_data['goo_cate_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_class'])) {
                        $query->where('goo_class', $search_data['goo_class']);
                    }
                }) //类型：1自营商品2系统商品
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_brse_id'])) {
                        $query->where('goo_brse_id', $search_data['goo_brse_id']);
                    }
                }) //品牌系列id
                ->select('goo_class', 'goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_price', 'goo_wholesale_price as goo_purchase_price', 'goo_unit', 'goo_brse_id', 'goo_bra_name')
                ->orderBy('goo_goods_encode', 'desc')
                ->paginate($this->show_count);

            $data = $list_data->items();
            $data = json_decode(json_encode($data), true);
            $goo_id = array_column($data, 'goo_id');
            // 查询商品附属表信息
            $goaf_data = DB::table('goods_affiliate')
                ->whereIn('goaf_goo_id', $goo_id)
                ->pluck('goaf_goo_id')
                ->toArray();
            // 查询入库仓库的商品的预警值
            $wago_data = DB::table('warehouse_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->where('wago_class', $request['waon_class'])
                ->whereIn('wago_goo_id', $goo_id)
                ->pluck('wago_min_warn', 'wago_goo_id')
                ->toArray();
            foreach ($data as $key => $value) {
                $goo_price = DB::connection('mysql_scm')->table('goods')
                    ->where('goo_goods_encode', $value['goo_goods_encode'])
                    ->select('goo_goods_encode', 'goo_wholesale_price', 'goo_purchase_price')
                    ->first();
                $data[$key]['goo_wholesale_price'] = $goo_price->goo_wholesale_price;
                $data[$key]['goo_purchase_price'] = $goo_price->goo_wholesale_price;
                // if ($value['goo_class'] == 2) {
                //     $data[$key]['goo_purchase_price'] = 0;
                // }
                // if (isset($goaf_data[$value['goo_id']]) && !empty($goaf_data[$value['goo_id']])) {// 商品别名
                //     $data[$key]['goo_name'] = $goaf_data[$value['goo_id']];
                // }
                if (isset($wago_data[$value['goo_id']])) { //仓库商品预警值
                    $data[$key]['wago_min_warn'] = $wago_data[$value['goo_id']];
                } else {
                    $data[$key]['wago_min_warn'] = 0;
                }
                unset($data[$key]['goo_class']);
            }
            $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
            $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $data_info['total'] = $list_data->total();               //总数据个数
            $data_info['current_number'] = $this->show_count;       //一页显示多少个
            $data_info['data'] = $data;                //返回数据
            $data_info['brse_data'] = []; //品牌系列数据
            if ($data_info['data']) {
                // 查询品牌系列数据
                $goo_brse_id = array_filter(array_unique(array_column($data_info['data'], 'goo_brse_id')));
                if ($goo_brse_id) {
                    $data_info['brse_data'] = DB::table('brand_serie')
                        ->whereIn('brse_id', $goo_brse_id)
                        ->select('brse_id', 'brse_name')
                        ->get();
                }
            }
        }

        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 导入-下载模板
    public function downTemplate(Request $request)
    {
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => 'storage/Template/PurchaseGoods.xlsx']);
    }

    /**
     * 设置采购单流程
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-03-13
     * @param  Request          $request [description]
     */
    public function setPurchaseOrder(Request $request) {
        // 验证数据
        $verify_data = new VerifyPurchaseOrderController;
        $error_message = $verify_data->setPurchaseOrderValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $find_set = DB::table('purchase_order_set')
            ->where('pos_shop_id', $user_info->adm_shop_id)
            ->first();
        if ($request['type'] == 1) {
            if (empty($find_set)) {
                $data['pos_set'][] = ['type'=>1,'name'=>'提交审核（待处理）','select'=>0];
                $data['pos_set'][] = ['type'=>2,'name'=>'采购审核（审核中）','select'=>0];
                $data['pos_set'][] = ['type'=>3,'name'=>'入库（未入库）','select'=>0];
                $data['pos_set'][] = ['type'=>4,'name'=>'确认完成（完成）','select'=>0];
            } else {
                $pos_set = json_decode($find_set->pos_set, true);
                usort($pos_set, function($a, $b) {
                    return $a['type'] <=> $b['type']; // 根据age键排序，使用太空船操作符（PHP 7及以上版本）
                });
                $data['pos_set'] = $pos_set;
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        if ($request['type'] == 2) {
            if ($find_set) {
                $update_set['pos_set'] = json_encode($request['pos_set'], true);
                $update_set['pos_update_id'] = $user_info->adm_id;
                $update_set['pos_update_time'] = date('Y-m-d H:i:s');
                $update_res = DB::table('purchase_order_set')
                    ->where('pos_id', $find_set->pos_id)
                    ->update($update_set);
            } else{
                $add_data['pos_shop_id'] = $user_info->adm_shop_id;
                $add_data['pos_set'] = json_encode($request['pos_set'], true);
                $add_data['pos_create_id'] = $user_info->adm_id;
                $add_data['pos_update_time'] = date('Y-m-d H:i:s');
                $add_res = DB::table('purchase_order_set')->insertGetId($add_data);
            }
            return response()->json(['code'=>200, 'msg'=>'提交成功', 'data'=>'']);
        }
    }
}
