<?php
/**
 * @package 商户端
 * @Author: ljj
 * @Date: 2021/1/5
 */
namespace app\controller\merchant\system;
use app\validate\merchant\PerformanceDivvyValidate;
use FormBuilder\Factory\Elm;
use think\App;
use crmeb\basic\BaseController;
use think\facade\Db;
use think\facade\Route;

class PerformanceDivvy extends BaseController
{
    protected $userInfo;

    /**
     * ProductCategory constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
//        $this->userInfo =$this->request->isLogin() ? $this->request->userInfo():null;
    }

    public function lst()
    {
        [$page, $limit] = $this->getPage();
        $mer_id=$this->request->merId();

        $where['mer_id']=$mer_id;
        $state = $this->request->param('state','-1');
        if($state==1){
            $where['state']=1;
        }


        $list=Db::name('enterprise_performance_divvy')->where($where)->order('kpi asc,id asc')->page($page, $limit)->select()->each(function ($v){
            $v['gdp']=set_price_rtrim($v['gdp']).' %';
            $v['kpi']=set_price_rtrim($v['kpi']);
            return $v;
        });
        $data['list']=$list;
        $data['total']=Db::name('enterprise_performance_divvy')->count();
        return app('json')->success($data);
    }
    public function createForm(){
        $data['state']=1;
        $merId=$this->request->merId();
        $form= Elm::createForm(Route::buildUrl('performanceDivvyCreate')->build(), [
            Elm::input('name', '身份')->required(),
            Elm::number('gdp', '分红池占比(日销售额百分比)')->required(),
            Elm::number('kpi', '业绩考核标准(万元)')->required()->info('小市场业绩之和，达到考核标准后身份升级；'),
            Elm::number('num', '邀请人数')->required(),
            Elm::frameImage('img', '身份标识图标', '/' . config('admin.' . ($merId ? 'merchant' : 'admin') . '_prefix') . '/setting/uploadPicture?field=img&type=1')->width('896px')->height('480px')->props(['footer' => false])->modal(['modal' => false, 'custom-class' => 'suibian-modal']),

            Elm::textarea('content', '权益说明')->required()->attrs(['rows' => 15]),
            Elm::switches('state', '状态')->inactiveValue(0)->activeValue(1)->inactiveText('关闭')->activeText('开启'),
        ]);
        $form->setTitle( '添加身份' )->formData($data);

        return app('json')->success(formToData($form));
    }
    public function updateForm($id){
        $data=Db::name('enterprise_performance_divvy')->find($id);
        if(!$data){
            return app('json')->fail('数据不存在');
        }
        $data['state']=(int)$data['state'];
        $merId=$this->request->merId();
        $form= Elm::createForm(Route::buildUrl('performanceDivvyUpdate', compact('id'))->build(), [
            Elm::input('name', '身份')->required(),
            Elm::number('gdp', '分红池占比(日销售额百分比)')->required(),
            Elm::number('kpi', '业绩考核标准(万元)')->required()->info('小市场业绩之和，达到考核标准后身份升级；'),
            Elm::number('num', '邀请人数')->required(),
            Elm::frameImage('img', '身份标识图标', '/' . config('admin.' . ($merId ? 'merchant' : 'admin') . '_prefix') . '/setting/uploadPicture?field=img&type=1')->width('896px')->height('480px')->props(['footer' => false])->modal(['modal' => false, 'custom-class' => 'suibian-modal']),
            Elm::textarea('content', '权益说明')->required()->attrs(['rows' => 15]),
            Elm::switches('state', '状态')->inactiveValue(0)->activeValue(1)->inactiveText('关闭')->activeText('开启'),
        ]);
        $form->setTitle(is_null($id) ? '添加身份' : '修改身份')->formData($data);

        $list=formToData($form);
        $list['data']=$data;
        return app('json')->success($list);
    }

    public function create(PerformanceDivvyValidate $validate)
    {
        $data = $this->checkParam($validate);




        // 使用 filter_var 函数验证是否为非负数
        if (filter_var($data['gdp'], FILTER_VALIDATE_FLOAT) !== false && $data['gdp'] >= 0) {
            // 参数合法，且为非负数
        } else {
            return app('json')->fail('分红池占比(日销售额百分比)不能是负数');
            // 参数不合法，或者为负数
        }
        if (filter_var($data['kpi'], FILTER_VALIDATE_FLOAT) !== false && $data['kpi'] >= 0) {
            // 参数合法，且为非负数
        } else {
            return app('json')->fail('业绩考核标准(万元)不能是负数');
            // 参数不合法，或者为负数
        }
        if (filter_var($data['num'], FILTER_VALIDATE_FLOAT) !== false && $data['num'] >= 0) {
            // 参数合法，且为非负数
        } else {
            return app('json')->fail('邀请人数不能是负数');
            // 参数不合法，或者为负数
        }

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

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

        $data['mer_id']=$this->request->merId();

        $count=Db::name('enterprise_performance_divvy')->where('mer_id',$data['mer_id'])->where('kpi', $data['kpi'])->count();
        if($count>0){
            return app('json')->fail('业绩考核标准金额已存在，请重新输入~');
        }


        Db::name('enterprise_performance_divvy')->insertGetId($data);
        return app('json')->success('添加成功');
    }


    public function update($id, PerformanceDivvyValidate $validate)
    {
        $data = $this->checkParam($validate);



        // 使用 filter_var 函数验证是否为非负数
        if (filter_var($data['gdp'], FILTER_VALIDATE_FLOAT) !== false && $data['gdp'] >= 0) {
            // 参数合法，且为非负数
        } else {
            return app('json')->fail('分红池占比(日销售额百分比)不能是负数');
            // 参数不合法，或者为负数
        }
        if (filter_var($data['kpi'], FILTER_VALIDATE_FLOAT) !== false && $data['kpi'] >= 0) {
            // 参数合法，且为非负数
        } else {
            return app('json')->fail('业绩考核标准(万元)不能是负数');
            // 参数不合法，或者为负数
        }
        if (filter_var($data['num'], FILTER_VALIDATE_FLOAT) !== false && $data['num'] >= 0) {
            // 参数合法，且为非负数
        } else {
            return app('json')->fail('邀请人数不能是负数');
            // 参数不合法，或者为负数
        }

        if($data['state']==1){
            $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');

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

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

        $data['mer_id']=$this->request->merId();

        $count=Db::name('enterprise_performance_divvy')->where('mer_id',$data['mer_id'])->where('kpi', $data['kpi'])->where('id !='.$id)->count();
        if($count>0){
            return app('json')->fail('业绩考核标准金额已存在，请重新输入~');
        }

        Db::name('enterprise_performance_divvy')->where('id',$id)->update($data);
        return app('json')->success('编辑成功');
    }
    private function checkParam(PerformanceDivvyValidate $validate)
    {
        $data = $this->request->params(['name', 'gdp', 'kpi', 'num', 'img', 'content', 'state']);
        $validate->check($data);
        return $data;
    }

}
