<?php

namespace Modules\Jiesuan\Http\Controllers;

use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Jiesuan\Services\BusinessmanService;
use Modules\Jiesuan\Services\ConstService;
use Modules\User\Http\Controllers\UserTrait;


class BankAccountController extends CatchController
{
    use UserTrait;
    use ValidatesRequests;

    /**
     * 添加公司结算银行卡
     * @param Request $request
     */
    public function addCompanyCard(Request $request) {
        $this->validate($request, [
            'owner_name' => 'required|string|max:64',
            'name_of_payee' => 'required|string|max:128',
            'card_no' => 'required',
            'bank_name' => 'required|string|max:128',
            'sub_bank_name' => 'required|string|max:256',
            'phone_of_payee' => 'required',
            // 'business_id' => 'required',
        ]);

        $company_uid = $this->getLoginUserId();
        $id = $request->input('id');
        $now = date('Y-m-d H:i:s');
        if($id) {
            // $data = $request->only(['owner_name', 'name_of_payee', 'card_no','bank_name', 'sub_bank_name', 'phone_of_payee', 'business_id']);
            $data = $request->only(['owner_name', 'name_of_payee', 'card_no','bank_name', 'sub_bank_name', 'phone_of_payee']);
            $data['updated_at'] = $now;
            // 只有待审核的允许修改 --放弃
            // DB::table('bank_cards')
            //     ->where([
            //         'id' => $id, 'status' => 1, 'company_uid'=> $company_uid
            //     ])->update($data);
            DB::table('bank_cards')
                ->where([
                    'id' => $id, 'company_uid'=> $company_uid
                ])->update($data);
        } else {
            $data = $request->all();
            $data['status'] = 2; // 免审直接通过
            $data['updated_at'] = $data['created_at'] = $now;
            $data['company_uid'] = $company_uid;
            DB::table('bank_cards')
                ->insert($data);
        }
        return 'ok';
    }

    /**
     * 商务列表
     * @param Request $request
     */
    public function listShangwu(Request $request) {
        return BusinessmanService::list();
    }

    /**
     * 银行列表
     * @param Request $request
     */
    public function listBank(Request $request) {
        return DB::table('banks')
            ->where(['is_show' => 1])
            ->select('id', 'name')
            ->get();
    }

    /**
     * 公司银行卡列表
     * @param Request $request
     */
    public function listCompanyCard(Request $request) {
        $company_uid = $this->getLoginUserId();
        $ownerName = $request->input('owner_name');
        $businessId = $request->input('business_id');
        $createStartAt = $request->input('create_start_at');
        $createEndAt = $request->input('create_end_at');
        $nameOfPayee =  $request->input('name_of_payee');
        $bankCards = DB::table('bank_cards')
            ->where([
                'company_uid' => $company_uid
            ])->where('status', '<>', 0)
            ->when($ownerName, function ($query, $ownerName){
                return $query->where('owner_name', 'like', '%'. $ownerName . '%');
            })->when($businessId, function ($query, $businessId){
                return $query->where('business_id', $businessId);
            })->when($createStartAt, function ($query, $createStartAt) {
                return $query->where('created_at', '>=', $createStartAt);
            })->when($createEndAt, function ($query, $createEndAt){
                return $query->where('created_at', '<=', $createEndAt . ' 23:59:59');
            })->when($nameOfPayee,function ($query,  $nameOfPayee){
                return $query->where('name_of_payee', 'like', '%'. $nameOfPayee . '%');
            })
            ->orderBy('id', 'desc')
            ->paginate($request->input('limit', 15));
        $businessmans = BusinessmanService::list()->keyBy('id');
        foreach ($bankCards as $bankCard) {
            $bankCard->status_str = ConstService::BANK_CARD_CHECK_STATUS[$bankCard->status] ?? '';
            if ($bankCard->business_id >  0){
                $bankCard->business_str = $businessmans->get($bankCard->business_id)->username ?? '';
            }else{
                $bankCard->business_str = "";
            }

        }

        return $bankCards;
    }

    /**
     * 公司管理员可用的银行卡列表
     * @param Request $request
     */
    public function listAvailableBankCard(Request $request) {
        $company_uid = $this->getLoginUserId();
        return DB::table('bank_cards')
            ->where([
                'company_uid' => $company_uid,
                // 'status' => 2
            ])->where('status','>',0)
            ->select('id', 'bank_name', 'card_no', 'sub_bank_name')
            ->get();
    }

    /**
     * 合作信息
     * @param Request $request
     */
    public function hezuoInfo(Request $request) {
        $shareRate = DB::table('company_share_rates')
            ->whereIn('company_uid', [0, $this->getLoginUserId()])
            ->select('company_uid', 'share_rate')
            ->orderBy('company_uid', 'desc')
            ->first()->share_rate  ?? '89.1';

        return [
            'share_rate' => $shareRate . '%',
        ];
    }

    /**
     * 删除银行卡信息
     * @param Request $request
     */
    public function delCompanyCard(Request $request) {
        $this->validate($request, [
            'id' => 'required'
        ]);
        $company_uid = $this->getLoginUserId();
        DB::table('bank_cards')
            ->where([
                'company_uid' => $company_uid,
                'id' => $request->input('id'),
            ])
            // ->where('status', '<>', 2)
            ->update([
                'status' => 0,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        return 'ok';
    }
}
