<?php
namespace App\Http\Models\Services\WarehouseManage;

use App\Services\CommonService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Services\Business\WashOrderBasicService;
use App\Http\Controllers\Api\Storage\WareInorderController;

// 仓储系统 -- 采购管理
class PurchaseOrder extends Model
{
    // 新增采购单获取采购单号及合同号
    public static function getPurchaseData(
        $user_info,
        $shop_id,
        $request
    ) {
        // 生成采购单号
        $rule_data = DB::table('order_rule')
            ->where('orru_type', 3) //类型：1.订单编号规则 2.工单编号规则 3.采购单号规则
            ->where('orru_cid', $user_info->adm_cid)
            ->where('orru_superior_id', $shop_id) //总店
            ->first(['orru_number', 'orru_date', 'orru_id']);
        if ($rule_data) {
            // 有此总店的数据 判断是不是今天的
            if ($rule_data->orru_date == date('Y-m-d')) {
                // 采购单总量+1
                $order_rule = DB::table('order_rule')
                    ->where('orru_id', $rule_data->orru_id)
                    ->increment('orru_number');

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

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

            $today_order = 1; //今天的采购单总量
        }
        // CG+年月日时分秒是16位 采购单编号共20位 所以补零的位数为4位
        $cg_number = 'CG' . date('YmdHis') . str_pad($today_order, 4, '0', STR_PAD_LEFT);
        // 生成合同单号
        $contract_number = time() . rand(10000, 99999);

        if ($order_rule) {
            return ['code'=>200, 'msg'=>'success', 'data'=>['cg_number'=>$cg_number, 'contract_number'=>$contract_number]];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'采购单生成错误'];
        }
    }

