<?php

namespace app\controller\manager;

use app\exception\RepositoryException;

use app\model\CouponMain;
use app\model\Member;
use app\model\Business as BusinessModel;
use app\repository\BusinessRepository;
use app\repository\CouponRepository;
use app\validate\CouponRelease;
use app\validate\CouponUsingRule;
use Exception;
use think\facade\Config;
use think\facade\Db;
use think\response\Json;
use think\response\View;
use think\facade\Config as CConfig;

/**
 * 优惠券相关
 **/
class Coupon extends Base
{

    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        CConfig::load('extra/distribution_proportion', 'distributionProportion');
        $this->data['distributionProportion'] = config('distributionProportion');
    }

    /**
     * 列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function index()
    {

        if ($this->request->isPost()) {
            $model = new CouponMain();
            $repo = CouponRepository::getInstance($model);
            $keyword = $this->request->param('keyword/s', '');
            $on_shelf = $this->request->param('on_shelf',CouponMain::on_shelf_off);
            $start_time = $this->request->param('start_time',);
            $end_time = $this->request->param('end_time');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap = [];
            $orders = ['sort' => 'desc', "id" => "desc"];
            if (!empty($on_shelf) && in_array($on_shelf, [CouponMain::COMMON_ON, CouponMain::COMMON_OFF])) {
                $whereMap[] = ['on_shelf', '=', $on_shelf];
            }
            if (!empty($start_time)) {
                $whereMap[] = ['start_time', '>=', $start_time];
            }
            if (!empty($end_time)) {
                $whereMap[] = ['end_time', '<=', $end_time];
            }
            if (!empty($keyword)) {
                $whereMap[] = ['name', 'like', "%" . $keyword . "%"];
            }

            $list = $repo->findList($whereMap, [], $page, $size, function ($q) {

                if (!empty($keyword)) {
                    return $q::hasWhere('business', function ($q) use ($keyword) {
                        $q->where('business_name', 'like', "%" . $keyword . "%")
                            //如果是渠道商或者工作人员  只查看自己的下级商家
                            ->when(Member::is_agency($this->auth['roles']), function ($q) {
                                $q->where('agency_code', '=', $this->auth['business_code']);
                            })
                            ->field("code,business_name,business_subtitle,type");
                        //->with('category');
                    });
                }

                if (Member::is_agency($this->auth['roles'])) {

                    return $q::hasWhere('business', function ($q) {
                        $q//如果是渠道商或者工作人员  只查看自己的下级商家
                        ->where('agency_code', '=', $this->auth['business_code'])
                            ->field("code,business_name,business_subtitle,type");
                        //->with('category');
                    });
                } else {
                    return $q->with(["business" => function ($query) {
                        $query->field("code,business_name,business_subtitle,type");
                        //->with('category');
                    }]);
                }

            }, $orders);
            $time = time();
            $list['list']->each(function ($item) use ($time) {
                if (strtotime($item->start_time) > $time) {
                    $item->state_text = '<span >未开始</span>';
                } else if ((strtotime($item->start_time) < $time) && (strtotime($item->end_time) > $time)) {
                    $item->state_text = '<span  class="f_green">进行中</span>';
                } else {
                    $item->state_text = '<span  class="f_red">已过期</span>';
                }
            });
            return $this->json(0, 'success', $list);
        }
        return $this->view();
    }

    /**
     * 上架状态 0上架 1下架
     * */
    public function shelf()
    {
        $id = input("id/d", 0);
        $on_shelf = input("on_shelf/d", 1);
        $model = new CouponMain();
        $repo = CouponRepository::getInstance($model);
        $coupon = $repo->findById($id);

        if (empty($coupon)) {
            return $this->json(4001, "优惠券不存在");
        }

        if (!in_array($on_shelf, [CouponMain::COMMON_OFF, CouponMain::COMMON_ON])) {
            return $this->json(4001, "状态错误");
        }
        $coupon->save(["on_shelf" => $on_shelf]);
        return $this->json();
    }

    /**
     * 持有详细
     *
     * @return Json|View
     * @throws Exception
     */
    public function info()
    {

        if ($this->request->isPost()) {
            $model = new CouponMain();
            $repo = CouponRepository::getInstance($model);
            $id = input("id/d");
            $keyword = $this->request->param('keyword/s', '');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $list = $repo->couponMainHasList($id, $keyword, $page, $size);
            $time = time();
            $list["list"]->each(function ($item) use ($time) {
                if (strtotime($item['end_time']) < $time) {
                    $item->time_state = '已过期';
                } else {
                    $item->time_state = '未过期';
                }

            });
            return $this->json(0, 'success', $list);
        }
        $id = input("id/d");
        $model = new CouponMain();
        $repo = CouponRepository::getInstance($model);
        $coupon = $repo->getModel()->with(["business" => function ($query) {
            $query
                ->field("code,business_name,business_subtitle,type")
                ->with('category');
        }, "couponType"])->where("id", $id)->find();
        if (empty($coupon)) {
            return $this->error("优惠券不存在");
        }
        $this->data["coupon"] = $coupon;
        return $this->view();
    }

    /**
     * 发布优惠券
     *
     * @return Json|View
     * @throws Exception
     */

    public function release()
    {
        if ($this->request->isPost()) {
            $data = input("item/a", []);
            $usingRule = input("using_rule/a", []);


            $business = BusinessRepository::getInstance()->getBusinessAccount($data["business_code"], true);

            if (empty($business)) {
                return $this->json(4001, '商家不存在');
            }
            $validate = new CouponRelease();
            //普通商家要验证扣除金额
            if (!$validate->scene($business["model"] ==BusinessModel::model_ordinary?"ordinary":"")->check($data)) {
                return $this->json(4001, $validate->getError());
            }

            $usingRuleValidate = new CouponUsingRule();
            if (!$usingRuleValidate->check($usingRule)) {
                return $this->json(4001, $usingRuleValidate->getError());
            }

            //持有限量
            Config::load("extra/wechat","wechat");
            $hasCouponMax = config("wechat.hasCouponMax")??0;
            if ($hasCouponMax > 0) {
                $hasCouponCount = CouponRepository::getInstance()->getBusinessOnShelfOnCount($business->code);
                if ($hasCouponCount > $hasCouponMax) {
                    return $this->json(4001, "商家持有商家优惠券不能超过{$hasCouponMax}");
                }
            }



            $data['business_type']          = $business['type'];
            $data['business_name']          = $business['business_name'];
            $data['lng']                    = $business['lng'];
            $data['lat']                    = $business['lat'];
            $data['business_circle_id']     = $business['business_circle_id'];


            $type = CouponRepository::getInstance()->getCouponTypeAll();
            $type = array_column($type->toArray(), null, "id");
            if (!isset($type[$data['type']])) {
                return $this->json(4001, '优惠券类型不存在');
            }
            $data['commission_agency'] = input("item.commission_agency/d", 0);
            $data['commission_admin'] = input("item.commission_admin/d", 0);
            $data['commission_consumer'] = input("item.commission_consumer/d", 0);

            $totalC = $data['commission_agency'] + $data['commission_admin'] + $data['commission_consumer'];
            if ($totalC != 100) {
                return $this->json(5002, "分配比例总和不等于100");
            }

            //保留两位小数
            $data['money'] = floor($data['money'] * 100) / 100;

            $totalMoney = $data['money'] * $data['count'];

            //未领取的优惠券
            $NotClaimedMoney = CouponRepository::getInstance()->getBusinessNotClaimedCoupon($business["code"]);

            if($business["model"] == BusinessModel::model_ordinary){
                if ($business["balance"] < ($totalMoney + $NotClaimedMoney)) {
                    return $this->json(4001, '商家余额不足');
                }
            }

            $data['type_name'] = $type[$data['type']]['name'];
            $date = date("Y-m-d H:i:s");
            $data['create_time'] = $date;
            $data['update_time'] = $date;


            Db::startTrans();
            try {
                CouponRepository::getInstance()->releaseCouponMain($data, $totalMoney, $usingRule);
                Db::commit();
                return $this->json();
            } catch (RepositoryException $e) {
                Db::rollback();
                return $this->json(5001, "发布失败" . $e->getMessage());
            } catch (\think\Exception $e) {
                Db::rollback();
                return $this->json(5002, "发布失败" . $e->getMessage());
            }

        }


        $this->data['business'] = BusinessRepository::getInstance()->getBusinessAll();
        $this->data['type'] = CouponRepository::getInstance()->getCouponTypeAll();
        return $this->view('add');

    }

    /**
     * 修改
     *
     * @return Json|View
     * @throws Exception
     */

    public function edit()
    {
        $couponMain = CouponMain::findOne(["id" => input("id/d", 0)], [], function ($q) {
            return $q->with("usingRule");
        });
        if ($this->request->isPost()) {
            $data = input("item/a", []);
            $usingRule = input("using_rule/a", []);
            if (empty($couponMain)) {
                return $this->json(4001, "优惠券不存在");
            }
            $validate = new CouponRelease();
            if (!$validate->scene("edit")->check($data)) {
                return $this->json(4001, $validate->getError());
            }

            $usingRuleValidate = new CouponUsingRule();
            if (!$usingRuleValidate->check($usingRule)) {
                return $this->json(4001, $usingRuleValidate->getError());
            }

            $business = BusinessRepository::getInstance()->getBusinessAccount($data["business_code"], true);
            if (empty($business)) {
                return $this->json(4001, '商家不存在');
            }
            //更新经纬度
            $data['business_type'] = $business['type'];
            $data['business_name'] = $business['business_name'];
            $data['lng'] = $business['lng'];
            $data['lat'] = $business['lat'];


            $data['commission_agency'] = input("item.commission_agency/d", 0);
            $data['commission_admin'] = input("item.commission_admin/d", 0);
            $data['commission_consumer'] = input("item.commission_consumer/d", 0);
            $totalC = $data['commission_agency'] + $data['commission_admin'] + $data['commission_consumer'];
            if ($totalC != 100) {
                return $this->json(5002, "分配比例总和不等于100");
            }

            $data['update_time'] = date("Y-m-d H:i:s");

            Db::startTrans();
            try {
                $couponMain->save($data);
                $couponMain->usingRule->save($usingRule);
                Db::commit();
                return $this->json();
            } catch (RepositoryException $e) {
                Db::rollback();
                return $this->json(5001, "发布失败" . $e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                return $this->json(5002, "发布失败" . $e->getMessage());
            }

        }

        if (empty($couponMain)||empty($couponMain['usingRule'])) {
            return $this->error("优惠券不存在或关联属性不存在");
        }
        $this->data['business'] = BusinessRepository::getInstance()->getBusinessAll();
        $this->data['type'] = CouponRepository::getInstance()->getCouponTypeAll();
        $this->data['item'] = $couponMain;

        return $this->view();

    }

}