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

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use App\Http\Controllers\Api\Verify\Purchase\VerifyPurchasePlanController;

// 仓储系统 -- 采购计划
class PurchasePlanController extends Controller
{
    // 采购计划页面
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPurchasePlanController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

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

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

        $list = Db::table('purchase_order')
            ->leftjoin('channel_unit', 'chun_id', '=', 'cg_supplyunit')
            ->where('need_toexamine', 5)
            ->where('is_del', 1)
            ->where('purchase_order.company_id', $userinfo->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_number'])) {  //采购单号
                    $query->where('cg_number', 'like', '%' . $where_data['cg_number'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['contract_number'])) { //合同号
                    $query->where('contract_number', 'like', '%' . $where_data['contract_number'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['goods_name'])) { //包含商品
                    $query->where('goods_name', 'like', '%' . $where_data['goods_name'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['chun_unit_name'])) { //采购单位
                    // $query->where('vendor', $where_data['cg_supplyunit']);
                    $query->where('chun_unit_name', 'like', '%' . $where_data['chun_unit_name'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_wareid'])) { //仓库
                    $query->where('cg_wareid', $where_data['cg_wareid']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_creator'])) {  //创建人
                    $query->where('cg_creator', 'like', '%' . $where_data['cg_creator'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['amount_start'])) {
                    $query->where('cg_amount', '>=', $where_data['amount_start']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['amount_end'])) {
                    $query->where('cg_amount', '<=', $where_data['amount_end']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['create_start'])) {
                    $query->where('create_time', '>=', $where_data['create_start']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['create_end'])) {
                    $query->where('create_time', '<=', $where_data['create_end'] . ' 23:59:59');
                }
            })
            ->where(function ($query) use ($where_data, $wareInArr) {
                if (!empty($where_data['dh_start']) || !empty($where_data['dh_end'])) {  //判断是否有到货时间，如果有到货时间，则添加该判断
                    $query->whereIn('cg_number', $wareInArr);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_supplyunit'])) { //采购单位
                    $query->where('cg_supplyunit', $where_data['cg_supplyunit']);
                }
            })
            ->select('cg_number', 'contract_number', 'cg_yfmoney', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_amount', 'cg_remark', 'chun_unit_name', 'cg_creator', 'create_time', 'cg_delivertype', 'cg_invoicetype', 'cg_settlementype', 'business_type', 'auditor_user', 'contact_name', 'contact_phone')
            ->orderBy('create_time', 'desc')
            ->paginate($page_size);

        $data = $list->items();
        $page_arr = [
            'page_count' => $list->lastPage(),  //总页数
            'page' => $list->currentPage(),     //当前页
            'page_size' => $page_size,          //每页条数
            'data_count' => $list->total(),     //总条数
        ];

        if ($data) {
            $warehoust = Db::table('warehouse')->pluck('ware_name', 'ware_id');
            $data = json_decode(json_encode($data), true);
            foreach ($data as $key => $val) {
                $data[$key]['ware_name'] = $warehoust[$val['cg_wareid']];

                if ($val['auditor_user'] == 0) {
                    $data[$key]['auditor_user'] = '';
                } else {
                    $data[$key]['auditor_user'] = Db::table('admin')
                        ->where('adm_id', $val['auditor_user'])
                        ->value('adm_name');
                }
                $goods = DB::table('storage_goods')
                    ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                    ->where('relation_number', $val['cg_number'])
                    ->select('goo_brse_id', 'goo_class', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'goo_brse_id', 'goo_class')
                    ->orderBy('ruku_num', 'asc')
                    ->get()->toArray();
                $goods = json_decode(json_encode($goods), true);
                // 查询系列数据
                $goo_brse_id = array_column($goods, 'goo_brse_id');
                $brse_data = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->pluck('brse_name', 'brse_id')
                    ->toArray();
                $goods_num = 0;
                foreach ($goods as $k => $v) {
                    $goods_num = $goods_num + $v['goods_num'];
                    // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                    if (!in_array($userinfo->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                        if (!empty($v['goo_brse_id'])) {
                            if ($v['goo_class'] == 2) {
                                $goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                unset($v['goo_brse_id']);
                            } else {
                                if (!in_array($userinfo->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                    $goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                    unset($v['goo_brse_id']);
                                }
                            }
                        }
                    }
                    // 显示品牌名称
                    if (!in_array($userinfo->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                        if ($v['goo_class'] == 2) {
                            $goods[$k]['goo_name'] = $v['goo_bra_name']. ' ' . $goods[$k]['goo_name'];
                        } else {
                            if (!in_array($userinfo->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $goods[$k]['goo_name'] = $v['goo_bra_name']. ' ' . $goods[$k]['goo_name'];
                            }
                        }
                    }
                }
                // 获取备注
                $note = DB::table('note')
                    ->where('note_number', $val['cg_number'])
                    ->select('note_id', 'note_content', 'note_time')
                    ->orderBy('note_id', 'desc')
                    ->get();

                $data[$key]['goods_count']  = $goods_num;
                $data[$key]['storage_goods'] = $goods;
                $data[$key]['note'] = $note;
            }
        }

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);

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

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

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

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

        // 添加采购计划前
        if ($request['type'] == 1) {
            // 生成采购单号
            $rule_data = DB::table('order_rule')
                ->where('orru_type', 3) //类型：1.订单编号规则 2.工单编号规则 3.采购单号规则
                ->where('orru_cid', $userinfo->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'] = $userinfo->adm_cid;
                $orru_data['orru_superior_id'] = $shop_id;
                $orru_data['orru_shop_id'] = $userinfo->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; //今天的工单总量
            }
            // 年月日时分秒是14位 采购单号共20位 所以补零的位数为4位
            $cg_number = 'CG' . date('YmdHis') . str_pad($today_order, 4, '0', STR_PAD_LEFT);

            // 生成合同单号
            $contract_number = time() . rand(10000, 99999);
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => ['cg_number' => $cg_number, 'contract_number' => $contract_number]]);
        }

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

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

        // 合同单号
        $allData['contract_number'] = time() . rand(10000, 99999);

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

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

        // 给采购表的数据赋值
        $cg_data = [];
        // 基本信息
        $cg_data['company_id'] = $userinfo->adm_cid;
        $cg_data['cg_userid'] = $userinfo->adm_id;
        $cg_data['cg_creator'] = $userinfo->adm_name;
        $cg_data['cg_superior_shop_id'] = $shop_id;
        $cg_data['cg_shop_id'] = $userinfo->adm_shop_id;
        $cg_data['cg_number'] = $allData['cg_number']; //单号
        $cg_data['contract_number'] = $allData['contract_number']; //合同单号
        $cg_data['cg_purchasetime'] = $allData['cg_purchasetime']; //采购日期
        $cg_data['business_type'] = $allData['business_type']; //业务类型1普通采购2样品采购
        $cg_data['cg_wareid'] = $allData['cg_wareid']; //仓库id
        $cg_data['cg_waon_class'] = $allData['cg_waon_class']; //仓库类别
        $cg_data['cg_remark'] = $allData['cg_remark']; //备注
        // 供货方
        $cg_data['cg_supplyunit'] = $allData['cg_supplyunit']; //供货单位
        $cg_data['contact_name'] = $allData['contact_name']; //联系人
        $cg_data['contact_phone'] = $allData['contact_phone']; //联系电话
        // 结算信息
        $cg_data['cg_paymentype'] = $allData['cg_paymentype']; //结算方式1现金2定期3款到发货4货到付款5月结15天6月结30天7月结60天
        $cg_data['cg_paytype'] = 1; //是否账单结算1否是
        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']; //票据类型0不开票1普通发票2专用发票
        $cg_data['cg_amount'] = $allData['cg_amount']; //采购金额
        $cg_data['cg_settlementype']   = 4; //结算状态1正常 待生成账单2待结算3已结算4待审核
        $cg_data['need_toexamine'] = 5;
        $cg_data['create_time'] = date('Y-m-d H:i:s');
        $cg_data['cg_state'] = 3;

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

        // 商品信息
        $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
            if ($cg_data['cg_amount'] <= '0' || $temp['univalence'] <= '0') {
                $temp['old_univalence'] = 0;
            } else {
                $temp['old_univalence'] = round($cg_data['cg_amount'] / $total_value * $temp['univalence'], 2);
            }

            if ($temp['goods_num'] < 1) {
                continue;
            }
            $temp['relation_number'] = $cg_data['cg_number'];
            $temp['storehouse']     = $cg_data['cg_wareid'];
            $temp['ruku_num']       = 0;
            $temp['goods_type']     = $val['goo_type'];
            $temp['creator']        = $userinfo->adm_name;

            $temp['create_time'] = date('Y-m-d H:i:s');
            $temp['company_id'] = $userinfo->adm_id;

            $goods_Arr = Db::table('goods')
                ->where('goo_id', $val['goods_id'])
                ->select('goo_name', 'goo_goods_encode', 'goo_class')
                ->first();
            if ($goods_Arr->goo_class == 1) {//类型：1自营商品2系统商品
                // 查询商品附属表
                $goaf_another_name = DB::table('goods_affiliate')
                    ->where('goaf_goo_id', $val['goods_id'])
                    ->where('goaf_shop_id', $userinfo->adm_shop_id)
                    ->value('goaf_another_name');
                if (!empty($goaf_another_name)) {
                    $goods_Arr->goo_name = $goaf_another_name;
                }
            } else {
                // 查询系统商品属性表
                $gosa_another_name = DB::table('goods_system_affiliate')
                    ->where('gosa_goo_id', $val['goods_id'])
                    ->where('gosa_shop_id', $userinfo->adm_shop_id)
                    ->value('gosa_another_name');
                if (!empty($gosa_another_name)) {
                    $goods_Arr->goo_name = $gosa_another_name;
                }
            }
            $goods_Arr = json_decode(json_encode($goods_Arr), true);
            if (!$goods_Arr) {
                return response()->json(['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 response()->json(['code' => 500, 'msg' => 'error', 'data' => '商品不能为空,请重新填写采购单']);
        }

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

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

        $res1 = DB::table('purchase_order')->insert($cg_data);
        $res2 = DB::table('storage_goods')->insert($storage_goods);

        if ($res1 && $res2) {
            DB::commit();
            Common::addLog($userinfo, getRealIp($request), '采购管理', '添加采购单', $cg_data['cg_number'] . '成功');
            if ($cg_data['cg_remark'] != '') {
                Common::addNote($userinfo, $shop_id, $cg_data['cg_number'], $cg_data['cg_remark'], '添加采购单');
            }
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '添加成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '添加失败']);
        }
    }

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

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

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

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

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

        if ($request['type'] == 1) {
            // 获取供应商名称
            $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('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'goo_brse_id', 'goo_class')
                ->get();
            $storage_goods = json_decode(json_encode($storage_goods), true);
            // 查询系列数据
            $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($storage_goods as $k => $v) {
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($userinfo->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($v['goo_brse_id'])) {
                        if ($v['goo_class'] == 2) {
                            $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                            unset($v['goo_brse_id']);
                        } else {
                            if (!in_array($userinfo->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                unset($v['goo_brse_id']);
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($userinfo->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($v['goo_class'] == 2) {
                        $storage_goods[$k]['goo_name'] = $v['goo_bra_name']. ' ' . $storage_goods[$k]['goo_name'];
                    } else {
                        if (!in_array($userinfo->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $storage_goods[$k]['goo_name'] = $v['goo_bra_name']. ' ' . $storage_goods[$k]['goo_name'];
                        }
                    }
                }
            }
            if (!in_array($puor_data['cg_state'], [1, 3])) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '状态已发生改变,该状态无法编辑']);
            }

            unset($puor_data['cg_state']);

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

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

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

        if (!in_array($puor_data['cg_state'], [1, 3])) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '状态已发生改变,该状态无法编辑']);
        }

        if ($puor_data['need_toexamine'] != 5) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '采购计划已发生变化,请刷新页面']);
        }

        // 验证合同单号是否重复
        $newcg_id = DB::table('purchase_order')
            ->where('cg_id', '!=', $puor_data['cg_id'])
            ->where('company_id', $userinfo->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where('contract_number', $allData['contract_number'])
            ->value('cg_id');
        if ($newcg_id) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '合同单号重复']);
        }

        $goods_data = $allData['goods'];
        unset($allData['goods']);
        $cg_data = [];
        $cg_data['cg_state']       = 3;
        $cg_data['need_toexamine'] = 1;
        $cg_data['cg_amount']      = $allData['cg_amount'];
        $cg_data['cg_purchasetime'] = $allData['cg_purchasetime'];
        $cg_data['contract_number'] = $allData['contract_number'];
        $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_paytype'] = 1; //是否账单结算1否是
        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'];
        $cg_data['cg_wareid']      = $allData['cg_wareid'];
        $cg_data['cg_waon_class']  = $allData['cg_waon_class'];
        $cg_data['contact_phone']  = $allData['contact_phone'];
        $cg_data['cg_remark']      = $allData['cg_remark'];
        $cg_data['contact_name']   = $allData['contact_name'];
        $cg_data['cg_settlementype']   = 4; //结算状态1正常 待生成账单2待结算3已结算4待审核
        $cg_data['create_time']   = date('Y-m-d H:i:s');

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

        $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 ($allData['cg_amount'] <= 0 || $temp['univalence'] <= 0) {
                $temp['old_univalence'] = 0;
            } else {
                $temp['old_univalence'] = round($allData['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'];
            $temp['ruku_num']       = 0;
            $temp['goods_type']     = isset($val['goods_type']) ? $val['goods_type'] : $val['goo_type'];
            $temp['creator']        = $userinfo->adm_name;

            $temp['create_time'] = date('Y-m-d H:i:s');
            $temp['company_id'] = $userinfo->adm_cid;

            $goods_Arr = Db::table('goods')
                ->where('goo_id', $val['goods_id'])
                ->select('goo_name', 'goo_goods_encode', 'goo_class')
                ->first();
            if ($goods_Arr->goo_class == 1) {//类型：1自营商品2系统商品
                // 查询商品附属表
                $goaf_another_name = DB::table('goods_affiliate')
                    ->where('goaf_goo_id', $val['goods_id'])
                    ->where('goaf_shop_id', $userinfo->adm_shop_id)
                    ->value('goaf_another_name');
                if (!empty($goaf_another_name)) {
                    $goods_Arr->goo_name = $goaf_another_name;
                }
            } else {
                // 查询系统商品属性表
                $gosa_another_name = DB::table('goods_system_affiliate')
                    ->where('gosa_goo_id', $val['goods_id'])
                    ->where('gosa_shop_id', $userinfo->adm_shop_id)
                    ->value('gosa_another_name');
                if (!empty($gosa_another_name)) {
                    $goods_Arr->goo_name = $gosa_another_name;
                }
            }
            $goods_Arr = json_decode(json_encode($goods_Arr), true);
            if (!$goods_Arr) {
                return response()->json(['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 response()->json(['code' => 500, 'msg' => 'error', 'data' => '商品不能为空,请重新填写采购单']);
        }

        $cg_data['goods_name'] = $goods_name;
        $cg_data['edit_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();

        DB::connection()->enableQueryLog();
        $res1 = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->update($cg_data);
        $res2 = DB::table('storage_goods')
            ->where('relation_number', $cg_number)
            ->delete();
        $res3 = DB::table('storage_goods')->insert($storage_goods);

        if ($res1 && $res2 && $res3) {
            DB::commit();
            Common::addLog($userinfo, getRealIp($request), '采购计划管理', '转采购单', $puor_data['cg_number'] . '成功');
            if ($puor_data['cg_remark'] != '') {
                Common::addNote($userinfo, $shop_id, $cg_number, $cg_data['cg_remark'], '转采购单');
            }
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '转采购成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '转采购失败']);
        }
    }

    // 导出
    public function exportExcel(Request $request)
    {
        // 获取当前操作账号信息
        $userinfo = Common::getUserInfo($request['api_token']);

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

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

        $data = Db::table('purchase_order')
            ->leftjoin('channel_unit', 'chun_id', '=', 'cg_supplyunit')
            ->where('need_toexamine', 5)
            ->where('is_del', 1)
            ->where('purchase_order.company_id', $userinfo->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_number'])) {  //采购单号
                    $query->where('cg_number', 'like', '%' . $where_data['cg_number'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['contract_number'])) { //合同号
                    $query->where('contract_number', 'like', '%' . $where_data['contract_number'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['goods_name'])) { //包含商品
                    $query->where('goods_name', 'like', '%' . $where_data['goods_name'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['chun_unit_name'])) { //采购单位
                    $query->where('chun_unit_name', 'like', '%' . $where_data['chun_unit_name'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_wareid'])) { //仓库
                    $query->where('cg_wareid', $where_data['cg_wareid']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_creator'])) {  //创建人
                    $query->where('cg_creator', 'like', '%' . $where_data['cg_creator'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['amount_start'])) {
                    $query->where('cg_amount', '>=', $where_data['amount_start']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['amount_end'])) {
                    $query->where('cg_amount', '<=', $where_data['amount_end']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['create_start'])) {
                    $query->where('create_time', '>=', $where_data['create_start']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['create_end'])) {
                    $query->where('create_time', '<=', $where_data['create_end'] . ' 23:59:59');
                }
            })
            ->where(function ($query) use ($where_data, $wareInArr) {
                if (!empty($where_data['dh_start']) || !empty($where_data['dh_end'])) {  //判断是否有到货时间，如果有到货时间，则添加该判断
                    $query->whereIn('cg_number', $wareInArr);
                }
            })
            ->select('cg_number', 'contract_number', 'cg_paymentype', 'cg_purchasetime', 'cg_amount', 'cg_remark', 'chun_unit_name', 'contact_name', 'contact_phone', 'cg_creator', 'create_time', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'cg_wareid')
            ->orderBy('cg_id', 'desc')
            ->get()->toArray();

        if (!empty($data)) {
            // 将对象转为数组
            $data = json_decode(json_encode($data), true);
            foreach ($data as $key => $value) {
                if ($value['cg_wareid']) {
                    $ware_id[] = $value['cg_wareid'];
                }
            }
            if (isset($adm_id)) {
                $adm_id = array_unique($adm_id);
                // 查找账号id对应的账号姓名
                $admin = DB::table('admin')->whereIn('adm_id', $adm_id)->pluck('adm_name', 'adm_id');
            } else {
                $adm_id = '';
                $admin = '';
            }

            $ware_id = array_unique($ware_id);
            $warehouse = DB::table('warehouse')->whereIn('ware_id', $ware_id)->pluck('ware_name', 'ware_id');
            foreach ($data as $key => $value) {
                $data[$key]['cg_wareid'] = $warehouse[$value['cg_wareid']];
                // 付款方式
                if ($value['cg_paymentype'] == 1) {
                    $data[$key]['cg_paymentype'] = '现金';
                }
                if ($value['cg_paymentype'] == 2) {
                    $data[$key]['cg_paymentype'] = '定期';
                }
                if ($value['cg_paymentype'] == 3) {
                    $data[$key]['cg_paymentype'] = '款到发货';
                }
                if ($value['cg_paymentype'] == 4) {
                    $data[$key]['cg_paymentype'] = '货到付款';
                }
                if ($value['cg_paymentype'] == 5) {
                    $data[$key]['cg_paymentype'] = '月结15天';
                }
                if ($value['cg_paymentype'] == 6) {
                    $data[$key]['cg_paymentype'] = '月结30天';
                }
                if ($value['cg_paymentype'] == 7) {
                    $data[$key]['cg_paymentype'] = '月结60天';
                }
                if ($value['cg_paymentype'] == 8) {
                    $data[$key]['cg_paymentype'] = '免费';
                }
                // 业务类型
                if ($value['business_type'] == '0') {
                    $data[$key]['business_type'] = '无';
                }
                if ($value['business_type'] == 1) {
                    $data[$key]['business_type'] = '普通采购';
                }
                if ($value['business_type'] == 2) {
                    $data[$key]['business_type'] = '样品采购';
                }
                if ($value['business_type'] == 3) {
                    $data[$key]['business_type'] = '厂家返利';
                }
                // 交货方式
                if ($value['cg_delivertype'] == 1) {
                    $data[$key]['cg_delivertype'] = '送货上门';
                }
                if ($value['cg_delivertype'] == 2) {
                    $data[$key]['cg_delivertype'] = '自提';
                }
                // 票据方式
                if ($value['cg_invoicetype'] == 0) {
                    $data[$key]['cg_invoicetype'] = '不开票';
                }
                if ($value['cg_invoicetype'] == 1) {
                    $data[$key]['cg_invoicetype'] = '普通发票';
                }
                if ($value['cg_invoicetype'] == 2) {
                    $data[$key]['cg_invoicetype'] = '专用发票';
                }
            }
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '暂无导出数据']);
        }

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

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

        $where['action_name'] = '采购计划列表';
        $where['field_name'] = ['采购单号', '合同单号', '结算方式', '采购日期', '采购总价', '采购备注', '供货单位', '联系人',  '联系电话', '添加人', '添加时间', '交货方式', '票据类型', '业务类型', '仓库'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

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