<?php

namespace app\controller\manager;

use app\exception\RepositoryException;
use app\model\Account;
use app\model\Coupon;
use app\model\CouponMain;
use app\model\Category as CategoryModel;
use app\model\Business as BusinessModel;
use app\model\Member;
use app\model\BusinessCircle as BusinessCircleModel ;
use app\repository\AccountRepository;
use app\repository\BusinessRepository;
use app\repository\RechargeRepository;
use app\service\wx\WechatPay;
use Exception;

use think\exception\ValidateException;
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()) {
            $repo = BusinessRepository::getInstance();
            $keyword = $this->request->param('keyword/s', '');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap = [["a.state", "=", BusinessModel::state_on]];
            $orders = ['a.id' => 'desc'];
            if (!empty($keyword)) {
                $whereMap[] = ['b.nick_name|a.business_name', 'like', "%$keyword%"];
            }
            //如果是渠道商或者工作人员  只查看自己的下级商家
            if(Member::is_agency($this->auth['roles'])){
                $whereMap[] = ['a.agency_code', '=', $this->auth['business_code']];
            }
            $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->coupon_profit_count = BusinessRepository::getInstance()->businessProfitTotal( $item->business_code);

                //商家充值总额
                $item->recharge_total_money = $item->total_recharge;
            });

            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", "");
        $business = BusinessRepository::getInstance()->findOneByWhere(['code' => $businessCode]);
        if ($this->request->isPost()) {
            if(empty($business)){
                return $this->json(4001,"商家不存在");
            }
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'business_name|商家名称'  => 'require|max:100',
                'business_subtitle|商家简称'  => 'max:100',
                'lat|纬度'  => 'require',
                'lng|经度'  => 'require',
                'province|省市区'  => 'require',
                'city|省市区'  => 'require',
                'county|省市区'  => 'require',
                'business_address|地址'  => 'require|min:3',
                'contact_name|联系人'  => 'require|min:1',
                'contact_phone|联系电话'  => 'require|mobile',
                'state|审核状态'  => 'require|in:0,1,2',
                'enable|启用状态'  => 'require|in:0,1',
                'type|分类'  => 'require|number',
                'characteristic|特色'  => 'max:100',
                'intro|介绍'  => 'require',
                'business_circle_id|商圈'  => 'require',
                'background|背景图'  => 'require',
                'score|评分'  => 'require|in:1,2,3,4,5',
                'reason|驳回原因'  => 'max:100',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            Db::startTrans();
            try {
                $business->save($item);
                Db::commit();
                return $this->json();
            } catch (ValidateException $e) {
                Db::rollback();
                return $this->json(4001, $e->getError());
            }

        }

        if (empty($business)) {
            return $this->error("商家不存在");
        }
        $this->data["item"] = $business;
        $this->data["type"] = CategoryModel::getByGroup();
        $this->data["businessCircle"] = BusinessCircleModel::getList();
        $this->data["model"] = BusinessModel::allModel();

        return $this->view();
    }

    /**
     * 商家认证列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function businessWaitList()
    {
        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 = [["a.state", "in", [BusinessModel::state_reviewing, BusinessModel::state_off]]];
            //如果是渠道商或者工作人员  只查看自己的下级商家
            if(Member::is_agency($this->auth['roles'])){
                $whereMap[] = ['a.agency_code', '=', $this->auth['business_code']];
            }
            $orders = ['a.id' => 'desc'];
            if (!empty($keyword)) {
                $whereMap[] = ['b.nick_name|a.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);
            $reason = input("reason/s", '');
            if (!in_array($state, [BusinessModel::state_off, BusinessModel::state_on])) {
                return $this->json(4001, "错误的审核状态");
            }

            $business = BusinessRepository::getInstance()->findOneByWhere(["code" => $businessCode]);
            if (empty($business)) {
                return $this->json(4001, "商家不存在");
            }
            if ($business['state'] != BusinessModel::state_reviewing) {
                return $this->json(4001, "商家当前状态不可审核");
            }
            $account  = AccountRepository::getInstance()->findOneByWhere(["business_code" => $businessCode]);
            if (empty($account)) {
                return $this->json(4001, "关联用户不存在");
            }

            Db::startTrans();
            try {
                $business->save(["state" => $state, "reason" => $reason]);
                //通过  就改变用户为商家
                if($state == BusinessModel::state_on){
                    $account->save(["type" => Account::type_business]);
                }

                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()->adminCreateOrder($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("5002", $e->getMessage());
            }

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

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

        return $this->view();
    }


}