<?php

namespace app\controller\manager;

use app\exception\RepositoryException;
use app\model\BusinessFlow;
use app\model\Coupon;
use app\model\CouponMain;
use app\model\Recharge;
use app\model\Business as BusinessModel;
use app\model\Member;
use app\repository\BusinessRepository;
use app\repository\RechargeRepository;
use app\service\wx\WechatPay;
use Exception;

use think\facade\Db;
use think\response\Json;
use think\response\View;

/*商家*/

class Business extends Base
{
    /**
     * 商家列表列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $model = new BusinessFlow();
            $repo = BusinessRepository::getInstance($model);
            $keyword = $this->request->param('keyword/s', '');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap = [["business.state", "=", BusinessModel::state_on]];
            $orders = ['business.id' => 'desc'];
            if (!empty($keyword)) {
                $whereMap[] = ['account.nick_name|business.business_name', 'like', "%$keyword%"];
            }

            $list = $repo->businessList($whereMap, $page, $size, $orders);
            $list["list"]->each(function ($item) {
                //得到当前商家的所有优惠券
                $date = date("Y-m-d H:i:s");
                //优惠券总数
                $item->coupon_total_count = CouponMain::where(["business_code" => $item->business->code])->sum("count");

                //进行中优惠券总数
                $item->coupon_doing_count = CouponMain::where(["business_code" => $item->business->code])
                    ->whereTime("start_time", "<", $date)
                    ->whereTime("end_time", ">", $date)
                    ->where("status", CouponMain::status_on)
                    ->where("on_shelf", CouponMain::on_shelf_on)
                    ->sum("count");

                //进行中优惠券总数
                $item->coupon_receive_count = CouponMain::where(["business_code" => $item->business->code])->sum("received_count");

                //过期未使用优惠券总数
                $item->coupon_be_overdue_count = Coupon::where(["business_code" => $item->business->code])
                    ->where("is_verificated", "=", Coupon::is_verificated_off)
                    ->whereTime("end_time", "<", $date)
                    ->count();

                //已使用优惠券总数
                $item->coupon_used_count = Coupon::where(["business_code" => $item->business->code])
                    ->where("is_verificated", "=", Coupon::is_verificated_on)
                    ->count();

                //商家充值总额
                $item->recharge_total_money = Recharge::where(["business_code" => $item->business->code])
                    ->where("state", "=", Recharge::state_on)
                    ->sum("money");
            });

            return $this->json(0, 'success', $list);
        }

        return $this->view();
    }


    /**
     * 商家优惠券列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function businessCouponList()
    {
        $businessCode = input("business_code/s", "");
        if ($this->request->isPost()) {

            event('CouponStatusCheck');

            $repo = BusinessRepository::getInstance();
            $keyword = $this->request->param('keyword/s', '');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap = ["business_code" => $businessCode];

            if (!empty($keyword)) {
                $whereMap[] = ['name', 'like', "%$keyword%"];
            }

            $list = $repo->businessCouponList($whereMap, $page, $size, ["create_time" => "desc", "id" => "desc"]);

            return $this->json(0, 'success', $list);
        }
        $this->data["businessCode"] = $businessCode;
        return $this->view();
    }


    /**
     * 商家扣费记录列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function businessDeductionList()
    {
        $businessCode = input("business_code/s", "");
        if ($this->request->isPost()) {
            $repo = BusinessRepository::getInstance();
            $keyword = $this->request->param('keyword/s', '');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap = ["business_code" => $businessCode];

            if (!empty($keyword)) {
                $whereMap[] = ['reason|business_name', 'like', "%$keyword%"];
            }

            $list = $repo->businessDeductionList($whereMap, $page, $size, ["create_time" => "desc", "id" => "desc"]);

            return $this->json(0, 'success', $list);
        }
        $this->data["businessCode"] = $businessCode;
        return $this->view();
    }

    /**
     * 商家充值记录列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function businessRechargeList()
    {
        $businessCode = input("business_code/s", "");
        if ($this->request->isPost()) {
            $repo = BusinessRepository::getInstance();
            $keyword = $this->request->param('keyword/s', '');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap = ["business_code" => $businessCode];

            if (!empty($keyword)) {
                $whereMap[] = ['order_num', 'like', "%$keyword%"];
            }

            $list = $repo->businessRechargeList($whereMap, $page, $size, ["create_time" => "desc", "id" => "desc"]);

            return $this->json(0, 'success', $list);
        }
        $this->data["businessCode"] = $businessCode;
        return $this->view();
    }

    /**
     * 商家详情
     *
     * @return Json|View
     * @throws Exception
     */
    public function businessDetail()
    {
        $businessCode = input("business_code/s", "");
        if ($this->request->isPost()) {

        }
        $business = $repo = BusinessRepository::getInstance()->findOneByWhere(['code' => $businessCode]);
        if (empty($business)) {
            return $this->error("商家不存在");
        }
        $this->data["item"] = $business;
        return $this->view();
    }

