<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020/6/25
 *
 *
 */

namespace app\controller\merchant\system;


use app\common\repositories\store\MerchantTakeRepository;
use app\common\repositories\system\config\ConfigClassifyRepository;
use app\validate\merchant\MerchantTakeValidate;
use crmeb\basic\BaseController;
use app\common\repositories\system\merchant\MerchantRepository;
use app\validate\merchant\MerchantUpdateValidate;
use crmeb\jobs\ChangeMerchantStatusJob;
use think\App;
use think\facade\Db;
use think\facade\Queue;

/**
 * Class Merchant
 * @package app\controller\merchant\system
 * @author xaboy
 * @day 2020/6/25
 */
class Merchant extends BaseController
{
    /**
     * @var MerchantRepository
     */
    protected $repository;

    /**
     * Merchant constructor.
     * @param App $app
     * @param MerchantRepository $repository
     */
    public function __construct(App $app, MerchantRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    /**
     * @return mixed
     * @throws \FormBuilder\Exception\FormBuilderException
     * @author xaboy
     * @day 2020/6/25
     */
    public function updateForm()
    {
        return app('json')->success(formToData($this->repository->merchantForm($this->request->merchant()->toArray())));
    }

    /**
     * @param MerchantUpdateValidate $validate
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function update(MerchantUpdateValidate $validate)
    {
        $data = $this->request->params(['mer_info', 'service_phone', 'mer_avatar', 'mer_banner', 'mer_state']);
        $validate->check($data);
        $this->request->merchant()->save($data);
        Queue::push(ChangeMerchantStatusJob::class, $this->request->merId());
        return app('json')->success('修改成功');
    }

    /**
     * @return mixed
     * @author xaboy
     * @day 2020/7/21
     */
    public function info()
    {
        $merchant = $this->request->merchant();
        $res = $merchant->visible(['mer_name','merchant_type', 'mer_id', 'category_id', 'mer_avatar', 'mer_banner', 'mer_info','mer_type', 'uid', 'bzj'])->toArray();
        $res['is_show'] = Db::name('user')->where('mer_id', $res['mer_id'])->value('is_show');
        return app('json')->success($res);
    }

    /**
     * @param MerchantTakeRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/8/1
     */
    public function takeInfo(MerchantTakeRepository $repository)
    {
        $merId = $this->request->merId();
        return app('json')->success($repository->get($merId) + merchantConfig($merId, ['tx_map_key']));
    }
    public function memberSettingsUpdate(MerchantTakeRepository $repository){
        $data = $this->request->params(['member_settings']);

        $member_settings=merchantConfig($this->request->merId(), 'member_settings');


        $merId = $this->request->merId();

        $where['mer_id']=$merId;
        $where['state']=1;
        $yeji=Db::name('enterprise_performance_divvy')->where($where)->sum('gdp');
        $daili=Db::name('enterprise_agent_divvy')->where($where)->sum('gdp');


        // 推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例≤100
        $bili1=$data['member_settings']['tjj'] + $data['member_settings']['ylj']+$yeji+$daili;
        if($bili1>100){
            return app('json')->fail('推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例≤100');
        }
//        // 运营中心比例+推荐代理商收益≤100-(推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例)
        $bili2=$data['member_settings']['yy_one']+$data['member_settings']['dls'];
        if($data['member_settings']['yy_kg']!=1){
            $bili2=$data['member_settings']['dls'];
        }
        if($bili2<=(100-$bili1)){

        }else{
            return app('json')->fail('运营中心比例+推荐代理商收益≤100-(推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例)');
        }



        $str='';

        $str.='修改人id：'.$this->request->adminId();
        $str.=' IP：'.$this->getRealIP();
        $str.=' 原：';
        $str.=json_encode($member_settings,256);
        $str.=' 修改后：';
        $str.=json_encode($data,256);
        Db::name('vip_log')->insert(['data'=>$str]);

        $repository->set($this->request->merId(), $data);
        return app('json')->success('设置成功');
    }
    //客户端IP
    public function getRealIP()
    {
        $forwarded = request()->header("x-forwarded-for");
        if ($forwarded) {
            $ip = explode(',', $forwarded)[0];
        } else {
            $ip = request()->ip();
        }
        return $ip;
    }
    public function getYejiDailiApi()
    {
        $merId = $this->request->merId();

        $where['mer_id']=$merId;
        $where['state']=1;

        $data['yeji']=Db::name('enterprise_performance_divvy')->where($where)->sum('gdp');
        $data['daili']=Db::name('enterprise_agent_divvy')->where($where)->sum('gdp');
        return app('json')->success($data);
    }
    public function memberSettings()
    {
        $merId = $this->request->merId();
        return app('json')->success(merchantConfig($merId, 'member_settings'));
    }

    /**
     * @param MerchantTakeValidate $validate
     * @param MerchantTakeRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/8/1
     */
    public function take(MerchantTakeValidate $validate, MerchantTakeRepository $repository)
    {
        $data = $this->request->params(['mer_take_status', 'mer_take_name', 'mer_take_phone', 'mer_take_address', 'mer_take_location', 'mer_take_day', 'mer_take_time']);
        $validate->check($data);
        $repository->set($this->request->merId(), $data);
        return app('json')->success('设置成功');
    }

    /*修改地址*/
    public  function  address(MerchantTakeRepository $repository){

        $req = $this->request->params(['lat', 'lng', 'addr']);
        if(isset($req['lat'])  &&  $req['lat'] != ""){
            $repository->set($this->request->merId(), $req);
            return app('json')->success('设置成功');
        }else{
            $merchant = $this->request->merchant();
            $data = $merchant->visible(['lat', 'lng', 'addr'])->toArray();
            return app('json')->success('ok',$data);
        }

    }
    function sms_record(){
        [$page, $limit] = $this->getPage();
        $arr=['SMS_294055127','SMS_294055127','SMS_465371794','SMS_465392073','SMS_465430830'];
        $count=Db::name('sms_record')->whereIn('template',$arr)->count();
        $list=Db::name('sms_record')->whereIn('template',$arr)->page($page,$limit)->order('sms_record_id desc')->select();
        $data= compact('count', 'list');
        return app('json')->success('ok',$data);
    }



    /**
     * @param $name
     * @return mixed
     * @author xaboy
     * @day 2020-03-27
     */
    public function getConfigByName($name)
    {
        $merId = $this->request->merId();
        $data = Db::name('system_config_value')->where('config_key', $name)->where('mer_id', $merId)->value('value');
        if (!$data){
            if ($name == 'base_commission') {
                return app('json')->success(0);
                // return app('json')->success(['yanglao_rate' => 0, 'shop_bonus_rate' => 0]);
            } else {
                return app('json')->fail('配置不存在');
            }
        }
        else {
            if (is_json($data)) {
                $data = json_decode($data, true);
            }
            return app('json')->success($data);
        }
    }

    /**
     * @return mixed
     * @author xaboy
     * @day 2020-04-22
     */
    public function saveConfigByName()
    {
        $merId = $this->request->merId();
        $name = input('name');
        $value = input('value');
        if (!$name || !$value) return app('json')->fail('保存失败');

        switch ($name){
            case 'base_commission':
                if ((int)$value < 5) {
                    return app('json')->fail('商户让利比例最低5%');
                }
                if ((int)$value > 100) {
                    return app('json')->fail('商户让利比例最高100%');
                }
                break;
        }

        /** @var ConfigClassifyRepository $make */
        if (!in_array($name, ['base_commission'])) {
            return app('json')->fail('只支持修改base_commission');
        }
        if(Db::name('system_config_value')->where('config_key', $name)->where('mer_id', $merId)->find()){
            Db::name('system_config_value')->where('config_key', $name)->where('mer_id', $merId)->update([
                'value' => (int)$value
            ]);
        }else{
            Db::name('system_config_value')->insert([
                'config_key'  => $name,
                'value'       => (int)$value,
                'mer_id'      => $merId,
            ]);
        }


        // /** @var ConfigClassifyRepository $make */
        // if (!in_array($name, ['shop_bonus_setting'])) {
        //     switch ($name){
        //         case 'shop_bonus_setting':
        //             if ((int)$value['shop_bonus_rate'] < 30) {
        //                 return app('json')->fail('商户让利比例最低30%');
        //             }
        //             break;
        //     }
        //     return app('json')->fail('只支持修改shop_bonus_setting');
        // }
        // if(Db::name('system_config_value')->where('config_key', $name)->where('mer_id', $merId)->find()){
        //     Db::name('system_config_value')->where('config_key', $name)->where('mer_id', $merId)->update([
        //         'value' => json_encode($value)
        //     ]);
        // }else{
        //     Db::name('system_config_value')->insert([
        //         'config_key'  => $name,
        //         'value'       => json_encode($value),
        //         'mer_id'      => $merId,
        //     ]);
        // }

        return app('json')->success('保存成功');
    }
}
