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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountControl\VerifyVoucherReceiptsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use Psy\VarDumper\Dumper;
use App\Http\Models\Api\YongYou;
use App\Http\Models\Api\YongYous;

// 财务系统 -- 凭证列表
class VoucherReceiptsController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVoucherReceiptsController;
        $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('voucher_receipts as vore')
            ->where('vore_cid', $user_info->adm_cid)
            ->where('vore_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) { //订单/工单/采购单号
                if (!empty($search_data['vore_order_number'])) {
                    $query->where('vore_ord_number', 'like', '%' . $search_data['vore_order_number'] . '%')
                        ->orwhere('vore_wor_number', 'like', '%' . $search_data['vore_order_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //单位类型1会员零售2客户单位3速电派单
                if (!empty($search_data['vore_type'])) {
                    $query->where('vore_type', $search_data['vore_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户单位
                if (!empty($search_data['vore_channel_unit'])) {
                    $query->where('vore_channel_unit', 'like', '%' . $search_data['vore_channel_unit'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //状态1未同步2已同步
                if (!empty($search_data['vore_state'])) {
                    $query->where('vore_state', $search_data['vore_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('vore_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('vore_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('vore_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //单号类型
                if (!empty($search_data['vore_order_type'])) {
                    $query->where('vore_order_type', $search_data['vore_order_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户单位id
                if (!empty($search_data['vore_client_id'])) {
                    $query->where('vore_client_id', $search_data['vore_client_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //买家类型:1会员零售2客户单位3速电派单
                if (!empty($search_data['vore_type'])) {
                    $query->where('vore_type', $search_data['vore_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
                if (!empty($search_data['vore_service_type'])) {
                    $query->where('vore_service_type', $search_data['vore_service_type']);
                }
            })
            ->select('vore_id', 'vore_order_type', 'vore_wor_id', 'vore_wor_number', 'vore_ord_id', 'vore_ord_number', 'vore_actual_price', 'vore_collection_price', 'vore_recycle_price', 'vore_plus_minus', 'vore_type', 'vore_channel_unit', 'vore_create_time', 'vore_state', 'vore_early_costing', 'vore_client_id', 'vore_service_type')
            ->orderBy('vore_create_time', 'desc')
            ->paginate($this->show_count);

        $list_items = $list_data->items();
        if ($list_items) {
            $vore_id = array_column($list_items, 'vore_id'); //凭证id
            $ord_id = array_column($list_items, 'vore_ord_id'); //订单id
            // 查询凭证借贷表信息
            $volo_data = DB::table('voucher_loan')
                ->whereIn('volo_vore_id', $vore_id)
                ->select('volo_vore_id', 'volo_type', 'volo_borrow_subject', 'volo_borrow_subject_name', 'volo_borrow_price', 'volo_loan_subject', 'volo_loan_subject_name', 'volo_loan_price', 'volo_borrow_costing', 'volo_borrow_costing_subject', 'volo_borrow_costing_name', 'volo_loan_costing', 'volo_loan_costing_subject', 'volo_loan_costing_name')
                ->get();
            // 查询备注信息
            $order_reamrks = DB::table('order_remarks')
                ->whereIn('orre_ord_id', $ord_id)
                ->select('orre_create_adm_name', 'orre_content', 'orre_time', 'orre_ord_id')
                ->orderby('orre_id', 'desc')
                ->get();
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->select('chun_id', 'chun_unit_name')
                ->get();
            $channel = json_decode(json_encode($channel), true);
            foreach ($channel as $k => $v) {
                $channel_name[$v['chun_id']] = $v['chun_unit_name'];
            }
            foreach ($list_items as $key => $value) {
                // 客户单位名称
                if (isset($channel_name[$value->vore_client_id])) {
                    $list_items[$key]->vore_channel_unit = $channel_name[$value->vore_client_id];
                } else {
                    $list_items[$key]->vore_channel_unit = $value->vore_channel_unit;
                }
            }
        } else {
            $volo_data = [];
            $order_reamrks = [];
        }

        $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['volo_data'] = $volo_data;                //订单商品数据
        $data_info['order_reamrks'] = $order_reamrks;                //订单商品数据

        // 获取当前列表下的按钮
        $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 VerifyVoucherReceiptsController;
        $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;

        // 查找凭证列表
        $find_vore_data = DB::table('voucher_receipts')
            ->where('vore_id', $request['vore_id'])
            ->select('vore_order_type', 'vore_wor_id', 'vore_wor_number', 'vore_ord_id', 'vore_ord_number')
            ->first();
        // vore_order_type 单号类型1.订单2.工单3.采购单4.销售单
        if ($find_vore_data->vore_order_type == 1) { //订单详情
            // 查询服务项目id
            $info = DB::table('order as ord')
                ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                ->where('ord_id', $find_vore_data->vore_ord_id)
                ->select('ord_service_sepr_id', 'orcl_rescue_service_price')
                ->first();
            // 根据服务项目id,查询服务名称
            if ($info->ord_service_sepr_id != '0') {
                $sepr_data = DB::table('service_project')
                    ->where('sepr_id', $info->ord_service_sepr_id)
                    ->select('sepr_name', 'sepr_order_money')
                    ->first();
                $info->ord_service_sepr_name = $sepr_data->sepr_name;
                $info->sepr_order_money = $info->orcl_rescue_service_price;
                unset($info->ord_service_sepr_id);
                unset($info->orcl_rescue_service_price);
            } else {
                unset($info->ord_service_sepr_id);
                $info = '';
            }
            // 查询商品信息
            $goods_data = DB::table('order_goods')
                ->where('orgo_ord_id', $find_vore_data->vore_ord_id)
                ->where('orgo_state', '!=', 2)
                ->select('orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity', 'orgo_goo_price', 'orgo_is_recycle', 'orgo_can_assign_quantity', 'orgo_collection_price', 'orgo_goo_inventory', 'orgo_state', 'orgo_goo_type', 'orgo_recycle_price', 'orgo_recycle_quantity', 'orgo_tem_goo_name as tem_goo_name', 'orgo_assign_price')
                ->get();
        } elseif ($find_vore_data->vore_order_type == 2) { //工单详情
            // 查询服务项目id
            $info = DB::table('work_order as wor')
                ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                ->where('wor_id', $find_vore_data->vore_wor_id)
                ->select('wor_service_sepr_id', 'wocl_rescue_service_price')
                ->first();
            // 根据服务项目id,查询服务名称
            if ($info->wor_service_sepr_id != '0') {
                $sepr_data = DB::table('service_project')
                    ->where('sepr_id', $info->wor_service_sepr_id)
                    ->select('sepr_name', 'sepr_order_money')
                    ->first();
                $info->ord_service_sepr_name = $sepr_data->sepr_name;
                $info->sepr_order_money = $info->wocl_rescue_service_price;
                unset($info->wor_service_sepr_id);
                unset($info->wocl_rescue_service_price);
            } else {
                unset($info->wor_service_sepr_id);
            }
            $goods_data = DB::table('work_good')
                ->where('wogo_wor_id', $find_vore_data->vore_wor_id)
                ->where('wogo_state', '!=', 2)
                ->select('wogo_goo_id', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_price', 'wogo_goo_amount', 'wogo_is_recycle', 'wogo_actual_recycle_number', 'wogo_remark', 'wogo_id', 'wogo_collection_price', 'wogo_goo_inventory', 'wogo_state', 'wogo_recycle_price', 'wogo_goo_type', 'wogo_recycle_quantity', 'wogo_tem_goo_name as tem_goo_name', 'wogo_assign_price')
                ->get();
        } elseif ($find_vore_data->vore_order_type == 3 || $find_vore_data->vore_order_type == 5) { //采购单详情
            $info = '';
            $goods_data = DB::table('storage_goods')
                ->where('relation_number', $find_vore_data->vore_ord_number)
                ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                ->select('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type as goo_type', 'stgo_stop')
                ->get();
        } elseif ($find_vore_data->vore_order_type == 4) {
            $goods_data = DB::table('order_goods')
                ->where('orgo_ord_id', $find_vore_data->vore_ord_id)
                ->where('orgo_state', '!=', 2)
                ->select('orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity', 'orgo_goo_price', 'orgo_is_recycle', 'orgo_can_assign_quantity', 'orgo_collection_price', 'orgo_goo_inventory', 'orgo_state', 'orgo_goo_type', 'orgo_recycle_price', 'orgo_recycle_quantity', 'orgo_tem_goo_name as tem_goo_name', 'orgo_assign_price')
                ->get();
        } elseif ($find_vore_data->vore_order_type == 6) {
            // 盘库单数据
            $find_stoc = DB::table('stocktake as a')
                ->leftJoin('admin as b', 'b.adm_id', '=', 'a.stoc_adm_id')
                ->leftJoin('warehouse as c', 'c.ware_id', '=', 'a.stoc_ware_id')
                ->where('stoc_id', $find_vore_data->vore_ord_id)
                ->select('adm_name', 'ware_name', 'stoc_make_time', 'stoc_state', 'stoc_type', 'stoc_storage_number', 'stoc_differ_number')
                ->first();
            // 获取盘库商品数据
            $find_goods = DB::table('stocktake_goods as a')
                ->leftJoin('goods as b', 'a.stgo_goo_id', '=', 'b.goo_id')
                ->where('stgo_stoc_id', $find_vore_data->vore_ord_id)
                ->select('stgo_stock_number', 'stgo_lock_number', 'stgo_stocktake_number', 'goo_name', 'goo_type', 'goo_goods_encode', 'stgo_priority_stock_number', 'stgo_priority_lock_number', 'stgo_unchecked_stock_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stocktake_number')
                ->get();
            $data['stoc_data'] = $find_stoc;
            $find_goods = json_decode(json_encode($find_goods), true);
            foreach ($find_goods as $key => $value) {
                $find_goods[$key]['stgo_stocktake_number'] = $value['stgo_stock_number'] + $value['stgo_lock_number'] + $value['stgo_stocktake_number'];
                $find_goods[$key]['stgo_priority_stocktake_number'] = $value['stgo_priority_stocktake_number'] + $value['stgo_priority_stock_number'] + $value['stgo_priority_lock_number'];
                $find_goods[$key]['stgo_unchecked_stocktake_number'] = $value['stgo_unchecked_stocktake_number'] + $value['stgo_unchecked_stock_number'];
            }
            $data['goods_data'] = $find_goods;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }
        $data['info'] = $info;
        $data['goods_data'] = $goods_data;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 备注
    public function remarks(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVoucherReceiptsController;
        $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;

        // 查找凭证列表
        $find_vore_data = DB::table('voucher_receipts')
            ->where('vore_id', $request['vore_id'])
            ->select('vore_order_type', 'vore_wor_id', 'vore_wor_number', 'vore_ord_id', 'vore_ord_number')
            ->first();
        // vore_order_type 单号类型1.订单2.工单3.采购单4.销售单
        if ($find_vore_data->vore_order_type == 1) { //订单详情
            $remarks_data = DB::table('order_remarks')
                ->where('orre_cid', $user_info->adm_cid)
                ->where('orre_shop_id', $user_info->adm_shop_id)
                ->where('orre_ord_id', $find_vore_data->vore_ord_id)
                ->select('orre_content', 'orre_create_adm_name', 'orre_create_adm_id', 'orre_time', 'orre_module')
                ->get();
        } elseif ($find_vore_data->vore_order_type == 2) { //工单详情
            $remarks_data = DB::table('order_remarks')
                ->where('orre_cid', $user_info->adm_cid)
                ->where('orre_shop_id', $user_info->adm_shop_id)
                ->where('orre_wor_id', $find_vore_data->vore_wor_id)
                ->select('orre_content', 'orre_create_adm_name', 'orre_create_adm_id', 'orre_time', 'orre_module')
                ->get();
        } elseif ($find_vore_data->vore_order_type == 3 || $find_vore_data->vore_order_type == 5) { //采购单详情
            $remarks_data = DB::table('note')
                ->where('note_adm_cid', $user_info->adm_cid)
                ->where('note_superior_shop_id', $shop_id)
                ->where('note_shop_id', $user_info->adm_shop_id)
                ->where('note_number', $find_vore_data->vore_ord_number)
                ->select('note_adm_id as orre_create_adm_id', 'note_name as orre_create_adm_name', 'note_content as orre_content', 'note_time as orre_time', 'note_type')
                ->get();
            foreach ($remarks_data as $key => $value) {
                $remarks_data[$key]->orre_module = $remarks_data[$key]->note_type;
            }
        } elseif ($find_vore_data->vore_order_type == 4) {
            //
        }
        $data['remarks_data'] = $remarks_data;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 删除
    public function delete(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;


        $find_vore_data = DB::table('voucher_receipts as vore')
            ->leftjoin('voucher_loan as volo', 'volo.volo_vore_id', '=', 'vore.vore_id')
            ->where('vore_cid', $user_info->adm_cid)
            ->where('vore_superior_shop_id', $shop_id)
            ->where('vore_state', 1)
            ->where('vore_order_type', 6)
            ->get()->toArray();
        if (empty($find_vore_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有可删除的凭证数据']);
        }

        DB::beginTransaction();

        $vore_id = array_column($find_vore_data, 'vore_id');
        // 先删除凭证借贷表数据
        $volo_res = DB::table('voucher_loan as b')
            ->leftjoin('voucher_receipts as a', 'a.vore_id', '=', 'b.volo_vore_id')
            ->where('vore_cid', $user_info->adm_cid)
            ->where('vore_superior_shop_id', $shop_id)
            ->whereIn('vore_id', $vore_id)
            ->delete();
        // 再删除凭证单据表数据
        $vore_res = DB::table('voucher_receipts')
            ->where('vore_cid', $user_info->adm_cid)
            ->where('vore_superior_shop_id', $shop_id)
            ->whereIn('vore_id', $vore_id)
            ->delete();
        if ($volo_res && $vore_res) {
            DB::commit();
            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'=>'删除失败']);
        }
    }

    // 业务凭证同步U8
    public function sync(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVoucherReceiptsController;
        $error_message = $verify_data->syncValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        ignore_user_abort();
        set_time_limit(0);

        // 判断当前业务凭证是否存在
        $vore_data = DB::table('voucher_receipts')
            ->whereIn('vore_id', $request['vore_id'])
            ->where('vore_state', 1)
            ->select('vore_id', 'vore_order_type', 'vore_wor_id', 'vore_wor_number', 'vore_ord_id', 'vore_ord_number', 'vore_type', 'vore_client_id', 'vore_channel_unit', 'vore_actual_price', 'vore_early_costing', 'vore_plus_minus', 'vore_recycle_price', 'vore_state')
            ->get()->toArray();
        if (empty($vore_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前业务凭证不存在']);
        }

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

        if (empty($request['now_date'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择同步U8时间']);
        }
        $now_date = $request['now_date'];

        $vore_ord_numbers = '';
        foreach ($vore_data as $key => $value) {
            if ($value->vore_order_type == '2') {
                $value->vore_ord_number = $value->vore_wor_number;
                $vore_ord_number[] = $value->vore_wor_number;
            } else {
                $value->vore_ord_number = $value->vore_ord_number;
                $vore_ord_number[] = $value->vore_ord_number;
            }
            if ($value->vore_state == '2') {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$value->vore_ord_number . '当前凭证已同步U8']);
            }
            // 根据凭证id查询对应的借贷关系
            $find_volo_data = DB::table('voucher_loan')
                ->where('volo_shop_id', $user_info->adm_shop_id)
                ->where('volo_vore_id', $value->vore_id)
                ->get()->toArray();
            $find_volo_data = json_decode(json_encode($find_volo_data), true);
            $vore_id = $value->vore_id;
            $u8_return = YongYous::apiWorkOrder($user_info, (array)$value, $find_volo_data, $now_date); //调用u8接口
            $log_data['u8_return'] = $u8_return;
            if ($u8_return['code'] == 500) {
                if ($u8_return['vou_data']) {
                    // 如果凭证添加失败，凭证号自动加1
                    YongYous::insertVoucher($user_info, $u8_return['vou_data'], 1);
                }
                $vore_ord_numbers .= $value->vore_ord_number . ', ';
            } else {
                $vore_edit_data['vore_state'] = 2;
                $vore_edit_data['vore_update_time'] = date('Y-m-d H:i:s');
                $vore_res = DB::table('voucher_receipts')
                    ->where('vore_id', $value->vore_id)
                    ->update($vore_edit_data);
            }
        }

        if (!empty($acset_numbers)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$vore_ord_numbers . '，U8财务系统凭证上传失败2！']);
        }

        $log_data['time'] = date('Y-m-d H:i:s');
        $log_data['user_info'] = $user_info;
        $log_data['vore_ord_number'] = $vore_ord_number;
        Common::write_record_log($log_data, 'pc/VoucherReceiptsController.txt', 'sync');

        if ($vore_res) {
            Common::addLog($user_info, getRealIp($request), '凭证列表', '同步U8', '单号(' . implode(',', $vore_ord_number) . ')同步成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'U8财务系统凭证上传成功！']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'U8财务系统凭证上传失败啦！']);
        }
    }
}
