<?php

namespace app\controller\manager;

use app\exception\RepositoryException;

use app\model\CouponMain;
use app\model\CouponType as CouponTypeModel;
use app\model\Business as BusinessModel;
use app\model\Member as MemberModel;
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()) {
            $repo = new CouponMain();
            $repo = CouponRepository::getInstance($repo);
            $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 = ['a.sort' => 'desc', "a.id" => "desc"];
            if (in_array($on_shelf, [CouponMain::COMMON_ON, CouponMain::COMMON_OFF])) {
                $whereMap[] = ['a.on_shelf', '=', $on_shelf];
            }
            if (!empty($start_time)) {
                $whereMap[] = ['a.start_time', '>= TIME' , $start_time];
            }
            if (!empty($end_time)) {
                $whereMap[] = ['a.end_time', '<= TIME', $end_time];
            }
            if (!empty($keyword)) {
                $whereMap[] = ['a.name|b.business_name', 'like', "%" . $keyword . "%"];
            }
            $list =$repo->couponMainList($whereMap,$page,$size,$orders,$this->auth);
            $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>';
                }
                //渠道商名称

                if(isset($item->business) && $item->business && !empty($item->business->agency_code)){
                    $item->agency_text = MemberModel::whereRaw("FIND_IN_SET('".MemberModel::ANENT_ROLE_ID."',roles)"  )
                        ->where("business_code",$item->business->agency_code)->value("nickname","");
                }else{
                    $item->agency_text = '';
                }

            });
            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, '商家不存在');
            }
            if($business->enable != BusinessModel::COMMON_OFF){
                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}");
                }
            }

            //检查类型
            if(CouponTypeModel::checkType($data['type']) !== true){
                return $this->json(4001, '优惠券类型不存在');
            }

            $type = CouponRepository::getInstance()->getCouponTypeAll();
            $type = array_column($type->toArray(), null, "id");
            $data['type_name']              = $type[$data['type']]['name'];

            $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'];




            $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['deduction_money'] = floor($data['deduction_money'] * 100) / 100;

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

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

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


            $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);
                CouponRepository::getInstance()->releaseCouponMain($data);
                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)], []);
        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, '商家不存在');
            }

            //检查类型
            if(CouponTypeModel::checkType($data['type']) !== true){
                return $this->json(4001, '优惠券类型不存在');
            }
            $type                   = CouponRepository::getInstance()->getCouponTypeAll();
            $type                   = array_column($type->toArray(), null, "id");
            $data['type_name']      = $type[$data['type']]['name'];


            //更新经纬度
            $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);
                CouponRepository::getInstance()->getModel()->where("coupon_id",$couponMain->id)->update(["end_time"=>$data["end_time"]." 00:00:00"]);
                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)) {
            return $this->error("优惠券不存在");
        }
        $this->data['business'] = BusinessRepository::getInstance()->getBusinessAll();
        $this->data['type'] = CouponRepository::getInstance()->getCouponTypeAll();
        $this->data['item'] = $couponMain;

        return $this->view();

    }



}