<?php
namespace App\Http\Controllers\WeChatApplet\AppletAccountControl;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\WeChatApplet\Verify\AppletAccountControl\VerifyAppletOrderBillController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Services\AccountControl\AppletOrderBill;

// 微信小程序 -- 财务系统 -- 账单列表
class AppletOrderBillController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

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

        $search_data = $request->all();
        // 判断是否有单号查询
        if (!empty($request['query_number'])) {
            // 根据单号查询对应的账单，查询单号有：订单号、工单号、采购单号
            $initial = substr($request['query_number'], 0, 1); //获取单号首字母
            if (in_array($initial, ['D', 'G', 'C'])) {
                if ($initial == 'D') { //查询订单对应的账单
                    $find_orbi_id = DB::table('order')
                        ->where('ord_cid', $user_info->adm_cid)
                        ->where('ord_shop_id', $user_info->adm_shop_id)
                        ->where('ord_delete', 1)
                        ->where('ord_order_number', $request['query_number'])
                        ->value('ord_orbi_id');
                    $search_data['orbi_id'] = $find_orbi_id;
                } elseif ($initial == 'G') { //查询工单对应的账单
                    $find_orbi_id = DB::table('work_order')
                        ->where('wor_cid', $user_info->adm_cid)
                        ->where('wor_shop_id', $user_info->adm_shop_id)
                        ->where('wor_delete', 1)
                        ->where('wor_number', $request['query_number'])
                        ->value('wor_wobi_id');
                    $search_data['orbi_id'] = $find_orbi_id;
                } elseif ($initial == 'C') { //查询采购单对应的账单
                    $find_orbi_number = DB::table('purchase_order')
                        ->where('company_id', $user_info->adm_cid)
                        ->where('cg_shop_id', $user_info->adm_shop_id)
                        ->where('is_del', 1)
                        ->where('cg_number', $request['query_number'])
                        ->value('cg_zdnumber');
                    $search_data['orbi_number'] = $find_orbi_number;
                } else {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是系统查询单号']);
                }

                if (empty($find_orbi_id) && empty($find_orbi_number)) {
                    return response()->json(['code'=>200, 'msg'=>'error', 'data'=>['data'=>[]]]);
                }
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是系统单号']);
            }
        }

        $list_data = DB::table('order_bill as orbi')
            ->where('orbi_cid', $user_info->adm_cid)
            ->where('orbi_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) { //账单状态1.未结款2.已结款3.待审核4.已驳回5.部分结款
                if (!empty($search_data['orbi_state']) && ($search_data['orbi_state'] == 6)) {
                    $query->whereIn('orbi_state', [1, 5]);
                } elseif (!empty($search_data['orbi_state'])) {
                    $query->where('orbi_state', $search_data['orbi_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //账单编号
                if (!empty($search_data['orbi_number'])) {
                    $query->where('orbi_number', 'like', '%' . $search_data['orbi_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //客户单位
                if (!empty($search_data['orcl_channel_unit'])) {
                    $query->where('orbi_type', 2)
                        ->where('orbi_client_id', $search_data['orcl_channel_unit'])
                        ->orwhere('orbi_channel_unit', $search_data['orcl_channel_unit']);
                }
            })
            ->where(function ($query) use ($search_data) { //账单生成类型1订单账单2速电同步生成3工单账单4期初账单5采购账单
                if (!empty($search_data['orbi_create_type'])) {
                    $query->where('orbi_create_type', $search_data['orbi_create_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //账单id
                if (!empty($search_data['orbi_id'])) {
                    $query->where('orbi_id', $search_data['orbi_id']);
                }
            })
            ->select('orbi_id', 'orbi_number', 'orbi_start_time', 'orbi_end_time', 'orbi_order_amount', 'orbi_bill_price', 'orbi_payment_time', 'orbi_payment_way', 'orbi_handle_adm_id', 'orbi_actual_price', 'orbi_state', 'orbi_audit_time', 'orbi_audit_adm_id', 'orbi_create_adm_id', 'orbi_remark', 'orbi_client_id', 'orbi_type', 'orbi_plus_minus', 'orbi_create_type', 'orbi_opening_time', 'orbi_create_time', 'orbi_receive_price', 'orbi_zero_price')
            ->orderBy('orbi_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $mem_id = [];
            $channel_id = [];
            $shop_arr = [];
            $vish_id = [];
            foreach ($list_items as $key => $value) {
                $adm_id[] = $value->orbi_create_adm_id;
                $adm_id[] = $value->orbi_handle_adm_id;
                $adm_id[] = $value->orbi_audit_adm_id;

                if ($value->orbi_type == 1) { //会员
                    $mem_id[] = $value->orbi_client_id;
                } elseif ($value->orbi_type == 2) { //客户单位
                    $channel_id[] = $value->orbi_client_id;
                } elseif ($value->orbi_type == 3) { //加盟店
                    $shop_arr[] = $value->orbi_client_id;
                } elseif ($value->orbi_type == 4) { //虚拟加盟店
                    $vish_id[] = $value->orbi_client_id;
                }
            }
            $adm_id = array_unique($adm_id);
            $mem_id = array_unique($mem_id);
            $shop_arr = array_unique($shop_arr);
            $vish_id = array_unique($vish_id);
            // 查找账号id对应的账号姓名
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->select('adm_id', 'adm_name')
                ->get()->toArray();

            // 查找所对应的 会员信息
            $find_mem = DB::table('member')
                ->whereIn('mem_id', $mem_id)
                ->select('mem_id', 'mem_name', 'mem_phone', 'mem_province', 'mem_city', 'mem_county', 'mem_address')
                ->get()->toArray();

            // 查找所对应的 客户单位信息
            $find_channel = DB::table('channel_unit')
                ->whereIn('chun_id', $channel_id)
                ->select('chun_id', 'chun_unit_name', 'chun_name', 'chun_phone', 'chun_province', 'chun_city', 'chun_county', 'chun_address')
                ->get()->toArray();
            $find_sd_chan = config('apisystem.sd_chan_info');
            foreach ($find_channel as $k => $v) {
                $channel_name[$v->chun_id] = $v->chun_unit_name;
            }

            $find_shop = DB::table('shop')
                ->whereIn('shop_id', $shop_arr)
                ->select('shop_id', 'shop_store_name', 'shop_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address')
                ->get()->toArray();

            $find_vish = DB::table('virtual_shop')
                ->whereIn('vish_id', $vish_id)
                ->select('vish_id', 'vish_store_name', 'vish_name', 'vish_phone', 'vish_province', 'vish_city', 'vish_county', 'vish_address')
                ->get()->toArray();
        } else {
            $find_admin = [];
            $find_mem = [];
            $find_channel = [];
            $find_sd_chan = [];
            $find_shop = [];
            $find_vish = [];
        }

        $state_count = DB::table('order_bill')
            ->where('orbi_cid', $user_info->adm_cid)
            ->where('orbi_superior_shop_id', $shop_id)
            ->select(DB::raw('count(*) as count, orbi_state'))
            ->groupBy('orbi_state')
            ->get();
        $orbi_state = 0;
        foreach ($state_count as $key => $value) {
            if ($value->orbi_state == 1 || $value->orbi_state == 5) {
                $orbi_state += $value->count;
            }
        }
        $state_count = json_decode(json_encode($state_count), true);
        $data['count'] = $orbi_state;
        $data['orbi_state'] = 6;
        array_push($state_count, $data);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据
        $data_info['find_admin'] = $find_admin;                  //返回数据
        $data_info['state_count'] = $state_count;                //返回数据
        $data_info['find_mem'] = $find_mem;                      //会员信息
        $data_info['find_channel'] = $find_channel;              //客户单位信息
        $data_info['find_sd_chan'] = $find_sd_chan;              //速电客户单位信息
        $data_info['find_shop'] = $find_shop;                    //加盟店
        $data_info['find_vish'] = $find_vish;                    //虚拟加盟店

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

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

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

        $search_data = $request->all();

        $select_field = "orbi_id, orbi_number, orbi_start_time, orbi_end_time, orbi_create_time, orbi_create_adm_id, orbi_order_amount, orbi_bill_price, orbi_actual_price, orbi_type, orbi_client_id, orbi_create_type, orbi_collection_price";
        $order_bill = new AppletOrderBill();
        $return_data = $order_bill->billNumber($user_info, $request->all(), $search_data, $this->show_count, $select_field);
        return response()->json($return_data);
    }

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

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

        $select_field = "orbi_number, orbi_state, orbi_start_time, orbi_end_time, orbi_create_time, orbi_create_adm_id, orbi_order_amount, orbi_bill_price, orbi_total_price, orbi_client_id, orbi_goods_sum, orbi_collection_price, orbi_audit_time, orbi_audit_adm_id, orbi_payment_time, orbi_payment_way, orbi_actual_price, orbi_remark, orbi_img, orbi_payee_id, orbi_type, orbi_zero_price, orbi_receive_price, orbi_plus_minus";
        $order_bill = new AppletOrderBill();
        $return_data = $order_bill->lookInfo($user_info, $request->all(), $select_field);
        return response()->json($return_data);
    }
}