    /**
     * 商家认证列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function businessWaitList()
    {
        if ($this->request->isPost()) {
            $model = new BusinessFlow();
            $repo = BusinessRepository::getInstance($model);
            $keyword = $this->request->param('keyword/s', '');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap = [["business.state", "in", [BusinessModel::state_reviewing, BusinessModel::state_off]]];
            $orders = ['business.id' => 'desc'];
            if (!empty($keyword)) {
                $whereMap[] = ['account.nick_name|business.business_name', 'like', "%$keyword%"];
            }

            $list = $repo->businessList($whereMap, $page, $size, $orders);

            return $this->json(0, 'success', $list);
        }

        return $this->view();
    }

    /**
     * 执行商家认证
     *
     * @return Json|View
     * @throws Exception
     */
    public function businessWait()
    {
        if ($this->request->isPost()) {
            $businessCode = input("business_code/s", "");
            $state = input("state/d", 0);
            $business = BusinessRepository::getInstance()->findOneByWhere(["code" => $businessCode]);
            if (empty($business)) {
                return $this->json(4001, "商家不存在");
            }
            if ($business['state'] != BusinessModel::state_reviewing) {
                return $this->json(4001, "商家当前状态不可审核");
            }
            if (!in_array($state, [BusinessModel::state_off, BusinessModel::state_on])) {
                return $this->json(4001, "错误的审核状态");
            }
            Db::startTrans();
            try {
                $business->save(["state"=>$state]);
                Db::commit();
                return  $this->json();
            }catch (RepositoryException $e){
                Db::rollback();
                return $this->json("5001","审核失败");
            }catch (\think\Exception $e){
                Db::rollback();
                return $this->json("5002","审核失败");
            }
        }
    }

    /**
     * 给商家指派代理商
     *
     * @return Json|View
     * @throws Exception
     */
    public function assign()
    {
        $businessCode = input("business_code/s", "");
        $business = BusinessRepository::getInstance()->findOneByWhere(["code" => $businessCode]);

        if ($this->request->isPost()) {
            $anent_code = input("agency_code/s", "");
            if(empty($business)){
                return  $this->json(4001,"商家不存在");
            }
            Db::startTrans();
            try {
                $business->save(["agency_code"=>$anent_code]);
                Db::commit();
                return  $this->json();
            }catch (RepositoryException $e){
                Db::rollback();
                return $this->json("5001","指派失败");
            }catch (\think\Exception $e){
                Db::rollback();
                return $this->json("5002","指派失败");
            }
        }
        if(empty($business)){
            return  $this->error("商家不存在");
        }
        $this->data["agent"] = Member::getAgentAll();
        $this->data["businessCode"] = $businessCode;
        $this->data["business"] = $business;
        return $this->view();
    }

    /**
     * 代为充值
     *
     * @throws Exception
     */
    public function rechargeBehalf()
    {
        $businessCode = input("business_code/s", "");
        $business = BusinessRepository::getInstance()->findOneByWhere(["code" => $businessCode]);

        if ($this->request->isPost()) {
            $money = input("money/f", 0,"abs");
            if($money<=0){
                return  $this->json(4001,"金额错误");
            }
            $money = floor($money * 100) / 100;
            if(empty($business)){
                return  $this->json(4001,"商家不存在");
            }
            Db::startTrans();
            try {
                //创建充值订单
                if (!$order = RechargeRepository::getInstance()->createOrder($businessCode,$money)) {
                    throw new RepositoryException('订单创建失败,请稍后重试');
                }
                //生成支付
                $res = WechatPay::getInstance()->order->unify([
                    'body'         => '商家充值',
                    'out_trade_no' => $order->order_num,
                    'total_fee'    => $money * 100,
                    'trade_type'   => 'NATIVE',
                    'product_id'   => $order->id,
                    'notify_url'   => $this->request->domain()."/api/recharge/notify.html",
                ]);

                if(!isset($res['code_url'])){
                    throw new RepositoryException('订单创建失败,请稍后重试');
                }

                Db::commit();
                return $this->json(0,"success",["order_num"=>$order->order_num,"code_url"=>$res['code_url']]);
            }catch (RepositoryException $e){
                Db::rollback();
                return $this->json("5001",$e->getMessage());
            }catch (Exception $e){
                Db::rollback();
                return $this->json("5001",$e->getMessage());
            }

        }
        if(empty($business)){
            return  $this->error("商家不存在");
        }

        $this->data["businessCode"] = $businessCode;

        return $this->view();
    }


}