    // 提交新增采购单
    public static function add(
        $user_info,
        $shop_id,
        $allData,
        $file = ''
        ) {
        $goods_data = $allData['goods'];
        unset($allData['goods']);
        // 给采购表的数据赋值
        $cg_data = [];
        // 基本信息
        $cg_data['company_id'] = $user_info->adm_cid;
        $cg_data['cg_userid']  = $user_info->adm_id;
        $cg_data['cg_creator'] = $user_info->adm_name;
        $cg_data['cg_superior_shop_id'] = $shop_id;
        $cg_data['cg_shop_id'] = $user_info->adm_shop_id;
        $cg_data['cg_number']      = $allData['cg_number']; //采购单号
        $cg_data['contract_number'] = $allData['contract_number']; //合同单号
        $cg_data['cg_purchasetime'] = $allData['cg_purchasetime']; //采购日期
        $cg_data['business_type']  = $allData['business_type']; //业务类型1普通采购2样品采购
        $cg_data['cg_wareid']      = $allData['cg_wareid']; //仓库id
        $cg_data['cg_waon_class']  = 1; //仓库类别1货物仓2非货物仓3旧货仓4临时仓
        $cg_data['cg_remark']      = $allData['cg_remark']; //采购依据(备注)
        // 供货方
        $cg_data['puor_supplyunit_type']  = 1; //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
        if ($allData['puor_supplyunit_type'] == 1) {
            $cg_data['cg_supplyunit']  = $allData['cg_supplyunit']; //供货单位
            $cg_data['contact_name']   = empty($allData['contact_name']) ? '' : $allData['contact_name']; //联系人
            $cg_data['contact_phone']  = empty($allData['contact_phone']) ? '' : $allData['contact_phone']; //联系电话
        } elseif ($allData['puor_supplyunit_type'] == 2) {
            $shop_parent_id = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->value('shop_parent_id');
            $parent_shop = DB::table('shop')
                ->where('shop_id', $shop_parent_id)
                ->select('shop_store_name', 'shop_name', 'shop_phone')
                ->first();
            $cg_data['cg_supplyunit']  = $shop_parent_id; //供货单位上级运营中心
            $cg_data['contact_name']   = $parent_shop->shop_name; //联系人
            $cg_data['contact_phone']  = $parent_shop->shop_phone; //联系电话
        } elseif ($allData['puor_supplyunit_type'] == 3) {
            // 根据供货单位id查询出客户单位是否是速电快保,是,在供应链后台新增销售单数据
            $chun_data = DB::table('channel_unit')
                ->where('chun_shop_id', $user_info->adm_shop_id)
                ->where('chun_class', 2)
                ->select('chun_id', 'chun_name', 'chun_phone', 'chun_class')
                ->first();
            $cg_data['cg_supplyunit']  = $chun_data->chun_id; //供货单位 供应链
            $cg_data['contact_name']   = $chun_data->chun_name; //联系人
            $cg_data['contact_phone']  = $chun_data->chun_phone; //联系电话
        }
        // 结算信息
        $cg_data['cg_paytype'] = 1; //是否账单结算1否是
        $cg_data['cg_paymentype']  = $allData['cg_paymentype']; //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天
        if ($allData['cg_paymentype'] == '3') {
            $cg_data['cg_yfmoney'] = $allData['cg_yfmoney']; //预付金额
        } else {
            $cg_data['cg_yfmoney'] = 0; //预付金额
        }
        $cg_data['cg_delivertype'] = $allData['cg_delivertype']; //交货方式1送货上门2自提
        $cg_data['cg_invoicetype'] = $allData['cg_invoicetype']; //票据类型1普通发票2专用发票
        $cg_data['cg_settlementype']   = 4; //结算状态1正常 待生成账单2待结算3已结算4待审核
        $cg_data['need_toexamine'] = 1;
        $cg_data['cg_state']   = 3; //采购单状态1审核中3驳回编辑5未入库8部分入库11完成(9待结算10待审核)15申请终止17中止
        $cg_data['cg_type'] = 1; //入库单
        $cg_data['cg_types'] = 1; //普通采购

        $total_value = 0;

        // 商品信息
        $goods_name = '';
        $storage_goods = [];
        $sell_count = 0; //出库总数量
        if(isset($allData['addType']) && $allData['addType']==2){
            if ($file->isValid()) {
                // 获取表格的大小，限制上传表格的大小5M
                $file_size = $_FILES['file']['size'];
                if ($file_size > 5 * 1024 * 1024) {
                    return ['code' => 500, 'msg' => '文件大小不能超过5M', 'data' => '文件大小不能超过5M'];
                }

                // 限制上传表格类型
                $ext = $file->getClientOriginalExtension(); //文件拓展名
                if ($ext != 'xlsx') {
                    return ['code' => 500, 'msg' => '仅允许上传以xlsx结尾的后缀文件', 'data' => '仅允许上传以xlsx结尾的后缀文件'];
                }
                // 有Xls和Xlsx格式两种
                $objReader = IOFactory::createReader('Xlsx');
                $filename = $_FILES['file']['tmp_name'];
                $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                if ($highestRow < 2) {
                    return ['code' => 500, 'msg' => '未获取到商品数据', 'data' => '未获取到商品数据'];
                }
                if ($highestRow > 1002) {
                    return ['code' => 500, 'msg' => '一次最多导入1000条数据', 'data' => '一次最多导入1000条数据'];
                }
                $goodid = [];
                for ($j = 2; $j <= $highestRow; $j++) {
                    if($j == 2){
                        if(trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()) =='序列码' && trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()) =='检索编号' && trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue()) =='商品名称' && trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue()) =='采购数量' && trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()) =='采购单价' && trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()) =='税率' && trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue()) =='币种'){
                            continue;
                        }else{
                            return ['code' => 500, 'msg' => '模板错误', 'data' => '模板错误'];
                        }
                    }
                    $temp = [];
                    $temp['goods_id'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());//商品id
                    if (empty($temp['goods_id'])) {
                        return ['code' => 500, 'msg' => '序列码必填', 'data' => '序列码必填'];
                    }
                    if($goodid && in_array($temp['goods_id'], $goodid)){
                        return ['code' => 500, 'msg' => '序列码'.$temp['goods_id'].'重复', 'data' => '序列码'.$temp['goods_id'].'重复'];
                    }else{
                        $goodid[] = $temp['goods_id'];
                    }
                    // 查询商品名称和检索编码
                    $goods_arr = Db::table('goods')
                        ->where('goo_id', $temp['goods_id'])
                        ->select('goo_name', 'goo_goods_encode', 'goo_class','goo_type','goo_unit')
                        ->first();
                    if (!$goods_arr) {
                        return ['code' => 500, 'msg' => '商品编号'.$temp['goods_id'].'错误,请重新填写采购单', 'data' => '商品编号'.$temp['goods_id'].'错误,请重新填写采购单','datas'=>$goods_arr];
                    }
                    $temp['tax_rate'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());//税率
                    if (empty($temp['tax_rate'])) {
                        $temp['tax_rate'] = 0;
                    }
                    $temp['currency'] = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());//币种
                    if (empty($temp['currency'])) {
                        $temp['currency'] = '人民币';
                    }
                    $temp['company_unit'] = $goods_arr->goo_unit;//计量单位
                    $temp['univalence'] = (float)trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());//采购单价
                    $temp['goods_num'] = (int)trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());//商品采购数量
                    if (empty($temp['goods_num'])) {
                        return ['code' => 500, 'msg' => 'error', 'data' => '商品采购数量错误,请重新填写采购单'];
                    }
                    $temp['money'] = (float)($temp['univalence']*$temp['goods_num']);//金额
                    $temp['cg_goodsnum'] = $temp['goods_num'];//采购数量,因为退货会减去采购数量,所以就有这个字短
                    // 提前将每个商品的分算平均后的价格计算完毕；  如果采购单价或采购总价为0 则赋值为0
                    if ($temp['univalence'] <= '0') {//$cg_data['cg_amount'] <= '0' ||
                        $temp['old_univalence'] = 0;
                    } else {
//                        $temp['old_univalence'] = round($cg_data['cg_amount'] / $total_value * $temp['univalence'], 2);
                        $temp['old_univalence'] = round($temp['univalence'], 2);
                    }
                    $total_value = $total_value+($temp['goods_num']*$temp['univalence']);
                    if ($temp['goods_num'] < 1) {
                        continue;
                    }
                    $temp['relation_number'] = $cg_data['cg_number']; //系统编号(入库单号,采购单号,调拨单号)
                    $temp['storehouse'] = $cg_data['cg_wareid']; //仓库id
                    $temp['ruku_num'] = 0; //入库数量
                    $temp['goods_type'] = $goods_arr->goo_type; //商品类型1正常商品2赠送商品3活动商品4旧货商品
                    $temp['creator'] = $user_info->adm_name;
                    $temp['create_time'] = date('Y-m-d H:i:s');
                    $temp['company_id'] = $user_info->adm_cid;
                    $temp['stgo_superior_shop_id'] = $shop_id;
                    $temp['stgo_shop_id'] = $user_info->adm_shop_id;


                    if ($goods_arr->goo_class == '2') {
                        $sell_count += $temp['goods_num']; //出库总数量
                    }

                    $temp['goods_number'] = $goods_arr->goo_goods_encode;
                    $temp['goods_name'] = $goods_arr->goo_name;
                    $goods_name = $goods_name . ',' . $goods_arr->goo_name . $goods_arr->goo_goods_encode;
                    $storage_goods[] = $temp;
                }
            }else{
                return ['code' => 500, 'msg' => '上传有误，请重新上传', 'data' => '上传有误，请重新上传'];
            }
        }else {
            // 处理商品数据
            foreach ($goods_data as $key => $val) {
                $temp = [];
                $temp['goods_id'] = $val['goods_id'];
                $temp['tax_rate'] = $val['tax_rate'];
                $temp['currency'] = $val['currency'];
                $temp['company_unit'] = empty($val['company_unit']) ? '' : $val['company_unit'];
                $temp['univalence'] = (float)$val['univalence'];
                $temp['money'] = (float)$val['money'];
                $temp['goods_num'] = (int)$val['goods_num'];
                $temp['cg_goodsnum'] = $temp['goods_num'];
                // 提前将每个商品的分算平均后的价格计算完毕；  如果采购单价或采购总价为0 则赋值为0
                if ($temp['univalence'] <= '0') {//$cg_data['cg_amount'] <= '0' ||
                    $temp['old_univalence'] = 0;
                } else {
                    $temp['old_univalence'] = round($temp['univalence'], 2);
                }
                $total_value = $total_value+($temp['goods_num']*$temp['univalence']);
                if ($temp['goods_num'] < 1) {
                    continue;
                }
                $temp['relation_number'] = $cg_data['cg_number']; //系统编号(入库单号,采购单号,调拨单号)
                $temp['storehouse'] = $cg_data['cg_wareid']; //仓库id
                $temp['ruku_num'] = 0; //入库数量
                $temp['goods_type'] = $val['goo_type']; //商品类型1正常商品2赠送商品3活动商品4旧货商品
                $temp['creator'] = $user_info->adm_name;
                $temp['create_time'] = date('Y-m-d H:i:s');
                $temp['company_id'] = $user_info->adm_cid;
                $temp['stgo_superior_shop_id'] = $shop_id;
                $temp['stgo_shop_id'] = $user_info->adm_shop_id;

                // 查询商品名称和检索编码
                $goods_arr = Db::table('goods')
                    ->where('goo_id', $val['goods_id'])
                    ->select('goo_name', 'goo_goods_encode', 'goo_class')
                    ->first();
                if (!$goods_arr) {
                    return ['code' => 500, 'msg' => '未知的商品,请重新填写采购单', 'data' => '未知的商品,请重新填写采购单'];
                }
                if ($goods_arr->goo_class == '2') {
                    $sell_count += $val['goods_num']; //出库总数量
                }

                $temp['goods_number'] = $goods_arr->goo_goods_encode;
                $temp['goods_name'] = $goods_arr->goo_name;
                $goods_name = $goods_name . ',' . $goods_arr->goo_name . $goods_arr->goo_goods_encode;
                $storage_goods[] = $temp;
            }
        }

        $cg_data['cg_amount']      = $total_value; //采购金额
        if (empty($storage_goods)) {
            return ['code'=>500, 'msg'=>'商品不能为空,请重新填写采购单', 'data'=>'商品不能为空,请重新填写采购单'];
        }

        $cg_data['goods_name'] = $goods_name;

        $puor_id = DB::table('purchase_order')->insert($cg_data);
        $stgo_id = DB::table('storage_goods')->insert($storage_goods);
        $new_goods_data = [];
        foreach ($storage_goods as $key => $value) {
            $new_goods_data[$key]['goo_id'] = $value['goods_id'];
        }
        $post_data['ware_id'] = $allData['cg_wareid'];
        $post_data['new_goods_data'] = $new_goods_data;
        $res = WashOrderBasicService::addGoodPlan($user_info, $post_data);

        // 查询自动流程
        $autoNext_data['cg_number'] = $cg_data['cg_number'];
        $autoNext_data['now_state'] = 0;
        $autoNext_res = self::autoNext($user_info,$autoNext_data,$shop_id);
        if ($autoNext_res['code'] != 200) {
            return $autoNext_res;
        }
        if ($puor_id && $stgo_id) {
            return ['code'=>200, 'msg'=>'采购单：添加成功', 'data'=>'采购单：添加成功', 'cg_data'=>$cg_data];
        } else {
            return ['code'=>500, 'msg'=>'添加失败', 'data'=>'添加失败'];
        }
    }

    // 获取编辑信息
    public static function getEditdata(
        $user_info,
        $puor_data,
        $cg_number
    ) {
        // 获取采购单的供货商名称，仓库名称，分组名称
        $puor_data['supplyunit_name'] = (string) Db::table('channel_unit')
            ->where('chun_id', $puor_data['cg_supplyunit'])
            ->value('chun_unit_name');
        $puor_data['ware_name'] = DB::table('warehouse')
            ->where('ware_id', $puor_data['cg_wareid'])
            ->value('ware_name');
        // 获取采购商品列表
        $storage_goods = DB::table('storage_goods')
            ->leftjoin('goods', 'goo_id', '=', 'goods_id')
            ->where('relation_number', $cg_number)
            ->select('goo_class', 'goo_bra_name', 'goo_brse_id', 'goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_cate_name', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'goo_brse_id', 'goo_class', 'goo_goods_encode')
            ->get();
        $storage_goods = json_decode(json_encode($storage_goods), true);
        // 判断状态
        if (!in_array($puor_data['cg_state'], [1, 3, 11])) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'状态已发生改变,该状态无法编辑'];
        }
        // 查询系列数据
        $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        foreach ($storage_goods as $key => $value) {
            // 判断系列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) {
                        $storage_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'))) {
                            $storage_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) {
                    $storage_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $storage_goods[$key]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $storage_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $storage_goods[$key]['goo_name'];
                    }
                }
            }
            unset($storage_goods[$key]['goo_brse_id']);
        }
        unset($puor_data['cg_state']);
        if ($puor_data && $storage_goods) {
            return ['code'=>200, 'msg'=>'success', 'data'=>['cg_data'=>$puor_data, 'storage_goods'=>$storage_goods]];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'查无数据'];
        }
    }

    // 编辑采购单
    public static function edit(
        $user_info,
        $puor_data,
        $allData
    ) {
        $goods_data = $allData['goods'];
        unset($allData['goods']);
        $cg_data = [];
        $total_value = 0;
        foreach ($goods_data as $key => $val) {
            $total_value = $total_value + ((int)$val['goods_num'] * (float)$val['univalence']);
        }
        $cg_data['cg_amount']       = $allData['cg_amount'];
        $cg_data['cg_purchasetime'] = $allData['cg_purchasetime'];
        $cg_data['business_type']   = $allData['business_type'];
        $cg_data['cg_supplyunit']   = $allData['cg_supplyunit'];
        $cg_data['cg_invoicetype']  = $allData['cg_invoicetype'];
        $cg_data['cg_paymentype']   = $allData['cg_paymentype'];
        $cg_data['cg_delivertype']  = $allData['cg_delivertype'];
        $cg_data['cg_wareid']       = $allData['cg_wareid'];
        $cg_data['cg_waon_class']   = 1;
        $cg_data['contract_number'] = $allData['contract_number'];
        $cg_data['contact_phone']   = $allData['contact_phone'];
        $cg_data['cg_remark']       = $allData['cg_remark'];
        $cg_data['contact_name']    = $allData['contact_name'];
        $cg_data['cg_correction']   = $allData['cg_correction'];
        $cg_data['puor_supplyunit_type']   = 1; //供货方类型1.供货单位2.运营中心 3.供应链4.可来电
        if ($allData['puor_supplyunit_type'] == 1) {
            $cg_data['cg_supplyunit']  = $allData['cg_supplyunit']; //供货单位
            $cg_data['contact_name']   = $allData['contact_name']; //联系人
            $cg_data['contact_phone']  = $allData['contact_phone']; //联系电话
        } elseif ($allData['puor_supplyunit_type'] == 2) {
            $shop_parent_id = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->value('shop_parent_id');
            $parent_shop = DB::table('shop')
                ->where('shop_id', $shop_parent_id)
                ->select('shop_store_name', 'shop_name', 'shop_phone')
                ->first();
            $cg_data['cg_supplyunit']  = $shop_parent_id; //供货单位上级运营中心
            $cg_data['contact_name']   = $parent_shop->shop_name; //联系人
            $cg_data['contact_phone']  = $parent_shop->shop_phone; //联系电话
        } elseif ($allData['puor_supplyunit_type'] == 3) {
            // 根据供货单位id查询出客户单位是否是速电快保,是,在供应链后台新增销售单数据
            $chun_data = DB::table('channel_unit')
                ->where('chun_shop_id', $user_info->adm_shop_id)
                ->where('chun_class', 2)
                ->select('chun_id', 'chun_name', 'chun_phone', 'chun_class')
                ->first();
            $cg_data['cg_supplyunit']  = $chun_data->chun_id; //供货单位 供应链
            $cg_data['contact_name']   = $chun_data->chun_name; //联系人
            $cg_data['contact_phone']  = $chun_data->chun_phone; //联系电话
        }

        $goods_name = '';
        $storage_goods = [];
        // 处理商品数据
        foreach ($goods_data as $key => $val) {
            $temp = [];
            $temp['goods_id']     = $val['goods_id'];
            $temp['tax_rate']     = $val['tax_rate'];
            $temp['currency']     = $val['currency'];
            $temp['company_unit'] = empty($val['company_unit']) ? '' : $val['company_unit'];
            $temp['univalence']   = (float) $val['univalence'];
            $temp['money']        = (float) $val['money'];
            $temp['goods_num']    = (int) $val['goods_num'];
            $temp['cg_goodsnum']  = $temp['goods_num'];

            // 提前分算平均，如果采购总价为0或者单品为0 则赋值为0；
            if ($puor_data['cg_amount'] <= 0 || $temp['univalence'] <= 0) {
                $temp['old_univalence'] = 0;
            } else {
                $temp['old_univalence'] = round($puor_data['cg_amount'] / $total_value * $temp['univalence'], 2);
            }

            if ($temp['goods_num'] < 1) {
                continue;
            }
            $temp['relation_number'] = $puor_data['cg_number'];
            $temp['storehouse'] = $puor_data['cg_wareid'];
            if (isset($goodsarray[$val['goods_id']]['ruku_num'])) {
                $temp['ruku_num'] = $goodsarray[$val['goods_id']]['ruku_num']; //已入库数量
            } else {
                $temp['ruku_num'] = 0;
            }
            $temp['goods_type'] = isset($val['goods_type']) ? $val['goods_type'] : $val['goo_type'];
            $temp['creator'] = $user_info->adm_name;
            $temp['create_time'] = date('Y-m-d H:i:s');
            $temp['company_id'] = $user_info->adm_cid;

            // 获取商品名称、检索编码
            $goods_arr = Db::table('goods')
                ->where('goo_id', $val['goods_id'])
                ->select('goo_name', 'goo_goods_encode', 'goo_class')
                ->first();
            $goods_arr = json_decode(json_encode($goods_arr), true);
            if (!$goods_arr) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'未知的商品,请重新填写采购单'];
            }

            $temp['goods_number'] = $goods_arr['goo_goods_encode'];
            $temp['goods_name']  = $goods_arr['goo_name'];
            $goods_name = $goods_name . ',' . $goods_arr['goo_name'] . $goods_arr['goo_goods_encode'];
            $storage_goods[] = $temp;
        }
        if (empty($storage_goods)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'商品不能为空,请重新填写采购单'];
        }
        $cg_data['goods_name'] = $goods_name;
        $cg_data['edit_time'] = date('Y-m-d H:i:s');
        $cg_data['cg_state'] = 3;
        $cg_data['cg_paytype'] = 1; //是否账单结算1否是
        if ($cg_data['cg_paymentype'] == '3') {
            $cg_data['cg_yfmoney'] = $allData['cg_yfmoney']; //预付金额
        } else {
            $cg_data['cg_yfmoney'] = 0; //预付金额
        }
        $old_ware_id = DB::table('purchase_order')
            ->where('cg_id', $puor_data['cg_id'])
            ->value('cg_wareid');
        $old_goods_data = DB::table('storage_goods')
            ->where('relation_number', $puor_data['cg_number'])
            ->select('goods_id as goo_id')
            ->get();

        // 修改采购单数据
        $puor_id = DB::table('purchase_order')
            ->where('cg_id', $puor_data['cg_id'])
            ->update($cg_data);

        // 删除原来采购单商品
        $del_stgo_id = DB::table('storage_goods')
            ->where('relation_number', $puor_data['cg_number'])
            ->delete();
        // 新增商品信息
        $stgo_id = DB::table('storage_goods')->insert($storage_goods);
        $post_data['ware_id'] = $old_ware_id;
        $post_data['new_goods_data'] = json_decode(json_encode($old_goods_data,true), true);
        $res = WashOrderBasicService::addGoodPlan($user_info, $post_data);
        foreach ($storage_goods as $key => $value) {
            $new_goods_data[$key]['goo_id'] = $value['goods_id'];
        }
        $post_data1['ware_id'] = $allData['cg_wareid'];
        $post_data1['new_goods_data'] = $new_goods_data;
        $res = WashOrderBasicService::addGoodPlan($user_info, $post_data1);
        if ($puor_id && $del_stgo_id && $stgo_id) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'编辑成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'编辑失败'];
        }
    }

    // 提交审核
    public static function submitAudit(
        $user_info,
        $cg_data,
        $shop_id
    ) {
        // 获取采购商品列表
        $storage_goods = DB::table('storage_goods')
            ->leftjoin('goods', 'goo_id', '=', 'goods_id')
            ->where('relation_number', $cg_data->cg_number)
            ->select('goo_class', 'goo_bra_name', 'goo_brse_id', 'goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_cate_name', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'goo_brse_id', 'goo_class', 'goo_goods_encode')
            ->get();
        $storage_goods = json_decode(json_encode($storage_goods), true);
        $sell_count = array_sum(array_column($storage_goods, 'goods_num'));
        // 生成销售单号
        $rule_data = DB::table('order_rule')
            ->where('orru_type', 4) //类型：1.订单编号规则 2.工单编号规则 3.采购单号规则 4.销售单规则
            ->where('orru_cid', $user_info->adm_cid)
            ->where('orru_superior_id', $shop_id) //总店
            ->first(['orru_number', 'orru_date', 'orru_id']);
        if ($rule_data) {
            // 有此总店的数据 判断是不是今天的
            if ($rule_data->orru_date == date('Y-m-d')) {
                // 采购单总量+1
                $order_rule = DB::table('order_rule')
                    ->where('orru_id', $rule_data->orru_id)
                    ->increment('orru_number');

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

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

            $today_order = 1; //今天的采购单总量
        }
        // XS+年月日时分秒是16位 销售单号共20位 所以补零的位数为4位
        $xs_number = 'XS' . date('YmdHis') . str_pad($today_order, 4, '0', STR_PAD_LEFT);
        if ($cg_data->puor_supplyunit_type == 2 && $user_info->shop_versions == 1) { //供货方类型1.供货单位2.运营中心3.供应链4.可来电
            // 运营中心生成销售单
            $shop_parent_id = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->value('shop_parent_id');
            $parent_shop = DB::table('shop')
                ->where('shop_id', $shop_parent_id)
                ->select('shop_cid', 'shop_superior_id', 'shop_store_name', 'shop_name', 'shop_phone')
                ->first();
            $sell_data['sell_cid'] = $parent_shop->shop_cid;
            $sell_data['sell_superior_shop_id'] = $parent_shop->shop_superior_id ? $parent_shop->shop_superior_id : $shop_parent_id;
            $sell_data['sell_shop_id'] = $shop_parent_id;
            $sell_data['sell_number'] = $xs_number; //单号
            $sell_data['sell_cg_id'] = $cg_data->cg_id; //采购单id
            $sell_data['sell_cg_shop_id'] = $user_info->adm_shop_id; //采购门店id
            $sell_data['sell_cg_number'] = $cg_data->cg_number; //采购单号
            $sell_data['sell_state'] = 2; //状态1保存/待提交2提交/待审核3通过/待出库4驳回5出库（6部分出库7异常出库 暂时不用）
            $sell_data['sell_count'] = $sell_count;
            $sell_data['sell_price'] = $cg_data->cg_amount * 100;
            $sell_data['sell_payment_way'] = 1;
            $sell_data['sell_chun_id'] = $cg_data->cg_shop_id;
            $sell_data['sell_actual_price'] = 0;
            $sell_data['sell_settlement_state'] = 4; //结算状态：1未结算2结算中3已结算4待审核
            $sell_data['sell_remark'] = $cg_data->cg_remark;
            $sell_data['sell_system_type'] = 1; //系统类型1自营2系统
            $sell_id =  DB::table('sell')->insertGetId($sell_data);
            foreach ($storage_goods as $key => $val) {
                // 查询商品名称和检索编码
                $goods_arr = Db::table('goods')
                    ->where('goo_id', $val['goods_id'])
                    ->whereIn('goo_type', [1, 2])
                    ->select('goo_id', 'goo_class', 'goo_goods_encode')
                    ->first();
                if (!$goods_arr) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'未知的商品，请重新填写采购单'];
                }
                // goo_class类型1自营商品2系统商品,goo_class为2的时候,在供应链添加数据
                if ($goods_arr->goo_class == '2') {
                    $temps = [];
                    $temps['sego_sell_id'] = $sell_id; //销售出库id
                    $temps['sego_goo_id'] = $goods_arr->goo_id; //商品id
                    $temps['sego_sell_number'] = $val['goods_num']; //销售数量
                    $temps['sego_sell_price'] = $val['univalence'] * 100; //销售金额
                    $temps['sego_update_time'] = date('Y-m-d H:i:s');
                    $sell_goods[] = $temps;
                } else {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'不是系统商品,无法添加采购单'];
                }
            }
            $sego_id =  DB::table('sell_goods')->insert($sell_goods);
            // 新增销售出库客户数据
            $find_shop = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->select('shop_store_name', 'shop_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address')
                ->first();
            $secl_data['secl_sell_id'] = $sell_id;
            $secl_data['secl_channel_unit'] = $find_shop->shop_store_name;
            $secl_data['secl_name'] = $find_shop->shop_name;
            $secl_data['secl_phone'] = $find_shop->shop_phone;
            $secl_data['secl_province'] = $find_shop->shop_province;
            $secl_data['secl_city'] = $find_shop->shop_city;
            $secl_data['secl_county'] = $find_shop->shop_county;
            $secl_data['secl_address'] = $find_shop->shop_address;
            $secl_data['secl_chun_id'] = $cg_data->cg_shop_id;
            $secl_data['secl_channel_type'] = 5; //客户单位类型:1.会员零售2.客户单位3.速电派单4.第三方派单5.运营中心与门店
            $secl_data['secl_update_time'] = date('Y-m-d H:i:s');
            $secl_id =  DB::table('sell_client')->insert($secl_data);
        } elseif ($cg_data->puor_supplyunit_type == 3) { //供应链生成销售单
            $sell_data['sell_cid'] = 1;
            $sell_data['sell_number'] = $xs_number; //单号
            $sell_data['sell_cg_id'] = $cg_data->cg_id; //采购单id
            $sell_data['sell_cg_number'] = $cg_data->cg_number; //采购单号
            $sell_data['sell_cg_shop_id'] = $user_info->adm_shop_id; //采购门店id
            $sell_data['sell_state'] = 7; //状态1保存/待提交2提交/待出库3出库4部分出库5异常出库6.终止7.下级门店提交/待审核8驳回
            $sell_data['sell_count'] = $sell_count;
            $sell_data['sell_price'] = $cg_data->cg_amount * 100;
            $sell_data['sell_payment_way'] = 1;
            $sell_data['sell_chun_id'] = $cg_data->cg_shop_id;
            $sell_data['sell_actual_price'] = 0;
            $sell_data['sell_remark'] = $cg_data->cg_remark;
            $sell_data['sell_settlement_state'] = 4; //结算状态：1未结算2结算中3已结算4待审核
            $sell_data['sell_system_type'] = 1; //系统类型1自营2系统
            $sell_id =  DB::connection('mysql_scm')->table('sell')->insertGetId($sell_data);
            foreach ($storage_goods as $key => $val) {
                // 查询商品名称和检索编码
                $goods_arr = Db::table('goods')
                    ->where('goo_id', $val['goods_id'])
                    ->whereIn('goo_type', [1, 2])
                    ->select('gyl_goo_id', 'goo_class', 'goo_goods_encode')
                    ->first();
                if (!$goods_arr) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'未知的商品，请重新填写采购单'];
                }
                // goo_class类型1自营商品2系统商品,goo_class为2的时候,在供应链添加数据
                if ($goods_arr->goo_class == '2') {
                    $temps = [];
                    $temps['sego_sell_id'] = $sell_id; //销售出库id
                    $temps['sego_goo_id'] = $goods_arr->gyl_goo_id; //商品id
                    $temps['sego_goo_goods_encode'] = $goods_arr->goo_goods_encode; //商品id
                    $temps['sego_sell_number'] = $val['goods_num']; //销售数量
                    $temps['sego_sell_price'] = $val['univalence'] * 100; //销售金额
                    $temps['sego_update_time'] = date('Y-m-d H:i:s');
                    $sell_goods[] = $temps;
                } else {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'不是系统商品，无法添加采购单'];
                }
            }
            $sego_id =  DB::connection('mysql_scm')->table('sell_goods')->insert($sell_goods);
            // 新增销售出库客户数据
            $find_shop = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->select('shop_store_name', 'shop_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address')
                ->first();
            $secl_data['secl_sell_id'] = $sell_id;
            $secl_data['secl_channel_unit'] = $find_shop->shop_store_name;
            $secl_data['secl_name'] = $find_shop->shop_name;
            $secl_data['secl_chun_id'] = $cg_data->cg_shop_id;
            $secl_data['secl_phone'] = $find_shop->shop_phone;
            $secl_data['secl_province'] = $find_shop->shop_province;
            $secl_data['secl_city'] = $find_shop->shop_city;
            $secl_data['secl_county'] = $find_shop->shop_county;
            $secl_data['secl_address'] = $find_shop->shop_address;
            $secl_data['secl_channel_type'] = 5; //客户单位类型:1.会员零售2.客户单位3.速电派单4.第三方派单5.运营中心与门店
            $secl_data['secl_update_time'] = date('Y-m-d H:i:s');
            $secl_id =  DB::connection('mysql_scm')->table('sell_client')->insert($secl_data);
        } else {
            $sell_id = true;
            $sego_id = true;
            $secl_id = true;
        }
        // 更改采购单状态
        $res = Db::table('purchase_order')
            ->where('cg_number', $cg_data->cg_number)
            ->where('is_del', 1)
            ->where('cg_state', 3)
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->update(['cg_state' => 1, 'auditor_user' => $user_info->adm_id, 'edit_time' => date('Y-m-d H:i:s')]);
      
        if ($sell_id && $sego_id && $secl_id && $res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'提交审核成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'提交审核失败'];
        }
    }

    /**
     * 验证是否自动过流程
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-03-14
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function autoNext($user_info, $request, $shop_id) {
        $find_set = DB::table('purchase_order_set')
            ->where('pos_shop_id', $user_info->adm_shop_id)
            ->first();
        if (!empty($find_set)) {
            $pos_set = json_decode($find_set->pos_set, true);
            usort($pos_set, function($a, $b) {
                return $a['type'] <=> $b['type']; // 根据age键排序，使用太空船操作符（PHP 7及以上版本）
            });
            foreach ($pos_set as $key => $value) {
                if ($value['type'] > $request['now_state']) {
                    if ($value['select'] == 1) {
                        break;
                    }
                    if ($value['type'] == 1) {//提交审核
                        // 获取采购单的数据
                        $cg_data = Db::table('purchase_order')
                            ->where('cg_number', $request['cg_number'])
                            ->where('is_del', 1)
                            ->where('company_id', $user_info->adm_cid)
                            ->where('cg_superior_shop_id', $user_info->adm_shop_id)
                            ->select('cg_state', 'cg_number', 'cg_id', 'puor_supplyunit_type', 'cg_amount', 'cg_shop_id', 'cg_remark')
                            ->first();
                        $submit_audit_res = PurchaseOrder::submitAudit($user_info, $cg_data, $shop_id);
                        if ($submit_audit_res['code'] != 200) {
                            return $submit_audit_res;
                        }
                    }

                    if ($value['type'] == 2) {//审核通过
                        $edit_data['cg_state'] = 5;
                        $edit_data['edit_time'] = date('Y-m-d H:i:s');
                        $edit_data['auditor_user'] = $user_info->adm_id;
                        $edit_data['cg_remark'] = '';
                        $res1 = DB::table('purchase_order')
                            ->where('cg_number', $request['cg_number'])
                            ->update($edit_data);
                    }

                    if ($value['type'] == 3) {//入库
                        $cg_data = DB::table('purchase_order')
                            ->where('cg_number', $request['cg_number'])
                            ->select('cg_id', 'cg_number', 'cg_settlementype', 'cg_yfmoney', 'cg_moling', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone', 'create_time', 'is_del')
                            ->first();
                        // $goods_data goods_id  wafr_id  num wfog_primary_id  wfog_type  wfog_outin_type
                        // is_del 是否删除1正常2删除
                        if ($cg_data->is_del != 1) {
                            return ['code'=>500, 'msg'=>'当前采购单已删除，无法入库！', 'data'=>'当前采购单已删除，无法入库！'];
                        }
                        $cg_data = json_decode(json_encode($cg_data), true);

                        // 查询采购单的商品数数据
                        $storage_goods = DB::table('storage_goods')
                            ->where('relation_number', $request['cg_number'])
                            ->select('goods_id', 'goods_number', 'storehouse', 'goods_name', 'cg_goodsnum', 'goods_num', 'univalence', 'ruku_num', 'company_id', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'old_univalence', 'stgo_stop')
                            ->get()->toArray();
                        foreach ($storage_goods as $key1 => $value1) {
                            // 查询商品id所在仓库，所在仓位库存，仓位库存有多到少
                            $find_wafr_data = DB::table('warehouse_freight_goods as wafg')
                                    ->leftjoin('warehouse_freight as wafr', 'wafg.wafg_wafr_id', '=', 'wafr.wafr_id')
                                    ->where('wafg_ware_id', $cg_data['cg_wareid'])
                                    ->where('wafg_class', 1)
                                    ->where('wafg_goo_id', $value1->goods_id)
                                    ->where(function ($query) use ($request) {
                                        $query->where('wafg_stock_number', '>', 0)
                                            ->orWhere('wafg_priority_stock_number', '>', 0);
                                    })
                                    ->select('wafr_id', 'wafr_name', 'wafr_rank')
                                    ->orderBy('wafg_stock_number', 'desc')
                                    ->orderBy('wafg_priority_stock_number', 'desc')
                                    ->get()->toArray();
                            if (empty($find_wafr_data)) {
                                // 查询仓位商品出入库表，查询商品入库的仓位历史记录
                                $find_wafr_data = DB::table('warehouse_freight_outin_goods as wfog')
                                    ->leftjoin('warehouse_freight as wafr', 'wfog.wfog_wafr_id', '=', 'wafr.wafr_id')
                                    ->where('wfog_ware_id', $cg_data['cg_wareid'])
                                    ->where('wfog_type', 1)//关联类型：1采购入库2采购退货出库
                                    ->where('wfog_goo_id', $value1->goods_id)
                                    ->select('wafr_id', 'wafr_name', 'wafr_rank')
                                    ->orderBy('wfog_id', 'desc')
                                    ->get()->toArray();

                                // 如果没有历史记录，查询仓库的仓位数据
                                if (empty($find_wafr_data)) {
                                    $find_wafr_data = DB::table('warehouse_freight')
                                        ->where('wafr_ware_id', $cg_data['cg_wareid'])
                                        ->where('wafr_shop_id', $user_info->adm_shop_id)
                                        ->where('wafr_delete', 1)//是否删除1否2是
                                        ->select('wafr_id', 'wafr_name', 'wafr_rank', 'wafr_shop_id')
                                        ->limit(10)
                                        ->get()->toArray();
                                }
                            }
                            $goods_data[$key1]['goods_id'] = $value1->goods_id;
                            $goods_data[$key1]['wafr_id'] = $find_wafr_data[0]->wafr_id;
                            $goods_data[$key1]['num'] = $value1->goods_num;
                            $goods_data[$key1]['estimate_time'] = date('Y-m-d H:i:s');
                        }

                        $storage_goods = json_decode(json_encode($storage_goods), true); //将对象转换为数组
                        $storage_goods = array_column($storage_goods, null, 'goods_id'); //商品id当做数组键值
                        $goods_id = array_unique(array_column($goods_data, 'goods_id')); //前端提交入库数据的商品id

                        $rk_number = 'RK' . rand(10, 99) . date('mdHis') . rand(100000, 999999); //单号
                        $request['rk_image'] = '';
                        $warehousing_retrun = WareInorder::warehousing(
                            $user_info, //用户信息
                            $shop_id, //门店id
                            $request, //用户信息
                            $goods_data, //提交的商品数据
                            $storage_goods, //查询采购单商品信息
                            $goods_id, //前端提交入库数据的商品id
                            $cg_data, //查询的采购单信息
                            $rk_number //入库单号
                        );
                        if ($warehousing_retrun['code'] != 200) {
                            return $warehousing_retrun;
                        }
                        //采购入库修改商品单价和总价
                        $WareInorderController = new WareInorderController();

                        $amount_ret = $WareInorderController->updateWagoAmountWare($storage_goods);
                        if($amount_ret['code'] != 200){
                            return $amount_ret;
                        }
                    }

                    if ($value['type'] == 4) {
                        $update_data['cg_state'] = 12; //采购单状态:确认完成
                        $update_data['edit_time'] = date('Y-m-d H:i:s');
                        $res = DB::table('purchase_order')
                            ->where('cg_number', $request['cg_number'])
                            ->update($update_data);
                    }
                }
            }
            return ['code'=>200, 'msg'=>'success', 'data'=>''];
        }
    }
}
