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

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use App\Http\Controllers\Api\Verify\WarehouseManage\VerifySellController;
use App\Http\Models\Api\Export;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\StockSellStorageGoods;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Models\Api\SellDetail;
use App\Http\Models\Services\WarehouseManage\Sales;

// 仓储系统 -- 销售出库单
class SellController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $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;

        $search_data = $request->all();
        $list_data = DB::table('sell as a')
            ->leftJoin('sell_client as secl', 'secl.secl_sell_id', '=', 'a.sell_id')
            ->where('sell_cid', $user_info->adm_cid)
            ->where('sell_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sell_number'])) {
                    $query->where('sell_number', 'like', '%' . $search_data['sell_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间/派单时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('sell_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('sell_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('sell_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //审核时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['audit_time_start']) && !empty($search_data['audit_time_end'])) {
                    $query->whereBetween('sell_audit_time', [$search_data['audit_time_start'], $search_data['audit_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['audit_time_start'])) {
                        $query->where('sell_audit_time', '>=', $search_data['audit_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['audit_time_end'])) {
                            $query->where('sell_audit_time', '<=', $search_data['audit_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['secl_name'])) {
                    $query->where('secl_name', 'like', '%' . $search_data['secl_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['secl_phone'])) {
                    $query->where('secl_phone', 'like', '%' . $search_data['secl_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sell_state'])) {
                    $query->where('sell_state', $search_data['sell_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ware_id'])) {
                    $query->where('sell_ware_id', $search_data['ware_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户单位id
                if (!empty($search_data['sell_chun_id'])) {
                    $query->where('sell_chun_id', $search_data['sell_chun_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //系统类型1自营(门店提交)2系统(自己生成)
                if (!empty($search_data['sell_system_type'])) {
                    $query->where('sell_system_type', $search_data['sell_system_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户单位类型:1.会员零售2.客户单位3.速电派单4.第三方派单5.运营中心与门店来往
                if (!empty($search_data['secl_channel_type'])) {
                    $query->where('secl_channel_type', $search_data['secl_channel_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //审核人
                if (!empty($search_data['sell_audit_adm_id'])) {
                    $query->where('sell_audit_adm_id', $search_data['sell_audit_adm_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //结算状态1未结算2结算中3已结算
                if (!empty($search_data['sell_settlement_state'])) {
                    $query->where('sell_settlement_state', $search_data['sell_settlement_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //采购门店id
                if (!empty($search_data['sell_cg_shop_id'])) {
                    $query->where('sell_cg_shop_id', $search_data['sell_cg_shop_id']);
                }
            })
            ->select('sell_id', 'sell_number', 'sell_state', 'sell_count', 'sell_adm_id', 'sell_remark', 'sell_data', 'sell_create_time', 'secl_channel_unit', 'secl_name', 'secl_phone', 'secl_address', 'sell_sebi_id', 'sell_actual_count', 'sell_actual_price', 'secl_province', 'secl_city', 'secl_county', 'sell_chun_id', 'sell_cg_shop_id', 'sell_system_type', 'sell_ware_id', 'sell_audit_adm_id', 'sell_settlement_state', 'sell_audit_time', 'secl_channel_type')
            ->orderBy('sell_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        $find_admin = [];
        if ($list_items) {
            $sell_chun_id = array_unique(array_column($list_items, 'sell_chun_id')); //客户单位id
            $sell_ware_id = array_unique(array_column($list_items, 'sell_ware_id')); //仓库id
            $sell_audit_adm_id = array_unique(array_column($list_items, 'sell_audit_adm_id')); //仓库id

            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $sell_chun_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            // 查询仓库名称
            $warehouse = DB::table('warehouse')
                ->whereIn('ware_id', $sell_ware_id)
                ->where('ware_shop_id', $shop_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();
            // 查询审核人
            $sell_audit_adm = DB::table('admin')
                ->whereIn('adm_id', $sell_audit_adm_id)
                ->pluck('adm_name', 'adm_id')
                ->toArray();
            // 查找账号id
            foreach ($list_items as $key => $value) {
                if ($value->sell_adm_id) {
                    $adm_id[] = $value->sell_adm_id;
                }
                if ($value->sell_data) {
                    $value->sell_data = json_decode($value->sell_data, true);
                }
                if ($value->sell_system_type == 1) { //系统类型1自营(门店提交)2系统(自己生成)
                    $list_items[$key]->secl_channel_unit = DB::table('shop')
                        ->where('shop_id', $value->sell_cg_shop_id)
                        ->value('shop_store_name');
                } else { //客户单位名称
                    $list_items[$key]->secl_channel_unit = isset($channel[$value->sell_chun_id]) ? $channel[$value->sell_chun_id] : '';
                }
                $list_items[$key]->sell_audit_adm_name = isset($sell_audit_adm[$value->sell_audit_adm_id]) ? $sell_audit_adm[$value->sell_audit_adm_id] : '';
                $list_items[$key]->ware_name = isset($warehouse[$value->sell_ware_id]) ? $warehouse[$value->sell_ware_id] : '';
            }
            if (!empty($adm_id)) {
                $adm_id = array_unique($adm_id);
                // 查找账号id对应的账号姓名
                $find_admin = DB::table('admin')
                    ->whereIn('adm_id', $adm_id)
                    ->select('adm_id', 'adm_name')
                    ->get();
            }
        }

        $state_count = DB::table('sell')
            ->where('sell_cid', $user_info->adm_cid)
            ->where('sell_superior_shop_id', $shop_id)
            ->select(DB::raw('count(*) as count, sell_state'))
            ->groupBy('sell_state')
            ->get();
        $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'] = $list_items;                //返回数据
        $data_info['find_admin'] = $find_admin;                //返回账号姓名
        $data_info['state_count'] = $state_count;

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $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']);

        //获取销售单详情
        $get_info_res = Sales::info($request, $user_info);
        return response()->json($get_info_res);
    }

    // 获取出库仓库信息
    public function warehouseInfo(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;

        $list_data = DB::table('warehouse as w')
            ->leftJoin('admin as a', 'a.adm_id', '=', 'w.ware_leader_id')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id', $shop_id)
            ->where('ware_type', 1)
            ->where('ware_state', 1)
            ->where('ware_all_stock', '>', 0)
            ->select('ware_id', 'ware_name', 'ware_address', 'adm_name', 'adm_phone')
            ->get();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
    }

    // 新增保存【暂时用不到】
    public function save(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->saveValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $sell_count = 0; //出库总数量
        $sell_price = 0; //合计金额
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || !is_numeric($request['sell_number'][$key]) || $request['sell_number'][$key] < 0 || !is_numeric($request['sell_price'][$key]) || $request['sell_price'][$key] < 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }
            $sell_price += $request['sell_number'][$key] * $request['sell_price'][$key]; //合计金额
            $sell_count += $request['sell_number'][$key]; //出库总数量

            $sego_data[$key]['sego_goo_id'] = $value;
            $sego_data[$key]['sego_sell_number'] = $request['sell_number'][$key];
            $sego_data[$key]['sego_sell_price'] = $request['sell_price'][$key] * 100;
        }

        // 获取当前操作账号信息
        $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;

        // 1 新增一个销售出库单数据
        $sell_data['sell_cid'] = $user_info->adm_cid;
        $sell_data['sell_shop_id'] = $user_info->adm_shop_id;
        $sell_data['sell_superior_shop_id'] = $shop_id;
        $sell_data['sell_adm_id'] = $user_info->adm_id;
        $sell_data['sell_number'] = '31' . rand(10, 99) . date('mdHis') . rand(100000, 999999);
        $sell_data['sell_state'] = 1; // 状态1保存/待提交2提交/待出库3出库
        $sell_data['sell_count'] = $sell_count;
        $sell_data['sell_price'] = $sell_price * 100;
        $sell_data['sell_chun_id'] = $request['chun_id'];
        $sell_data['sell_ware_id'] = $request['sell_ware_id'];
        $sell_data['sell_waon_class'] = $request['proc_waon_class'] ? $request['proc_waon_class'] : 1;
        $sell_data['sell_actual_price'] = 0;
        $sell_data['sell_payment_way'] = $request['sell_payment_way'];
        if ($request['sell_data']) {
            $sell_data['sell_data'] = json_encode($request['sell_data']);
        } else {
            $sell_data['sell_data'] = '';
        }
        $sell_data['sell_remark'] = $request['sell_remark'] ? $request['sell_remark'] : '';

        DB::beginTransaction();

        // 新增销售出库单
        $sell_res =  DB::table('sell')->insertGetId($sell_data);

        // 2. 新增销售出库商品数据
        foreach ($sego_data as $key => $value) {
            $sego_data[$key]['sego_sell_id'] = $sell_res;
            $sego_data[$key]['sego_update_time'] = date('Y-m-d H:i:s');
        }
        $sego_res =  DB::table('sell_goods')->insert($sego_data);

        // 3. 新增销售出库客户数据
        $secl_data['secl_sell_id'] = $sell_res;
        $secl_data['secl_channel_unit'] = $request['chun_unit_name'];
        $secl_data['secl_name'] = $request['chun_name'];
        $secl_data['secl_phone'] = $request['chun_phone'];
        $secl_data['secl_province'] = $request['chun_province'];
        $secl_data['secl_city'] = $request['chun_city'];
        $secl_data['secl_county'] = $request['chun_county'];
        $secl_data['secl_address'] = $request['chun_address'];
        $secl_data['secl_update_time'] = date('Y-m-d H:i:s');
        $secl_res =  DB::table('sell_client')->insert($secl_data);

        if ($sell_res && $sego_res && $secl_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '保存', '保存销售出库单：' . $sell_data['sell_number'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'新增销售出库单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'新增销售出库单失败']);
        }
    }

    // 新增提交并清点出库，生成出库单状态为待出库状态【暂时用不到】
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->saveValidator($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;

        // 1 新增一个销售出库单数据
        $sell_data['sell_cid'] = $user_info->adm_cid;
        $sell_data['sell_shop_id'] = $user_info->adm_shop_id;
        $sell_data['sell_superior_shop_id'] = $shop_id;
        $sell_data['sell_adm_id'] = $user_info->adm_id;
        $sell_data['sell_number'] = '31' . rand(10, 99) . date('mdHis') . rand(100000, 999999);
        $sell_data['sell_state'] = 2; //状态1保存/待提交2提交/待出库3出库

        $sell_count = 0; //采购总数量
        $sell_price = 0; //合计金额
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || !is_numeric($request['sell_number'][$key]) || $request['sell_number'][$key] < 0  || !is_numeric($request['sell_price'][$key]) || $request['sell_price'][$key] < 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }
            $sell_price += $request['sell_number'][$key] * $request['sell_price'][$key]; //合计金额
            $sell_count += $request['sell_number'][$key]; //采购总数量

            $sego_data[$key]['sego_goo_id'] = $value;
            $sego_data[$key]['sego_sell_number'] = $request['sell_number'][$key];
            $sego_data[$key]['sego_sell_price'] = $request['sell_price'][$key] * 100;

            $goo_inventory = 1;
            $goo_state = 1;
            // 获取商品成本价
            $cost_price = StockSellStorageGoods::costPrice(
                $request['sell_ware_id'], //仓库id
                $request['proc_waon_class'], //仓库类别
                $value //商品id
            );
            // 生成销售明细
            $sell_res = SellDetail::add(
                $user_info, //用户信息
                $sell_data['sell_number'], //销售出库单号
                0, //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
                0, //订单标签id
                $request['sell_ware_id'], //仓库id
                2, //客户类型：1.门店零售 2.来往单位
                $request['chun_id'], //会员id/来往单位id
                0, //服务门店id
                $value, //商品id
                $request['sell_price'][$key], //商品售价
                $request['sell_number'][$key], //订单商品数量
                $cost_price / 100, //商品成本价
                $goo_inventory, //库存扣除方式1.良品 2.优先
                $goo_state,  //商品状态1.正常 2.删除3回收的商品4换货商品
                $request['sell_remark'] ? $request['sell_remark'] : '' //备注
            );
            if (empty($sell_res)) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'提交失败'];
            }
        }

        $sell_data['sell_count'] = $sell_count;
        $sell_data['sell_price'] = $sell_price * 100;
        $sell_data['sell_chun_id'] = $request['chun_id'];
        $sell_data['sell_ware_id'] = $request['sell_ware_id'];
        $sell_data['sell_waon_class'] = $request['proc_waon_class'] ? $request['proc_waon_class'] : 1;
        $sell_data['sell_actual_price'] = 0;
        $sell_data['sell_payment_way'] = $request['sell_payment_way'];
        if ($request['sell_data']) {
            $sell_data['sell_data'] = json_encode($request['sell_data']);
        } else {
            $sell_data['sell_data'] = '';
        }
        $sell_data['sell_remark'] = $request['sell_remark'] ? $request['sell_remark'] : '';

        DB::beginTransaction();
        // 新增销售出库单
        $sell_res =  DB::table('sell')->insertGetId($sell_data);

        // 2. 新增销售出库商品数据
        foreach ($sego_data as $key => $value) {
            $sego_data[$key]['sego_sell_id'] = $sell_res;
            $sego_data[$key]['sego_update_time'] = date('Y-m-d H:i:s');
        }
        $sego_res =  DB::table('sell_goods')->insert($sego_data);

        // 3. 新增销售出库客户数据
        $secl_data['secl_sell_id'] = $sell_res;
        $secl_data['secl_channel_unit'] = $request['chun_unit_name'];
        $secl_data['secl_name'] = $request['chun_name'];
        $secl_data['secl_phone'] = $request['chun_phone'];
        $secl_data['secl_province'] = $request['chun_province'];
        $secl_data['secl_city'] = $request['chun_city'];
        $secl_data['secl_county'] = $request['chun_county'];
        $secl_data['secl_address'] = $request['chun_address'];
        $secl_data['secl_update_time'] = date('Y-m-d H:i:s');
        $secl_res =  DB::table('sell_client')->insert($secl_data);

        // 查询销售出库单创建时间
        $sell_create_time = DB::table('sell')
            ->where('sell_id', $sell_res)
            ->value('sell_create_time');

        // 生成应收应付
        $sell_bill = ReceivableBill::create(
            $user_info, //用户信息
            7, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
            0, //应收账款id
            $sell_res, //原始id(销售单id)
            $sell_data['sell_number'], //应收账款单号/原始号(销售单号)
            2, //客户类型：1.门店零售 2.来往单位
            $sell_data['sell_chun_id'], //会员id/来往单位id
            $secl_data['secl_channel_unit'], //来往单位名称
            $sell_data['sell_price'], //结算金额(应收金额)
            '', //结款时间
            '', //会计科目id
            $sell_data['sell_price'], //实际金额(应收金额)
            0, //抹零金额
            1,  //状态：1.未核销 2.已核销
            1,  //应收账单id是否是自己 1.不是 2.是
            $sell_data['sell_remark'],  //备注
            0,  //已收金额
            '', //截止时间
            1, //金额正负1正   2负值
            9, //显示类型：1订单收款 10订单退款
            1, //是否合并代收：1是2否
            $sell_create_time
        );

        // 结款明细
        $AccountingSettlement = AccountingSettlement::add(
            $user_info,            // [用户信息]
            21,                     // [单据类型销售出库单]
            $sell_res,   // [与单据类型对应的id]
            $sell_data['sell_number'], // [与单据类型对应的单号]
            2,                     // [买家类型1门店零售2来往单位]
            $sell_data['sell_chun_id'],    // [会员/客户id]
            $secl_data['secl_channel_unit'],  // [来往单位名称]
            '',      // [会计科目id]
            1,                             // [类型1收入2支出]
            $sell_data['sell_price'],   // [实际金额](此次的实收金额)
            $sell_data['sell_price'],   // [合计金额](此次的应收金额)
            0,                        // [欠收金额](此次结款后还应收金额)
            0,                        // [抹零金额]
            $sell_data['sell_remark']   // [备注]
        );

        if ($sell_res && $sego_res && $secl_res && $sell_bill && $AccountingSettlement) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '新增', '新增销售出库单：' . $sell_data['sell_number'] . '成功');
            $return_data['sell_id'] = $sell_res;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'新增销售出库单成功', 'return_data'=>$return_data]);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'新增销售出库单失败']);
        }
    }

    // 编辑【暂时用不到】
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 销售出库单数据
        $find_sell = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->select('sell_state', 'sell_number')
            ->first();
        if ($find_sell->sell_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单已提交无法编辑']);
        }
        if ($find_sell->sell_state == 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单已出库无法编辑']);
        }

        if ($request['type'] == 1) {// 获取页面数据
            $sell_data = DB::table('sell as a')
                ->leftJoin('sell_client as c', 'c.secl_sell_id', '=', 'a.sell_id')
                ->where('sell_id', $request['sell_id'])
                ->select('sell_id', 'sell_payment_way', 'sell_price', 'sell_actual_price', 'sell_data', 'sell_chun_id', 'secl_channel_unit', 'secl_name', 'secl_phone', 'secl_address', 'sell_ware_id', 'sell_data', 'sell_remark', 'secl_province', 'secl_city', 'secl_county', 'sell_waon_class')
                ->first();
            $sell_data->sell_data = json_decode($sell_data->sell_data, true);
            $sell_data->secl_channel_unit = DB::table('channel_unit')
                ->where('chun_id', $sell_data->sell_chun_id)
                ->value('chun_unit_name');

            // 获取客户类型信息
            $channel_type = DB::table('channel_unit as a')
                ->leftJoin('channel_type as b', 'b.chty_id', '=', 'a.chun_chty_id')
                ->where('chun_id', $sell_data->sell_chun_id)
                ->select('chty_id', 'chty_name')
                ->first();

            // 获取仓库信息
            $warehouse_data = DB::table('warehouse as w')
                ->leftJoin('admin as a', 'a.adm_id', '=', 'w.ware_leader_id')
                ->where('ware_id', $sell_data->sell_ware_id)
                ->select('ware_id', 'ware_name', 'ware_address', 'adm_name', 'adm_phone')
                ->first();

            // 获取商品数据
            $find_goods = DB::table('sell_goods as a')
                ->leftJoin('goods as b', 'a.sego_goo_id', '=', 'b.goo_id')
                ->where('sego_sell_id', $request['sell_id'])
                ->select('sego_sell_number', 'sego_goo_id', 'sego_sell_price', 'goo_name', 'goo_type', 'goo_goods_encode')
                ->get();
            $data['sell_data'] = $sell_data;
            $data['goods_data'] = $find_goods;
            $data['warehouse_data'] = $warehouse_data;
            $data['channel_type'] = $channel_type;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

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

        $sell_count = 0; //采购总数量
        $sell_price = 0; //合计金额
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || !is_numeric($request['sell_number'][$key]) || $request['sell_number'][$key] < 0 || !is_numeric($request['sell_price'][$key]) || $request['sell_price'][$key] < 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }
            $sell_price += $request['sell_number'][$key] * $request['sell_price'][$key]; //合计金额
            $sell_count += $request['sell_number'][$key]; //采购总数量

            $sego_data[$key]['sego_sell_id'] = $request['sell_id'];
            $sego_data[$key]['sego_update_time'] = date('Y-m-d H:i:s');
            $sego_data[$key]['sego_goo_id'] = $value;
            $sego_data[$key]['sego_sell_number'] = $request['sell_number'][$key];
            $sego_data[$key]['sego_sell_price'] = $request['sell_price'][$key] * 100;
        }

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

        DB::beginTransaction();

        // 1 编辑销售出库单数据
        $sell_data['sell_adm_id'] = $user_info->adm_id;
        $sell_data['sell_count'] = $sell_count;
        $sell_data['sell_chun_id'] = $request['chun_id'];
        $sell_data['sell_ware_id'] = $request['sell_ware_id'];
        $sell_data['sell_waon_class'] = $request['proc_waon_class'] ? $request['proc_waon_class'] : 1;
        $sell_data['sell_price'] = $sell_price * 100;
        $sell_data['sell_payment_way'] = $request['sell_payment_way'];
        $sell_data['sell_update_time'] = date('Y-m-d H:i:s');
        if ($request['sell_data']) {
            $sell_data['sell_data'] = json_encode($request['sell_data']);
        } else {
            $sell_data['sell_data'] = '';
        }
        $sell_data['sell_remark'] = $request['sell_remark'] ? $request['sell_remark'] : '';

        $sell_res = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->update($sell_data);

        // 2. 更改盘点商品表的数据
        // 2.1 删除原来盘点id对应的盘点商品数据
        $sego_del_res = DB::table('sell_goods')
            ->where('sego_sell_id', $request['sell_id'])
            ->delete();
        // 2.2 重新添加提交的盘点商品数据
        $sego_res =  DB::table('sell_goods')->insert($sego_data);

        // 3. 编辑销售出库客户数据
        $secl_data['secl_channel_unit'] = $request['chun_unit_name'];
        $secl_data['secl_name'] = $request['chun_name'];
        $secl_data['secl_phone'] = $request['chun_phone'];
        $secl_data['secl_province'] = $request['chun_province'];
        $secl_data['secl_city'] = $request['chun_city'];
        $secl_data['secl_county'] = $request['chun_county'];
        $secl_data['secl_address'] = $request['chun_address'];
        $secl_data['secl_update_time'] = date('Y-m-d H:i:s');
        $secl_res =  DB::table('sell_client')
            ->where('secl_sell_id', $request['sell_id'])
            ->update($secl_data);

        if ($sell_res && $sego_del_res && $sego_res && $secl_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '编辑', '编辑销售出库单：' . $find_sell->sell_number . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'编辑销售出库单：成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑销售出库单：失败']);
        }
    }

    // 提交【暂时用不到】
    public function submit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_sell = DB::table('sell')
            ->leftjoin('sell_client as secl', 'secl.secl_sell_id', '=', 'sell_id')
            ->where('sell_id', $request['sell_id'])
            ->select('sell_number', 'sell_state', 'sell_chun_id', 'secl_channel_unit', 'sell_price', 'sell_remark', 'sell_ware_id', 'sell_waon_class', 'sell_create_time')
            ->first();
        // sell_state 状态1保存/待提交2提交/待出库3出库
        if ($find_sell->sell_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单不是待提交状态']);
        }

        $update_data['sell_state'] = 2; //状态1保存/待提交2提交/待出库3出库
        $update_data['sell_update_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();

        $sell_res = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->update($update_data);

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

        // 生成应收应付
        $sell_bill = ReceivableBill::create(
            $user_info, //用户信息
            7, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
            0, //应收账款id
            $request['sell_id'], //原始id(销售单id)
            $find_sell->sell_number, //应收账款单号/原始号(销售单号)
            2, //客户类型：1.门店零售 2.来往单位
            $find_sell->sell_chun_id, //会员id/来往单位id
            $find_sell->secl_channel_unit, //来往单位名称
            $find_sell->sell_price, //结算金额(应收金额)
            '', //结款时间
            '', //会计科目id
            $find_sell->sell_price, //实际金额(应收金额)
            0, //抹零金额
            1,  //状态：1.未核销 2.已核销
            1,  //应收账单id是否是自己 1.不是 2.是
            $find_sell->sell_remark,  //备注
            0,  //已收金额
            '', //截止时间
            1, //金额正负1正   2负值
            9, //显示类型：1订单收款 10订单退款
            1, //是否合并代收：1是2否
            $find_sell->sell_create_time
        );

        // 结款明细
        $AccountingSettlement = AccountingSettlement::add(
            $user_info,            // [用户信息]
            21,                     // [单据类型销售出库单]
            $request['sell_id'],   // [与单据类型对应的id]
            $find_sell->sell_number, // [与单据类型对应的单号]
            2,                     // [买家类型1门店零售2来往单位]
            $find_sell->sell_chun_id,    // [会员/客户id]
            $find_sell->secl_channel_unit,  // [来往单位名称]
            '',      // [会计科目id]
            1,                             // [类型1收入2支出]
            $find_sell->sell_price,   // [实际金额](此次的实收金额)
            $find_sell->sell_price,   // [合计金额](此次的应收金额)
            0,                        // [欠收金额](此次结款后还应收金额)
            0,                        // [抹零金额]
            $find_sell->sell_remark   // [备注]
        );

        // 查询销售出库商品信息
        $sell_goods = DB::table('sell_goods')
            ->where('sego_sell_id', $request['sell_id'])
            ->select('sego_id', 'sego_sell_id', 'sego_goo_id', 'sego_sell_price', 'sego_sell_number', 'sego_actual_number')
            ->get();
        foreach ($sell_goods as $key => $value) {
            $goo_inventory = 1;
            $goo_state = 1;
            // 获取商品成本价
            $cost_price = StockSellStorageGoods::costPrice(
                $find_sell->sell_ware_id, //仓库id
                $find_sell->sell_waon_class, //仓库类别
                $value->sego_goo_id //商品id
            );
            // 生成销售明细
            $sell_res = SellDetail::add(
                $user_info, //用户信息
                $find_sell->sell_number, //销售出库单号
                0, //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
                0, //订单标签id
                $find_sell->sell_ware_id, //仓库id
                2, //客户类型：1.门店零售 2.来往单位
                $find_sell->sell_chun_id, //会员id/来往单位id
                0, //服务门店id
                $value->sego_goo_id, //商品id
                $value->sego_sell_price / 100, //商品售价
                $value->sego_sell_number, //订单商品数量
                $cost_price / 100, //商品成本价
                $goo_inventory, //库存扣除方式1.良品 2.优先
                $goo_state,  //商品状态1.正常 2.删除3回收的商品4换货商品
                $find_sell->sell_remark //备注
            );
            if (empty($sell_res)) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'提交失败'];
            }
        }


        if ($sell_res && $sell_bill && $AccountingSettlement) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '提交', '销售出库单：' . $find_sell->sell_number . ' 提交成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'提交成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'提交失败']);
        }
    }

    // 审核
    public function audit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->auditValidator($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_sell = DB::table('sell')
            ->leftjoin('sell_client as secl', 'secl.secl_sell_id', '=', 'sell_id')
            ->where('sell_id', $request['sell_id'])
            ->select('sell_number', 'sell_state', 'sell_chun_id', 'secl_channel_unit', 'sell_price', 'sell_remark', 'sell_ware_id', 'sell_waon_class', 'sell_create_time', 'sell_cg_id', 'sell_cg_number', 'sell_cg_shop_id')
            ->first();
        if ($request['type'] == 1) { //查询页面数据
            $get_info_res = Sales::info($request, $user_info);
            return response()->json($get_info_res);
        }

        DB::beginTransaction();

        $audit_res = Sales::audit($user_info, $request, $find_sell);
        if ($audit_res['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '审核', '销售出库单：' . $find_sell->sell_number . ' 审核成功');
        } else {
            DB::rollBack();
        }
        return response()->json($audit_res);
    }

    // 出库
    public function originalRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $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']);
        if ($request['type'] == 1) { //获取页面数据
            // 销售出库单数据
            $sell_data = DB::table('sell as a')
                ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.sell_ware_id')
                ->leftJoin('sell_client as c', 'c.secl_sell_id', '=', 'a.sell_id')
                ->where('sell_id', $request['sell_id'])
                ->select('sell_id', 'sell_number', 'sell_state', 'sell_count', 'sell_adm_id', 'sell_price', 'sell_actual_price', 'sell_payment_way', 'sell_create_time', 'secl_channel_unit', 'secl_name', 'secl_phone', 'secl_address', 'ware_name', 'sell_data', 'sell_remark', 'sell_actual_count', 'secl_province', 'secl_city', 'secl_county', 'sell_waon_class', 'sell_chun_id', 'sell_system_type', 'sell_reject_reason', 'sell_ware_id')
                ->first();
            $sell_data = json_decode(json_encode($sell_data, true), true);
            if ($sell_data['sell_system_type'] == 2) { //系统类型1自营2系统
                $sell_data['secl_channel_unit'] = DB::table('shop')
                    ->where('shop_id', $sell_data['sell_chun_id'])
                    ->value('shop_store_name');
            } else {
                $sell_data['secl_channel_unit'] = DB::table('channel_unit')
                    ->where('chun_id', $sell_data['sell_chun_id'])
                    ->value('chun_unit_name');
            }

            // 获取采购商品数据
            $find_goods = DB::table('sell_goods as a')
                ->leftJoin('goods as b', 'a.sego_goo_id', '=', 'b.goo_id')
                ->where('sego_sell_id', $request['sell_id'])
                ->where('goo_delete', 1)
                ->where('goo_type', 1) //商品类型 1正常商品2赠品商品3活动商品4旧货商品
                ->select('sego_sell_number', 'sego_sell_price', 'sego_actual_number', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_id')
                ->get()->toArray();
            // 查询仓位商品锁定表
            $find_wfgl_data = DB::table('warehouse_freight_goods_lock as w')
                ->leftJoin('warehouse_freight as wf', 'w.wfgl_wafr_id', '=', 'wf.wafr_id')
                ->where('wfgl_shop_id', $user_info->adm_shop_id)
                ->where('wfgl_type', 3)
                ->where('wfgl_state', 1)
                ->where('wfgl_original_id', $request['sell_id'])
                ->where('wfgl_original_number', $sell_data['sell_number'])
                ->select('wfgl_id', 'wfgl_ware_id', 'wfgl_wago_id', 'wfgl_wafr_id', 'wfgl_wafg_id', 'wfgl_lock_quantity', 'wfgl_lock_type', 'wafr_name', 'wfgl_waon_class')
                ->get()->toArray();
            $find_wfgl_data = json_decode(json_encode($find_wfgl_data, true), true);
            $new_wfgl_sate = false; //是否重新组仓位数据
            if (empty($find_wfgl_data)) {
                // 没有查询到仓位锁定库存，需要重新组数据
                $new_wfgl_sate = true;
            }
            $new_wfgl_data = []; //新的仓位数据
            foreach ($find_goods as $key => $value) {
                // 查询仓库商品表中有可发货商品的数据
                $option_ware[] = DB::table('warehouse_goods as wago')
                    ->leftjoin('warehouse as w', 'wago.wago_ware_id', '=', 'w.ware_id')
                    ->where('wago_ware_id', $sell_data['sell_ware_id'])
                    ->where('wago_class', 1)
                    ->where('wago_goo_id', $value->goo_id)
                    ->select('wago_id', 'ware_id as wafr_id', 'ware_name as wafr_name', 'wago_stock_amount as wafg_stock_number', 'wago_lock_amount', 'wago_priority_lock_amount', 'wago_priority_stock_amount as wafg_priority_stock_number')
                    ->first();
                // 查询仓位商品表中有销售出库商品的数据
                $find_goods[$key]->option_freight = DB::table('warehouse_freight_goods as wafg')
                    ->leftjoin('warehouse_freight as wafr', 'wafg.wafg_wafr_id', '=', 'wafr.wafr_id')
                    ->where('wafg_ware_id', $sell_data['sell_ware_id'])
                    ->where('wafg_class', 1)
                    ->where('wafg_goo_id', $value->goo_id)
                    ->where(function ($query) use ($value) {
                        $query->where('wafg_stock_number', '>', 0)->Orwhere('wafg_lock_quantity', '>', 0);
                    })
                    ->select('wafr_id', 'wafr_name', 'wafr_rank', 'wafg_stock_number', 'wafg_priority_stock_number', 'wafg_lock_quantity', 'wafg_priority_lock_quantity')
                    ->get()->toArray();

                if (!empty($option_ware[0])) {
                    if ($option_ware[0]->wafg_stock_number > 0) {
                        $option_ware[0]->wafr_id = 0;
                        $option_ware[0]->wafr_name = '仓库';
                        $option_ware[0]->wafg_stock_number = $option_ware[0]->wafg_stock_number;
                        $option_ware[0]->wafg_priority_stock_number = $option_ware[0]->wafg_priority_stock_number;
                        $find_goods[$key]->option_freight = array_merge($option_ware, $find_goods[$key]->option_freight);
                    }
                }
                unset($option_ware);
                $wago_id = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $sell_data['sell_ware_id'])
                    ->where('wago_class', 1)
                    ->where('wago_goo_id', $value->goo_id)
                    ->value('wago_id');
                if ($new_wfgl_sate) {
                    // 重新调整数组
                    $temp_wfgl_data['wfgl_id'] = 0; //仓位商品锁定主键id
                    $temp_wfgl_data['wafr_name'] = '仓库'; //仓位商品锁定主键id
                    $temp_wfgl_data['wfgl_ware_id'] = $sell_data['sell_ware_id']; //仓库id
                    $temp_wfgl_data['wfgl_wago_id'] = $wago_id; //仓库商品主键id
                    $temp_wfgl_data['wfgl_wafr_id'] = 0; //仓位id
                    $temp_wfgl_data['wfgl_wafg_id'] = 0; //仓位商品主键id
                    $temp_wfgl_data['wfgl_lock_quantity'] = $value->sego_sell_number; //商品锁定数量
                    $temp_wfgl_data['wfgl_lock_type'] = 1; //商品锁定类型：1良品2优先
                    $new_wfgl_data[] = $temp_wfgl_data;
                    unset($temp_wfgl_data);
                }
                if ($new_wfgl_sate) { //没有仓位锁定商品
                    $find_goods[$key]->wfgl_data = $new_wfgl_data;
                    unset($new_wfgl_data);
                } else { //有锁定商品的
                    $num = 0;
                    $sego_sell_number = $value->sego_sell_number; //出库数量
                    foreach ($find_wfgl_data as $wfgl_key => $wfgl_value) { //从仓位商品表中扣除发货数量
                        if ($wfgl_value['wfgl_wago_id'] == $wago_id) { //判断仓库类别和发货类型和仓库商品id
                            if ($wfgl_value['wfgl_lock_quantity'] != 0) { //此仓位还有锁定数量，可以从这个仓位出库
                                $sego_sell_number = $sego_sell_number - $wfgl_value['wfgl_lock_quantity']; //出库商品-仓位中锁定的数量
                                $wafr_data[$num]['wafr_name'] = $wfgl_value['wafr_name'];
                                $wafr_data[$num]['wfgl_id'] = $wfgl_value['wfgl_id'];
                                $wafr_data[$num]['wfgl_wago_id'] = $wfgl_value['wfgl_wago_id'];
                                $wafr_data[$num]['wfgl_wafr_id'] = $wfgl_value['wfgl_wafr_id'];
                                $wafr_data[$num]['wfgl_wafg_id'] = $wfgl_value['wfgl_wafg_id'];
                                $wafr_data[$num]['wfgl_lock_type'] = $wfgl_value['wfgl_lock_type'];
                                if ($sego_sell_number <= 0) { //出库商品-仓位中锁定的数量小于0，仓位锁定出库后还有剩余，出完了，跳出
                                    $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = abs($sego_sell_number);
                                    $wafr_data[$num]['wfgl_lock_quantity'] = $sego_sell_number + $wfgl_value['wfgl_lock_quantity'];
                                    break;
                                } else { //出库商品-仓位中锁定的数量大于0，没出完，从下一个仓位扣除
                                    $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = 0;
                                    $wafr_data[$num]['wfgl_lock_quantity'] = $wfgl_value['wfgl_lock_quantity'];
                                }
                                $num++;
                            }
                        }
                    }

                    if ($sego_sell_number > 0) { //仓位出库后还有需要出库的库存，从仓库出库
                        $wafr_data[$num]['wafr_name'] = '仓库';
                        $wafr_data[$num]['wfgl_lock_quantity'] = $sego_sell_number;
                        $wafr_data[$num]['wfgl_id'] = $sego_sell_number;
                        $wafr_data[$num]['wfgl_ware_id'] = $sell_data['sell_ware_id']; //仓库id
                        $wafr_data[$num]['wfgl_wago_id'] = $wago_id; //仓库商品主键id
                        $wafr_data[$num]['wfgl_wafr_id'] = 0;
                        $wafr_data[$num]['wfgl_wafg_id'] = 0; //仓位商品主键id
                        $wafr_data[$num]['wfgl_lock_type'] = 1; //商品锁定类型：1良品2优先
                    }
                    $find_goods[$key]->wfgl_data = $wafr_data;
                    unset($sego_sell_number);
                    unset($wafr_data);
                }
            }

            // 查询账号id对应姓名
            $find_admin = DB::table('admin')
                ->where('adm_id', $sell_data['sell_adm_id'])
                ->select('adm_id', 'adm_name')
                ->first();
            $data['sell_data'] = $sell_data;
            $data['goods_data'] = $find_goods;
            $data['find_admin'] = $find_admin;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }
        // 查询信息
        $find_sell = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->select('sell_id', 'sell_state', 'sell_number', 'sell_ware_id', 'sell_count', 'sell_create_time', 'sell_sebi_id', 'sell_chun_id', 'sell_waon_class', 'sell_actual_price', 'sell_actual_count', 'sell_cg_number', 'sell_cg_shop_id', 'sell_system_type')
            ->first();
        // 状态1保存/待提交2提交/待审核3通过/待出库4驳回5出库（6部分出库7异常出库 暂时不用）
        if ($find_sell->sell_state == 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单未提交']);
        }
        if ($find_sell->sell_state == 5) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单已出库']);
        }
        if ($find_sell->sell_sebi_id != 0) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'已生成账单的销售出库单不可出库']);
        }
        if ($find_sell->sell_actual_count > 0) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单已经部分出库，无法原单出库']);
        }

        DB::beginTransaction();
        // 出库
        $out_return = Sales::outStorage($request->all(), $user_info, $find_sell, 3);
        // 仓库商品锁定表
        $wagl_id = DB::table('warehouse_goods_lock')
            ->where('wagl_original_correlation_id', $request['sell_id'])
            ->where('wagl_correlation_type', 4)
            ->value('wagl_id');
        if (!empty($wagl_id)) {
            $wagl_res = DB::table('warehouse_goods_lock')
                ->where('wagl_original_correlation_id', $request['sell_id'])
                ->where('wagl_correlation_type', 4)
                ->update(['wagl_update_time' => date('Y-m-d H:i:s'), 'wagl_state' => 2]);
        } else {
            $wagl_res =  true;
        }
        $wfgl_id = DB::table('warehouse_freight_goods_lock')
            ->where('wfgl_shop_id', $user_info->adm_shop_id)
            ->where('wfgl_original_id', $request['sell_id'])
            ->where('wfgl_original_number', $find_sell->sell_number)
            ->where('wfgl_correlation_type', 4)
            ->value('wfgl_id');
        if (!empty($wfgl_id)) {
            $wfgl_res = DB::table('warehouse_freight_goods_lock')
                ->where('wfgl_shop_id', $user_info->adm_shop_id)
                ->where('wfgl_original_id', $request['sell_id'])
                ->where('wfgl_original_number', $find_sell->sell_number)
                ->where('wfgl_correlation_type', 4)
                ->update(['wfgl_update_time' => date('Y-m-d H:i:s'), 'wfgl_state' => 2]);
        } else {
            $wfgl_res = true;
        }
        if ($out_return['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '出库', '销售出库单：' . $find_sell->sell_number . ' 出库成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'出库成功']);
        } else {
            DB::rollBack();
            return response()->json($out_return);
        }
    }

    /**
     * [outStorage 出库操作，部分出库、出库、原单出库的共有代码]
     * @param  [type] $request   [入库提交的数据]
     * @param  [type] $user_info [用户信息]
     * @param  [type] $find_sell [销售出库单信息]
     * @param  [type] $type      [出库类型：1部分出库2出库3原单出库]
     * @return [type]            [数组，返回入库结果]
     */
    private function outStorage($request, $user_info, $find_sell, $type)
    {
        // 原单入库
        if ($type == 3) {
            // 查询销售出库的商品数据
            $find_sego_goods = DB::table('sell_goods')
                ->where('sego_sell_id', $request['sell_id'])
                ->select('sego_id', 'sego_goo_id', 'sego_sell_price', 'sego_sell_number', 'sego_actual_number')
                ->get()->toArray();

            // 原单入库只提交销售出库单id，没有提交出库商品id、出库商品数量的数组
            $request['goo_id'] = array_column($find_sego_goods, 'sego_goo_id');
            // 这里把销售出库单的商品id、出库数量赋值给这两个数组，下面的代码就可以执行了
            $request['sell_actual_count'] = array_column($find_sego_goods, 'sego_sell_number');
        // 部分出库、出库
        } else {
            // 查询销售出库的商品数据
            $find_sego_goods = DB::table('sell_goods')
                ->where('sego_sell_id', $request['sell_id'])
                ->whereIn('sego_goo_id', $request['goo_id'])
                ->select('sego_id', 'sego_goo_id', 'sego_sell_price', 'sego_sell_number', 'sego_actual_number')
                ->get()->toArray();
        }
        if (count($find_sego_goods) != count($request['goo_id'])) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'存在不是销售出库单的商品，无法出库！'];
        }
        $goods_price = array_column($find_sego_goods, 'sego_sell_price', 'sego_goo_id'); //商品id对应的销售金额

        $sell_actual_count = 0; //实际入库总数量
        $price_sum = 0; //本次实际入库金额
        $i = 0; //序号
        foreach ($request['goo_id'] as $key => $value) {
            if (
                !is_numeric($value) || $value < 0 ||
                !is_numeric($request['sell_actual_count'][$key]) ||
                $request['sell_actual_count'][$key] < 0
            ) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误'];
            }
            $sell_actual_count += $request['sell_actual_count'][$key]; //实际出库总数量
            $price_sum += $request['sell_actual_count'][$key] * (isset($goods_price[$value]) ? $goods_price[$value] : 0); //实际出库总金额

            $goo_actual_count[$value] = $request['sell_actual_count'][$key]; //商品id对应的实际出库的数量
            $purchase_goo_actual_count[$value] = $request['sell_actual_count'][$key]; //进销存-商品id对应的实际出库的数量
            $purchase_goo_actual_price[$value] = $goods_price[$value] / 100; //进销存-商品id对应的实际出库的金额
            $goo_actual_id[] = $value;
            $goo_inventory[] = 1;
            $i++;
        }

        // 1. 更改采购入库单数据
        // if ($type != 1) {
        //     $update_data['sell_state'] = 3;//状态1保存/待提交2提交/待出库3出库4部分出库5异常出库
        //     $oure_type = 2;//出入库记录类型1.入库单
        // } else {
        //     $oure_type = 8;//出入库记录类型7.部分入库
        // }
        // 1. 更改销售出库单数据
        $update_data['sell_actual_count'] = $find_sell->sell_actual_count + $sell_actual_count; //实际出库数量
        $update_data['sell_actual_price'] = $find_sell->sell_actual_price + $price_sum; //实际出库金额
        $update_data['sell_remark'] = isset($request['sell_remark']) ? $request['sell_remark'] : ''; //出库备注
        $update_data['sell_update_time'] = date('Y-m-d H:i:s');

        if ($type == 1) { //部分出库
            if ($update_data['sell_actual_count'] != $find_sell->sell_count) {
                $update_data['sell_state'] = 4; //状态1保存/待提交2提交/待出库3出库4部分出库5异常出库
                $oure_type = 8; //出入库记录类型7.部分入库
            } else {
                $update_data['sell_state'] = 3;
                $oure_type = 2; //出入库记录类型1.入库单
            }
        } elseif ($type == 2) { //出库
            if ($update_data['sell_actual_count'] != $find_sell->sell_count) {
                $update_data['sell_state'] = 5; //状态1保存/待提交2提交/待出库3出库4部分出库5异常出库
                $oure_type = 8; //出入库记录类型7.部分入库
            } else {
                $update_data['sell_state'] = 3;
                $oure_type = 2; //出入库记录类型1.入库单
            }
        } elseif ($type == 3) { //原单出库
            $update_data['sell_state'] = 3; //状态1保存/待提交2提交/待出库3出库4部分出库5异常出库
            $oure_type = 2; //出入库记录类型1.入库单
        }

        if (isset($request['sell_data'])) {
            $update_data['sell_data'] = json_encode($request['sell_data']);
        } else {
            $update_data['sell_data'] = '';
        }
        $sell_res = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->update($update_data);

        // 2. 查询仓库的库存数量
        $find_waon = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $find_sell->sell_ware_id)
            ->where('waon_class', $find_sell->sell_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 - $sell_actual_count; //商品总库存
        $waon_data['waon_stock_fine_amount'] = $find_waon->waon_stock_fine_amount - $sell_actual_count; //良品总库存
        $waon_res = DB::table('warehouse_onhand')
            ->where('waon_id', $find_waon->waon_id)
            ->update($waon_data);

        // 3.生成出入库记录
        if (config('apisystem.WAREHOUSE')) {
            $oure_res = OutinRecord::addition(
                $user_info, //用户信息
                $request['sell_id'], //原始单的关联id
                $find_sell->sell_number, //原始单的关联单号
                4, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
                2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                $find_sell->sell_chun_id, //选择的客户id,会员id/单位id
                $find_sell->sell_number, //原始单号，旧货回收单单号
                0, //入库仓库id
                $find_sell->sell_ware_id, //出库仓库id
                $sell_actual_count, //出库的商品总数量
                $oure_type, //类型 5.退换回收单 9发货单 11换货出库12换货入库13退货入库14退货出库
                2, //操作类型：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入库
                $find_sell->sell_waon_class, //仓库类别
                $request['goo_id'], //商品id
                $request['sell_actual_count'], //商品数量
                $goo_inventory //出库类型1良品2优先
            );
        } else {
            $oure_res = OutinRecord::add(
                $user_info, //用户信息
                $find_sell->sell_number, //原始单号
                0, //入库仓库id
                $find_sell->sell_ware_id, //出库仓库id
                $sell_actual_count, //出库的商品总量
                $oure_type, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
                $request['goo_id'], //数组，商品id
                $request['sell_actual_count'], //数组，商品数量
                $goo_inventory, //数组，出库类型1良品2优先
                2, //操作类型：1锁定库存2出库3入库4调货5发货
                $waon_data['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入库
            );
        }

        // 4. 在仓库商品表增加对应的商品
        // 4.1.2 更新采购入库单商品的实际入库数量
        $sql = 'UPDATE `faster_sell_goods` SET ';
        $actual_number_sql = '';
        $update_time_sql = '';
        $ids = '';
        $actual_goo_id  = []; //实际入库的商品id
        $actual_goo_price  = []; //实际入库的商品价格
        foreach ($find_sego_goods as $key => $value) {
            if (in_array($value->sego_goo_id, $goo_actual_id)) {
                $actual_goo_id[] = $value->sego_goo_id; //盘点实际入库的商品id
                $actual_goo_price[$value->sego_goo_id] = $value->sego_sell_price; //盘点实际入库的商品价格

                // 商品实际入库数量
                // 更改商品库存数量
                $actual_number_sql = $actual_number_sql . ' WHEN ' . $value->sego_id;
                $actual_number_sql = $actual_number_sql . ' THEN ' . ($value->sego_actual_number + $goo_actual_count[$value->sego_goo_id]);
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value->sego_id;
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $value->sego_id . ',';
            }
        }

        $sql = $sql . ' `sego_actual_number`=  CASE `sego_id` ' . $actual_number_sql . ' END,';
        $sql = $sql . ' `sego_update_time`=  CASE `sego_id` ' . $update_time_sql . ' END';
        $sql = $sql . ' WHERE `sego_id` IN (' . trim($ids, ',') . ')';
        $sego_res = DB::update($sql);

        // 4.2 查询仓库商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $find_sell->sell_ware_id)
            ->where('wago_class', $find_sell->sell_waon_class)
            ->whereIn('wago_goo_id', $request['goo_id'])
            ->get(['wago_id', 'wago_stock_number', 'wago_goo_id']);
        $warehouse_goods = json_decode(json_encode($warehouse_goods), true);
        if (count($warehouse_goods) != count($request['goo_id'])) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'仓库商品库存不足，无法出库'];
        }

        // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
        $sql = 'UPDATE `faster_warehouse_goods` SET ';
        $stock_number_sql = '';
        $update_time_sql = '';
        $ids = '';
        foreach ($warehouse_goods as $key => $value) {
            // 要更改的商品库存数量
            $stock_number = $value['wago_stock_number'] - $goo_actual_count[$value['wago_goo_id']];
            if ($stock_number < 0) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'仓库商品库存不足，无法出库'];
            }
            // 更改商品库存数量
            $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']]);
        }

        $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);

        // 销售出库单
        // $sell_bill = ReceivableBill::create(
        //     $user_info, //用户信息
        //     6, // 类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单  7.销售出库单
        //     0, // 应收账款id
        //     $request['sell_id'], //原始id(销售出库单)
        //     $find_sell->sell_number, //应收账款单号/原始号(销售出库单)
        //     2, //客户类型：1.门店零售 2.来往单位
        //     $find_sell->sell_chun_id, //会员id/来往单位id
        //     $chun_unit_name, //来往单位名称
        //     $price_sum, //结算金额
        //     '', //结款时间
        //     '', //会计科目id
        //     0, //实际金额
        //     0, //抹零金额
        //     1,  //状态：1.未核销 2.已核销
        //     1,  //应收账单id是否是自己 1.不是 2.是
        //     '',  //备注
        //     0,  //已收金额
        //     '', //截止时间
        //     1,//金额正负1正   2负值
        //     9,//显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
        //     1//是否合并代收：1是2否
        // );

        // 销售出库单
        // $sell_bill = ReceivableBill::create(
        //     $user_info, //用户信息
        //     6, // 类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单  7.销售出库单
        //     0, // 应收账款id
        //     $request['sell_id'], //原始id(销售出库单)
        //     $find_sell->sell_number, //应收账款单号/原始号(销售出库单)
        //     2, //客户类型：1.门店零售 2.来往单位
        //     $find_sell->sell_chun_id, //会员id/来往单位id
        //     $chun_unit_name, //来往单位名称
        //     $sell_actual_price, //结算金额
        //     '', //结款时间
        //     '', //会计科目id
        //     0, //实际金额
        //     0, //抹零金额
        //     1,  //状态：1.未核销 2.已核销
        //     1,  //应收账单id是否是自己 1.不是 2.是
        //     '',  //备注
        //     0,  //已收金额
        //     '', //截止时间
        //     1,//金额正负1正   2负值
        //     9,//显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
        //     1//是否合并代收：1是2否
        // );

        if ($sell_res && $waon_res && $oure_res && $sego_res && $ware_edit_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'出库成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败'];
        }
    }

    // 提交出库
    public function submitStorage(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->submitStorageValidator($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_sell = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->select('sell_id', 'sell_state', 'sell_number', 'sell_ware_id', 'sell_count', 'sell_create_time', 'sell_sebi_id', 'sell_actual_count', 'sell_actual_price', 'sell_chun_id', 'sell_waon_class', 'sell_cg_number')
            ->first();
        if ($find_sell->sell_state == 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单未提交']);
        }
        if ($find_sell->sell_state == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单已驳回']);
        }
        if ($find_sell->sell_state == 5) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单已出库']);
        }
        if ($find_sell->sell_sebi_id != 0) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'已生成账单的销售出库单不可出库']);
        }

        if ($request['type'] == 1) {
            // 销售出库单数据
            $sell_data = DB::table('sell as a')
                ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.sell_ware_id')
                ->leftJoin('sell_client as c', 'c.secl_sell_id', '=', 'a.sell_id')
                ->where('sell_id', $request['sell_id'])
                ->select('sell_id', 'sell_number', 'sell_state', 'sell_count', 'sell_adm_id', 'sell_price', 'sell_actual_price', 'sell_payment_way', 'sell_create_time', 'secl_channel_unit', 'secl_name', 'secl_phone', 'secl_address', 'ware_name', 'sell_data', 'sell_remark', 'sell_actual_count', 'secl_province', 'secl_city', 'secl_county', 'sell_waon_class', 'sell_chun_id', 'sell_system_type', 'sell_reject_reason', 'sell_ware_id')
                ->first();
            $sell_data = json_decode(json_encode($sell_data, true), true);
            if ($sell_data['sell_system_type'] == 1) { //系统类型1自营2系统
                $sell_data['secl_channel_unit'] = DB::table('shop')
                    ->where('shop_id', $sell_data['sell_chun_id'])
                    ->value('shop_store_name');
            } else {
                $sell_data['secl_channel_unit'] = DB::table('channel_unit')
                    ->where('chun_id', $sell_data['sell_chun_id'])
                    ->value('chun_unit_name');
            }

            // 获取采购商品数据
            $find_goods = DB::table('sell_goods as a')
                ->leftJoin('goods as b', 'a.sego_goo_id', '=', 'b.goo_id')
                ->where('sego_sell_id', $request['sell_id'])
                ->where('goo_delete', 1)
                ->where('goo_type', 1) //商品类型 1正常商品2赠品商品3活动商品4旧货商品
                ->select('sego_sell_number', 'sego_sell_price', 'sego_actual_number', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_id', 'goo_class', 'goo_bra_name', 'goo_brse_id')
                ->get()->toArray();
            // 查询仓位商品锁定表
            $find_wfgl_data = DB::table('warehouse_freight_goods_lock as w')
                ->leftJoin('warehouse_freight as wf', 'w.wfgl_wafr_id', '=', 'wf.wafr_id')
                ->where('wfgl_shop_id', $user_info->adm_shop_id)
                ->where('wfgl_type', 3)
                ->where('wfgl_state', 1)
                ->where('wfgl_original_id', $request['sell_id'])
                ->where('wfgl_original_number', $sell_data['sell_number'])
                ->select('wfgl_id', 'wfgl_ware_id', 'wfgl_wago_id', 'wfgl_wafr_id', 'wfgl_wafg_id', 'wfgl_lock_quantity', 'wfgl_lock_type', 'wafr_name', 'wfgl_waon_class')
                ->get()->toArray();
            $find_wfgl_data = json_decode(json_encode($find_wfgl_data, true), true);
            $new_wfgl_sate = false; //是否重新组仓位数据
            if (empty($find_wfgl_data)) {
                // 没有查询到仓位锁定库存，需要重新组数据
                $new_wfgl_sate = true;
            }
            $new_wfgl_data = []; //新的仓位数据
            // 查询系列数据
            $goo_brse_id = array_column($find_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($find_goods as $key => $value) {
                // 查询仓库商品表中有可发货商品的数据
                $option_ware[] = DB::table('warehouse_goods as wago')
                    ->leftjoin('warehouse as w', 'wago.wago_ware_id', '=', 'w.ware_id')
                    ->where('wago_ware_id', $sell_data['sell_ware_id'])
                    ->where('wago_class', 1)
                    ->where('wago_goo_id', $value->goo_id)
                    ->select('wago_id', 'ware_id as wafr_id', 'ware_name as wafr_name', 'wago_stock_amount as wafg_stock_number', 'wago_lock_amount', 'wago_priority_lock_amount', 'wago_priority_stock_amount as wafg_priority_stock_number')
                    ->first();
                // 查询仓位商品表中有发货商品的数据
                $find_goods[$key]->option_freight = DB::table('warehouse_freight_goods as wafg')
                    ->leftjoin('warehouse_freight as wafr', 'wafg.wafg_wafr_id', '=', 'wafr.wafr_id')
                    ->where('wafg_ware_id', $sell_data['sell_ware_id'])
                    ->where('wafg_class', 1)
                    ->where('wafg_goo_id', $value->goo_id)
                    ->where(function ($query) use ($value) {
                        $query->where('wafg_stock_number', '>', 0)->Orwhere('wafg_lock_quantity', '>', 0);
                    })
                    ->select('wafr_id', 'wafr_name', 'wafr_rank', 'wafg_stock_number', 'wafg_priority_stock_number', 'wafg_lock_quantity', 'wafg_priority_lock_quantity')
                    ->get()->toArray();

                if (!empty($option_ware[0])) {
                    if ($option_ware[0]->wafg_stock_number > 0) {
                        $option_ware[0]->wafr_id = 0;
                        $option_ware[0]->wafr_name = '仓库';
                        $option_ware[0]->wafg_stock_number = $option_ware[0]->wafg_stock_number;
                        $option_ware[0]->wafg_priority_stock_number = $option_ware[0]->wafg_priority_stock_number;
                        $find_goods[$key]->option_freight = array_merge($option_ware, $find_goods[$key]->option_freight);
                    }
                }
                unset($option_ware);
                $wago_id = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $sell_data['sell_ware_id'])
                    ->where('wago_class', 1)
                    ->where('wago_goo_id', $value->goo_id)
                    ->value('wago_id');
                if ($new_wfgl_sate) {
                    // 重新调整数组
                    $temp_wfgl_data['wfgl_id'] = 0; //仓位商品锁定主键id
                    $temp_wfgl_data['wafr_name'] = '仓库'; //仓位商品锁定主键id
                    $temp_wfgl_data['wfgl_ware_id'] = $sell_data['sell_ware_id']; //仓库id
                    $temp_wfgl_data['wfgl_wago_id'] = $wago_id; //仓库商品主键id
                    $temp_wfgl_data['wfgl_wafr_id'] = 0; //仓位id
                    $temp_wfgl_data['wfgl_wafg_id'] = 0; //仓位商品主键id
                    $temp_wfgl_data['wfgl_lock_quantity'] = $value->sego_sell_number; //商品锁定数量
                    $temp_wfgl_data['wfgl_lock_type'] = 1; //商品锁定类型：1良品2优先
                    $new_wfgl_data[] = $temp_wfgl_data;
                    unset($temp_wfgl_data);
                }
                if ($new_wfgl_sate) { //没有仓位锁定商品
                    $find_goods[$key]->wfgl_data = $new_wfgl_data;
                    unset($new_wfgl_data);
                } else { //有锁定商品的
                    $num = 0;
                    $sego_sell_number = $value->sego_sell_number; //发货数量
                    foreach ($find_wfgl_data as $wfgl_key => $wfgl_value) { //从仓位商品表中扣除发货数量
                        if ($wfgl_value['wfgl_wago_id'] == $wago_id) { //判断仓库类别和发货类型和仓库商品id
                            if ($wfgl_value['wfgl_lock_quantity'] != 0) { //此仓位还有锁定数量，可以从这个仓位出库
                                $sego_sell_number = $sego_sell_number - $wfgl_value['wfgl_lock_quantity']; //出库商品-仓位中锁定的数量
                                $wafr_data[$num]['wafr_name'] = $wfgl_value['wafr_name'];
                                $wafr_data[$num]['wfgl_id'] = $wfgl_value['wfgl_id'];
                                $wafr_data[$num]['wfgl_wago_id'] = $wfgl_value['wfgl_wago_id'];
                                $wafr_data[$num]['wfgl_wafr_id'] = $wfgl_value['wfgl_wafr_id'];
                                $wafr_data[$num]['wfgl_wafg_id'] = $wfgl_value['wfgl_wafg_id'];
                                $wafr_data[$num]['wfgl_lock_type'] = $wfgl_value['wfgl_lock_type'];
                                if ($sego_sell_number <= 0) { //出库商品-仓位中锁定的数量小于0，仓位锁定出库后还有剩余，出完了，跳出
                                    $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = abs($sego_sell_number);
                                    $wafr_data[$num]['wfgl_lock_quantity'] = $sego_sell_number + $wfgl_value['wfgl_lock_quantity'];
                                    break;
                                } else { //出库商品-仓位中锁定的数量大于0，没出完，从下一个仓位扣除
                                    $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = 0;
                                    $wafr_data[$num]['wfgl_lock_quantity'] = $wfgl_value['wfgl_lock_quantity'];
                                }
                                $num++;
                            }
                        }
                    }

                    if ($sego_sell_number > 0) { //仓位出库后还有需要出库的库存，从仓库出库
                        $wafr_data[$num]['wafr_name'] = '仓库';
                        $wafr_data[$num]['wfgl_lock_quantity'] = $sego_sell_number;
                        $wafr_data[$num]['wfgl_id'] = $sego_sell_number;
                        $wafr_data[$num]['wfgl_ware_id'] = $sell_data['sell_ware_id']; //仓库id
                        $wafr_data[$num]['wfgl_wago_id'] = $wago_id; //仓库商品主键id
                        $wafr_data[$num]['wfgl_wafr_id'] = 0;
                        $wafr_data[$num]['wfgl_wafg_id'] = 0; //仓位商品主键id
                        $wafr_data[$num]['wfgl_lock_type'] = 1; //商品锁定类型：1良品2优先
                    }
                    $find_goods[$key]->wfgl_data = $wafr_data;
                    unset($sego_sell_number);
                    unset($wafr_data);
                }
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($value->goo_brse_id)) {
                        // 显示系列名称
                        if ($value->goo_class == 2) {
                            $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $value->goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $value->goo_name;
                        }
                    }
                }
                unset($find_goods[$key]->goo_class);
                unset($find_goods[$key]->goo_brse_id);
            }

            // 查询账号id对应姓名
            $find_admin = DB::table('admin')
                ->where('adm_id', $sell_data['sell_adm_id'])
                ->select('adm_id', 'adm_name')
                ->first();
            $data['sell_data'] = $sell_data;
            $data['goods_data'] = $find_goods;
            $data['find_admin'] = $find_admin;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        DB::beginTransaction();
        // 出库
        $out_return = Sales::outStorage($request->all(), $user_info, $find_sell, 3);
        // 仓库商品锁定表
        $wagl_id = DB::table('warehouse_goods_lock')
            ->where('wagl_original_correlation_id', $request['sell_id'])
            ->where('wagl_correlation_type', 4)
            ->value('wagl_id');
        if (!empty($wagl_id)) {
            $wagl_res = DB::table('warehouse_goods_lock')
                ->where('wagl_original_correlation_id', $request['sell_id'])
                ->where('wagl_correlation_type', 4)
                ->update(['wagl_update_time' => date('Y-m-d H:i:s'), 'wagl_state' => 2]);
        } else {
            $wagl_res =  true;
        }
        $wfgl_id = DB::table('warehouse_freight_goods_lock')
            ->where('wfgl_shop_id', $user_info->adm_shop_id)
            ->where('wfgl_original_id', $request['sell_id'])
            ->where('wfgl_original_number', $find_sell->sell_number)
            ->where('wfgl_type', 4)
            ->value('wfgl_id');
        if (!empty($wfgl_id)) {
            $wfgl_res = DB::table('warehouse_freight_goods_lock')
                ->where('wfgl_shop_id', $user_info->adm_shop_id)
                ->where('wfgl_original_id', $request['sell_id'])
                ->where('wfgl_original_number', $find_sell->sell_number)
                ->where('wfgl_type', 4)
                ->update(['wfgl_update_time' => date('Y-m-d H:i:s'), 'wfgl_state' => 2]);
        } else {
            $wfgl_res = true;
        }
        if ($out_return['code'] == 200 && $wfgl_res && $wagl_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '出库', '销售出库单：' . $find_sell->sell_number . ' 出库成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'出库成功']);
        } else {
            DB::rollBack();
            return response()->json($out_return);
        }
    }

    // 部分出库
    public function partStorage(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->partStorageValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_sell = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->select('sell_state', 'sell_number', 'sell_ware_id', 'sell_count', 'sell_create_time', 'sell_sebi_id', 'sell_actual_count', 'sell_actual_price', 'sell_chun_id', 'sell_waon_class')
            ->first();
        if ($find_sell->sell_state == 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单未提交']);
        }
        if ($find_sell->sell_state == 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单已出库']);
        }
        if ($find_sell->sell_sebi_id != 0) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'已生成账单的销售出库单不可出库']);
        }

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

        DB::beginTransaction();
        // 出库
        $out_return = $this->outStorage($request->all(), $user_info, $find_sell, 1);

        if ($out_return['code'] == 200) {
            $sere_del_res = DB::table('sell_record')
                ->where('sere_sell_id', $request['sell_id'])
                ->delete();
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '部分出库', '销售出库单：' . $find_sell->sell_number . ' 出库成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'出库成功']);
        } else {
            DB::rollBack();
            return response()->json($out_return);
        }
    }

    // 扫码记录【暂时用不到】
    public function scanRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->scanRecordValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if ($request['scan_type'] == 1) {
            // 条形码出库
            // 获取当前操作账号信息
            $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;
            $goo_type = isset($request['goo_type']) ? $request['goo_type'] : 1;
            // 1. 判断当前门店是否有该条形码商品
            $find_goods = DB::table('goods')
                ->where('goo_cid', $user_info->adm_cid)
                ->where('goo_superior_shop_id', $shop_id)
                ->where('goo_delete', 1)
                ->where('goo_goods_encode', $request['scan_code'])
                ->where('goo_type', $goo_type)
                ->select('goo_id', 'goo_goods_encode', 'goo_name', 'goo_type')
                ->first();
            if (!$find_goods) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前门店未找到 ' . $request['scan_code'] . ' 该条形码商品']);
            }
            // 查找销售出库记录表是否添加当前扫码商品
            $find_prre = DB::table('sell_record')
                ->where('sere_sell_id', $request['sell_id'])
                ->where('sere_goo_goods_encode', $find_goods->goo_goods_encode)
                ->select('sere_id', 'sere_goo_quantity')
                ->first();
            if ($request['type'] == 1) {
                // 扫码增加商品
                if ($find_prre) {
                    $sere_res = DB::table('sell_record')
                        ->where('sere_id', $find_prre->sere_id)
                        ->increment('sere_goo_quantity');
                } else {
                    // 没有添加商品，增加一条商品数据
                    $sere_data['sere_sell_id'] = $request['sell_id'];
                    $sere_data['sere_goo_id'] = $find_goods->goo_id;
                    $sere_data['sere_goo_name'] = $find_goods->goo_name;
                    $sere_data['sere_goo_goods_encode'] = $find_goods->goo_goods_encode;
                    $sere_data['sere_goo_quantity'] = 1;
                    $sere_data['sere_goo_type'] = $request['goo_type'];
                    $sere_res = DB::table('sell_record')->insert($sere_data);
                }
                // 提示文字
                $return_meg = '添加';
            } else {
                // 扫码减少商品
                if ($find_prre) {
                    if ($find_prre->sere_goo_quantity == 1) {
                        $sere_res = DB::table('sell_record')
                            ->where('sere_id', $find_prre->sere_id)
                            ->delete();
                    } else {
                        $sere_res = DB::table('sell_record')
                            ->where('sere_id', $find_prre->sere_id)
                            ->decrement('sere_goo_quantity');
                    }
                } else {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$request['scan_code'] . ' 该条形码商品尚未添加扫码记录']);
                }
                // 提示文字
                $return_meg = '删除';
            }
            if ($sere_res) {
                Common::addLog($user_info, getRealIp($request), '销售出库', '扫码记录', '商品条码：' . $request['scan_code'] . ' 扫码记录' . $return_meg . '成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'扫码记录' . $return_meg . '成功', 'return_data'=>$find_goods]);
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'扫码记录' . $return_meg . '失败']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂未开通二维码扫码出库']);
        }
    }

    // 删除扫码记录【暂时用不到】
    public function deleteRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->deleteRecordValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $sere_res = DB::table('sell_record')
            ->where('sere_sell_id', $request['sell_id'])
            ->where('sere_goo_id', $request['goo_id'])
            ->delete();
        if ($sere_res) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'商品扫码记录删除成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品扫码记录删除失败']);
        }
    }

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

        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || !is_numeric($request['sell_actual_count'][$key]) || $request['sell_actual_count'][$key] < 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }
            $goo_id[] = $value;
            $goo_quantity[$value] = $request['sell_actual_count'][$key];
        }
        $find_goods = DB::table('goods')
            ->whereIn('goo_id', $goo_id)
            ->select('goo_id', 'goo_name', 'goo_goods_encode')
            ->get();
        foreach ($find_goods as $key => $value) {
            $sere_data[$key]['sere_sell_id'] = $request['sell_id'];
            $sere_data[$key]['sere_goo_id'] = $value->goo_id;
            $sere_data[$key]['sere_goo_name'] = $value->goo_name;
            $sere_data[$key]['sere_goo_goods_encode'] = $value->goo_goods_encode;
            $sere_data[$key]['sere_goo_quantity'] = $goo_quantity[$value->goo_id];
        }
        DB::beginTransaction();
        $find_prre = DB::table('sell_record')
            ->where('sere_sell_id', $request['sell_id'])
            ->value('sere_id');
        if ($find_prre) {
            // 删除原来提交记录的数据
            $sere_del_res = DB::table('sell_record')
                ->where('sere_sell_id', $request['sell_id'])
                ->delete();
        } else {
            $sere_del_res = true;
        }

        // 添加新的商品搜索记录
        $sere_add_res = DB::table('sell_record')->insert($sere_data);

        if ($sere_add_res && $sere_del_res) {
            DB::commit();
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '销售出库', '出库记录', '商品搜索记录提交成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'商品搜索记录提交成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品搜索记录提交失败']);
        }
    }

    // 搜索商品
    public function searchGoods(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $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']);

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

        $search_data = $request->all();
        $list_data = DB::table('goods as a')
            ->leftJoin('warehouse_goods as b', 'b.wago_goo_id', '=', 'a.goo_id')
            ->where('goo_cid', $user_info->adm_cid)
            ->where('goo_superior_shop_id', $shop_id)
            ->where('wago_ware_id', $request['ware_id'])
            ->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'] . '%');
                }
            })
            ->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_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->select('goo_id', 'goo_name', 'goo_goods_encode', 'goo_price')
            ->orderBy('goo_id', 'desc')
            ->get();
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 生成账单搜索
    public function searchBill(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;

        $search_data = $request->all();
        // 如果选择了单位类型 查询出该单位类型下有多少个单位
        if (!empty($search_data['unit_type'])) {
            $chun_id = DB::table('channel_unit')
                ->where('chun_chty_id', $search_data['unit_type'])
                ->get(['chun_id'])->toArray();
            $search_data['chty_id'] = array_column($chun_id, 'chun_id');
        }

        $data = DB::table('sell as s')
            ->leftJoin('admin as c', 'c.adm_id', '=', 's.sell_adm_id')
            ->where('sell_cid', $user_info->adm_cid)
            ->where('sell_superior_shop_id', $shop_id)
            ->where('sell_actual_count', '>', 0)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sebi_id'])) {
                    // 编辑
                    $query->where('sell_sebi_id', 0)
                        ->Orwhere('sell_sebi_id', $search_data['sebi_id']);
                } else {
                    // 新增
                    $query->where('sell_sebi_id', 0);
                }
            }) //判断是编辑还是新增
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('sell_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('sell_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('sell_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            }) //起止日期
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sell_chun_id'])) {
                    $query->where('sell_chun_id', $search_data['sell_chun_id']);
                }
            }) //客户单位
            ->orderBy('sell_id', 'desc')
            ->get(['sell_id', 'sell_create_time', 'sell_number', 'sell_price', 'sell_actual_price', 'adm_name']);

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

    // 生成账单
    public function createBill(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->createBillValidator($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;

        $number = 'SZ' . time() . rand(1000000, 9999999);
        // 1. 销售账单表新增一条数据
        $add_data['sebi_cid'] = $user_info->adm_cid;
        $add_data['sebi_shop_id'] = $user_info->adm_shop_id;
        $add_data['sebi_superior_shop_id'] = $shop_id;
        $add_data['sebi_create_adm_id'] = $user_info->adm_id;
        $add_data['sebi_number'] = $number;
        $add_data['sebi_wor_amount'] = count($request['sell_id']);
        $add_data['sebi_start_time'] = $request['start_time'];
        $add_data['sebi_end_time'] = $request['end_time'];
        $add_data['sebi_state'] = 3; //待审核
        $add_data['sebi_type'] = $request['sell_type']; //类型：1门店零售2渠道单位
        $add_data['sebi_client_id'] = $request['sell_client_id']; //渠道/客户id
        // 获取到商品总量/合计金额/结算金额
        $add_data['sebi_goods_sum'] = 0; //商品总数量
        $add_data['sebi_total_price'] = 0; //合计金额
        $add_data['sebi_bill_price'] = 0; //结算金额
        $sell = DB::table('sell')
            ->whereIn('sell_id', $request['sell_id'])
            ->get(['sell_actual_count', 'sell_price', 'sell_actual_price']);
        foreach ($sell as $key => $value) {
            $add_data['sebi_total_price'] += $value->sell_price;
            $add_data['sebi_bill_price'] += $value->sell_actual_price;
            $add_data['sebi_goods_sum'] += $value->sell_actual_count;
        }
        DB::beginTransaction();

        $sebi_id = DB::table('sell_bill')->insertGetId($add_data);

        // 2.修改销售单表 账单id
        $sql = 'UPDATE `faster_sell` SET ';
        $sell_sebi_id = ''; //账单id
        $update_time = ''; //调货时间
        $sell_id = "";

        foreach ($request['sell_id'] as $key => $value) {
            // 更改账单id
            $sell_sebi_id = $sell_sebi_id . ' WHEN ' . $value;
            $sell_sebi_id = $sell_sebi_id . ' THEN ' . $sebi_id;
            // 更改时间
            $update_time = $update_time . ' WHEN ' . $value;
            $update_time = $update_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
            // 要更改的销售单id
            $sell_id = $sell_id . $value . ',';
        }
        $sql = $sql . ' `sell_sebi_id`= CASE `sell_id` ' . $sell_sebi_id . ' END,';
        $sql = $sql . ' `sell_update_time`= CASE `sell_id` ' . $update_time . ' END';
        $sql = $sql . ' WHERE `sell_id` IN (' . trim($sell_id, ',') . ')';
        $save_sell = DB::update($sql);

        // 应收账单表新增数据
        // if($request['sell_type'] == 2){
        //     $analyze = Common::updateAnalyze(
        //         $user_info, //用户信息
        //         $request['sell_client_id'], //客户单位id
        //         1, //单量
        //         $request['sell_actual_price'] * 100, //应收账款结算金额
        //         1  //类型1.编辑+ 2.编辑-
        //     );
        // }else{
        //     $analyze = true;
        // }

        if ($sebi_id && $save_sell) {
            Common::addLog($user_info, getRealIp($request), '销售出库', '生成账单', '生成账单：' . $number . '成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'生成账单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成账单失败']);
        }
    }

    // 打印
    public function print(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 销售出库单数据
        $sell_data = DB::table('sell as a')
            ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.sell_ware_id')
            ->leftJoin('sell_client as c', 'c.secl_sell_id', '=', 'a.sell_id')
            ->leftJoin('channel_info as chin', 'chin.chin_chun_id', '=', 'a.sell_chun_id')
            ->leftjoin('print_number as prnu', 'prnu.prnu_original_id', '=', 'a.sell_id')
            ->where('sell_id', $request['sell_id'])
            ->select('sell_id', 'sell_number', 'sell_state', 'sell_count', 'sell_adm_id', 'sell_price', 'sell_actual_price', 'sell_payment_way', 'sell_create_time', 'secl_channel_unit', 'secl_name', 'secl_phone', 'secl_address', 'ware_name', 'sell_data', 'sell_remark', 'chin_level', 'prnu_print_num', 'secl_province', 'secl_city', 'secl_county', 'sell_chun_id')
            ->first();
        $sell_data->sell_data = json_decode($sell_data->sell_data, true);
        $sell_data->secl_channel_unit = DB::table('channel_unit')
            ->where('chun_id', $sell_data->sell_chun_id)
            ->value('chun_unit_name');

        $data['sell_price'] = num_to_rmb($sell_data->sell_price / 100);
        // 获取采购商品数据
        $find_goods = DB::table('sell_goods as a')
            ->leftJoin('goods as b', 'a.sego_goo_id', '=', 'b.goo_id')
            ->where('sego_sell_id', $request['sell_id'])
            ->select('sego_sell_number', 'sego_sell_price', 'goo_name', 'goo_goods_encode', 'sego_sell_price')
            ->get();

        // 查询账号id对应姓名
        $find_admin = DB::table('admin')
            ->where('adm_id', $sell_data->sell_adm_id)
            ->select('adm_id', 'adm_name')
            ->first();
        $data['sell_data'] = $sell_data;
        $data['goods_data'] = $find_goods;
        $data['find_admin'] = $find_admin;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 导出
    public function export(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;

        $search_data = $request->all();
        $data = DB::table('sell as a')
            ->leftJoin('sell_client as secl', 'secl.secl_sell_id', '=', 'a.sell_id')
            ->where('sell_cid', $user_info->adm_cid)
            ->where('sell_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sell_number'])) {
                    $query->where('sell_number', 'like', '%' . $search_data['sell_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sell_create_time'])) {
                    $query->where('sell_create_time', 'like', '%' . $search_data['sell_create_time'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['secl_name'])) {
                    $query->where('secl_name', 'like', '%' . $search_data['secl_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['secl_phone'])) {
                    $query->where('secl_phone', 'like', '%' . $search_data['secl_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ware_id'])) {
                    $query->where('sell_ware_id', $search_data['ware_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sell_state'])) {
                    $query->where('sell_state', $search_data['sell_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sell_chun_id'])) {
                    $query->where('sell_chun_id', $search_data['sell_chun_id']);
                }
            }) //客户单位id
            ->select('sell_number', 'sell_state', 'sell_count', 'sell_adm_id', 'sell_remark', 'sell_data', 'sell_create_time', 'secl_channel_unit', 'secl_name', 'secl_phone', 'secl_address', 'sell_ware_id', 'sell_chun_id')
            ->orderBy('sell_id', 'desc')
            ->get();
        // 将对象转化为数组
        $data = json_decode(json_encode($data), true);
        $sell_chun_id = array_unique(array_column($data, 'sell_chun_id')); //客户单位id
        $sell_ware_id = array_unique(array_column($data, 'sell_ware_id')); //仓库id

        if (!empty($data)) {
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $sell_chun_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            // 查询仓库名称
            $warehouse = DB::table('warehouse')
                ->whereIn('ware_id', $sell_ware_id)
                ->where('ware_shop_id', $shop_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();
            // 查找账号id
            foreach ($data as $key => $value) {
                if ($value['sell_adm_id']) {
                    $adm_id[] = $value['sell_adm_id'];
                }
            }
            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $admin = DB::table('admin')->whereIn('adm_id', $adm_id)->pluck('adm_name', 'adm_id');
            foreach ($data as $key => $value) {
                // 状态
                if ($value['sell_state'] == 1) {
                    $data[$key]['sell_state'] = '待提交';
                }
                if ($value['sell_state'] == 2) {
                    $data[$key]['sell_state'] = '待出库';
                }
                if ($value['sell_state'] == 3) {
                    $data[$key]['sell_state'] = '出库';
                }
                if ($value['sell_state'] == 4) {
                    $data[$key]['sell_state'] = '部分出库';
                }
                if ($value['sell_state'] == 5) {
                    $data[$key]['sell_state'] = '异常出库';
                }
                // 操作人
                $data[$key]['sell_adm_id'] = $admin[$value['sell_adm_id']];
                // 物流信息json数据
                if (!empty($value['sell_data'])) {
                    $value['sell_data'] = json_decode($value['sell_data'], true);

                    if ($value['sell_data'][0]['type'] == 1) {
                        // 1.第三方物流
                        $data[$key]['sell_data'] = '[' . $value['sell_data'][0]['traffic_unit'] . ']
                        ' . implode(",", $value['sell_data'][0]['express_waybill']);
                    } elseif ($value['sell_data'][0]['type'] == 2 || $value['sell_data'][0]['type'] == 3) {
                        // 2.供货方配送 3.采购方自提
                        $data[$key]['sell_data'] = '[' . $value['sell_data'][0]['traffic_unit'] . '] '
                            . $value['sell_data'][0]['name'] . ','
                            . $value['sell_data'][0]['phone'] .
                            implode(",", $value['sell_data'][0]['car_num']);
                    } elseif ($value['sell_data'][0]['type'] == 4) {
                        // 4.无
                        $data[$key]['sell_data'] = $value['sell_data'][0]['remark'];
                    }
                }
                // 客户单位名称
                if (isset($channel[$value['sell_chun_id']])) {
                    $data[$key]['secl_channel_unit'] = $channel[$value['sell_chun_id']];
                } else {
                    $data[$key]['secl_channel_unit'] = '';
                }
                $data[$key]['sell_ware_id'] = $warehouse[$value['sell_ware_id']];
                // 采购单号
                $data[$key]['sell_number'] = "\t" . $value['sell_number'];
                unset($data[$key]['sell_chun_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(10000, 99999) . '.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'=>'导出失败']);
        }
    }

    /**
     * 列表导出函数
     * @param  $path   string  excel路径
     * @param  $where  string  where条件
     * @param  $data   array   导出数据
     * @return array
     */
    public function publicExport($path, $where, $data)
    {
        $res = DB::table('sell')->get();
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet(); //获取工作表
        // dump($worksheet);die;
        // // $letter = range('A','Z');//生成a-z的字母
        // return response()->json(['code'=> 900, 'msg'=>'success', 'data'=>$worksheet]);

        $letter = [];
        $num = count($data[0]);
        for ($i = 0; $i < $num; $i++) {
            if ($i < 26) {
                $letter[] = chr(65 + $i);
            } else {
                $letter[] = chr(64 + ($i / 26)) . chr(65 + $i % 26);
            }
        }
        // $filename = 'D:\phpStudy\PHPTutorial\WWW\sudian\public\excel\2019-11-13\20191113-64715.xls';
        $filename = public_path() . $path;
        $highest_row = '';
        if (is_file($filename)) {
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filename); //如果文件存在则直接载入
            $sheet = $spreadsheet->getActiveSheet(); //获取活动的工作sheet
            $highest_row = $sheet->getHighestRow(); // 取得总行数
        } else {
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); //文件不存在则实例化一个新的文件
            $sheet = $spreadsheet->getActiveSheet(); //获取工作表
            // $title = $this->gainFields($where['admin_id'],$where['action']);//获取拥有字段
            $sheet->setTitle($where['action_name']);  //设置当前sheet的标题
            $title = $where['field_name'];
            foreach ($title as $key => $value) {
                $sheet->setCellValue($letter[$key] . '1', $value . "\t");
                // $spreadsheet->getActiveSheet()->getColumnDimension('aa')->setAutoSize(true);
                $spreadsheet->getActiveSheet()->getColumnDimension($letter[$key])->setAutoSize(true);
            }
        }

        $i = $highest_row ? $highest_row : 1; //开始行数
        foreach ($data as $key => $value) {
            $j = 0;
            foreach ($value as $k => $v) {
                $sheet->setCellValue($letter[$j] . ($i + 1), $v);
                $j++;
            }
            $i++;
        }
        $obj_Writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        // ob_end_clean();//清除缓冲区,避免乱码
        header("Content-type: application/vnd.ms-excel; charset=UTF-8");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $obj_Writer->save($filename);
    }

    // 打印次数提交
    public function printNumber(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $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']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 判断是否有打印数据
        $prnu_id = DB::table('print_number')
            ->where('prnu_adm_cid', $user_info->adm_cid)
            ->where('prnu_superior_shop_id', $shop_id)
            ->where('prnu_type', 4)
            ->where('prnu_original_id', $request['sell_id'])
            ->select('prnu_id', 'prnu_print_num')
            ->first();
        $prnu_data['prnu_adm_cid'] = $user_info->adm_cid;   //公司id
        $prnu_data['prnu_shop_id'] = $user_info->adm_shop_id;   //所属门店id
        $prnu_data['prnu_superior_shop_id'] = $shop_id;   //所属总店id
        $prnu_data['prnu_type'] = 4;   //所属类型
        $prnu_data['prnu_original_id'] = $request['sell_id'];   //销售单id
        $prnu_data['prnu_update_time'] = date('Y-m-d H:i:s');

        if ($prnu_id) {
            $prnu_data['prnu_print_num'] = $prnu_id->prnu_print_num + 1;   //打印次数
            $prnu_res = DB::table('print_number')
                ->where('prnu_original_id', $request['sell_id'])
                ->update($prnu_data);
        } else {
            $prnu_data['prnu_print_num'] = 1;   //打印次数
            $prnu_res = DB::table('print_number')->insert($prnu_data);
        }

        if ($prnu_res) {
            $sell_number = DB::table('sell')
                ->where('sell_id', $request['sell_id'])
                ->value('sell_number');
            Common::addLog($user_info, getRealIp($request), '销售出库', '打印', '销售出库单：' . $sell_number . ' 打印成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'打印成功']);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'打印成功']);
        }
    }

    // 销售单结算
    public function sellSettlement(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $error_message = $verify_data->sellSettlementValidator($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) {
            $sell_data_result = DB::table('sell as a')
                ->leftJoin('channel_unit as b', 'b.chun_id', '=', 'a.sell_chun_id')
                ->leftJoin('admin as c', 'c.adm_id', '=', 'a.sell_adm_id')
                ->where('sell_number', $request['sell_number'])
                ->select('sell_id', 'adm_name', 'sell_price', 'sell_chun_id', 'sell_number', 'sell_create_time', 'chun_unit_name', 'sell_price', 'sell_system_type', 'sell_cg_shop_id')
                ->first();
            // $inorderresult = DB::table('accounting_settlement as acse')
            //     ->leftJoin('admin as adm', 'adm.adm_id', '=', 'acse.acset_adm_id')
            //     ->where('acset_original_number', $request['sell_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();
            if ($sell_data_result->sell_system_type == 1) {
                $sell_data_result->chun_unit_name = DB::table('shop')
                    ->where('shop_id', $sell_data_result->sell_cg_shop_id)
                    ->value('shop_store_name');
            }
            // foreach ($inorderresult as $k => $v) {
            //     if ($v->acset_state == '1') {
            //         $inorderresult[$k]->adm_name = '--';
            //     }
            // }
            return response()->json(['code'=>200, 'msg'=>'success', 'sell_data'=>$sell_data_result]);
        }
        DB::beginTransaction();
        $sellSettlement_res = Sales::sellSettlement($user_info, $request);
        if ($sellSettlement_res['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '销售出库', '结算', $request['sell_number'].'结算成功');
        } else {
            DB::rollBack();
        }
        return response()->json($sellSettlement_res);
    }

    // 销售单出库记录
    public function sellRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellController;
        $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']);

        // 获取销售单出库记录
        $sell_record_data = Sales::sellRecord($request, $user_info);
        return response()->json($sell_record_data);
    }
}
