<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2022/10/29
 * Time: 11:08
 */
namespace app\api\controller;

use app\admin\model\Addr;
use app\admin\model\device\Chargedevice;
use app\admin\model\device\Chargegroup;
use app\admin\model\device\Site;
use app\admin\model\order\Order;
use app\common\controller\Api;
use \app\admin\model\users\Users as UsersModel;

/**
 * 设备接口
 */
class Device extends Api{

    protected $noNeedLogin = ['myselfdevices','myselfsites'];
    protected $noNeedRight = ['*'];
    /**
     * 我的站点列表
     */
    public function mySites(){
        $page = $this->request->post('page',1);
        $site_list = Site::where(['agent_user_id' =>$this->auth->id])
            ->page($page)
            ->limit($this->pageSize)
            ->select();
        foreach ($site_list as $key => $val){
            $device_count = Chargedevice::where(['site_id' =>$val['id'],'user_id' =>$this->auth->id])->count();//获取我的每个站点设备数
            $site_list[$key]['device_count'] = $device_count;
        }
        $total_device_count = Chargedevice::where(['user_id' =>$this->auth->id])->count();
        $this->success('获取成功',['site_list' =>$site_list,'total_device_count' =>$total_device_count]);
    }

    /**
     * 我的设备
     */
    public function myDevices(){
        $page = $this->request->post('page',1);
        $site_id = $this->request->param('site_id');
        $where = ['site_id' =>$site_id,'user_id' =>$this->auth->id];
        $device_list = Chargedevice::where($where)
            ->page($page)
            ->limit($this->pageSize)
            ->select();//获取我的每个站点设备详情
        $site_info = Site::alias('s')
            ->join('addr ad','ad.ID = s.area_id','left')
            ->field('s.*,ad.MergerName')
            ->where(['s.id' =>$site_id])
            ->find();
        $site_device_count = Chargedevice::where($where)->count();//获取我的每个站点设备数
        $this->success('获取成功',['device_list' =>$device_list,'site_device_count' =>$site_device_count,'site_info' =>$site_info]);
    }

    /**
     * 未授权设备（充电桩）列表
     */
    public function getUnauthDevices(){
        $page = $this->request->post('page',1);
        $where = ['authorizestatus' =>1];
        $device_list = Chargedevice::where($where)
            ->page($page)
            ->limit($this->pageSize)
            ->select();//获取我的每个站点设备详情
        $this->success('获取成功',['device_list' =>$device_list]);
    }

    /**
     * 获取三级联地址 ID 地址id ParentId 上级id Name 城市名称
     * @param pid 上级id
     * @return array
     */
    public function getAddressList(){
        $pid = $this->request->param('pid',0);
        if($pid){
            $where['ID|ParentId'] = $pid;
        }
        if(!$pid){
            $where['LevelType'] = 2;
        }
        $field = 'ID pid, ParentId, Name name, Pinyin, LevelType';
        $list = Addr::getSelect($where , $field);
        $pinyin = [];
        $city_list = [];
        foreach ($list as $key => $val){
            $firstpinyin = substr($val['Pinyin'],0,1);
            $pinyin[] = $firstpinyin;
            $chargedevice = Chargedevice::where(['area_id|city_id|province_id' =>$val['pid']])->find();
            if($chargedevice){
//                unset($list[$key]);
                $city_list[] =$val;
            }
        }
        array_multisort($pinyin, SORT_ASC, $list);
        $pinyin_arr = array_unique($pinyin);
        sort($pinyin_arr);
        $this->success('获取成功',['pinyin' =>$pinyin_arr,'city_list' =>$city_list]);
    }

    /**
     * 获取站点所有未授权设备（充电桩）列表
     */
    public function getSiteDevices(){
        $page = $this->request->post('page',1);
        $city_id = $this->request->post('city_id',0);
        $area_id = $this->request->post('area_id',0);
        $where = [];//默认拿出南昌的充电桩
        if($city_id){
            $where['city_id'] = $city_id;
        }
        if($area_id){
            $where['area_id'] = $area_id;
        }
        $chargegroups = Chargegroup::where($where)
//            ->page($page)
//            ->limit($this->pageSize)
            ->select();//取出所有小区（站点）
        $project_scale_arr = [];
        foreach ($chargegroups as $key => $val){
            $chargedevice = Chargedevice::where(['group_id' =>$val['id']])->find();
            $total_device_count = Chargedevice::where(['group_id' =>$val['id']])->count();//总设备数
            if(!$total_device_count){
                unset($chargegroups[$key]);
                continue;
            }
            $auth_device_count = Chargedevice::where(['authorizestatus' =>2,'group_id' =>$val['id']])->count();//已认购总设备数
            $chargegroups[$key]['image'] = $chargedevice['image'];//设备图片
            $chargegroups[$key]['cycle'] = $chargedevice['cycle'] = 3;//设备周期
            $chargegroups[$key]['total_device_count'] = $total_device_count;//总设备数
            $chargegroups[$key]['auth_device_count'] = $auth_device_count;//已认购总设备数
//            $chargegroups[$key]['day_bonus'] = $chargedevice['day_bonus'];//每日分红
            /*if($chargedevice['price'] == 39800){
                $chargegroups[$key]['day_bonus'] = '28';
                $chargegroups[$key]['limit_buy'] = 15;//限购
            }else{
                $chargegroups[$key]['day_bonus'] = '28';
                $chargegroups[$key]['limit_buy'] = 15;//限购
            }*/
            $chargegroups[$key]['day_bonus'] = '28';
            $chargedevice['price'] = 10800;
            $chargegroups[$key]['limit_buy'] = 15;//限购
            $chargegroups[$key]['price'] = floor($chargedevice['price']);//设备单价
            $chargegroups[$key]['percentage'] = sprintf('%.2f',$auth_device_count/$total_device_count);//项目规模
            $chargegroups[$key]['project_scale'] = sprintf('%.2f',$chargedevice['price']*$total_device_count/10000).'万元';//项目规模
//            $project_scale_arr[] = sprintf('%.2f',$chargedevice['price']*$total_device_count/10000);
            $project_scale_arr[] = $total_device_count - $auth_device_count;
        }
        sort($chargegroups);
        array_multisort($project_scale_arr,SORT_DESC,$chargegroups);
        $new_chargegroups = array_slice($chargegroups, ($page-1)*$this->pageSize, $this->pageSize);
        $this->success('获取成功',['chargegroups' =>$new_chargegroups]);
    }

    /**
     * 获取站点详情
     */
    public function getSiteDetail(){
        $group_id = $this->request->post('group_id',0);
//        $chargegroups = Chargegroup::where(['id' =>$group_id])->find();//取出所有小区（站点）
        $chargedevice = Chargedevice::where(['authorizestatus' =>1,'group_id' =>$group_id])->find();
        if(!$chargedevice){
            $this->error('此站点已售罄');
        }
        $total_device_count = Chargedevice::where(['group_id' =>$group_id])->count();//总设备数
        $auth_device_count = Chargedevice::where(['authorizestatus' =>2,'group_id' =>$group_id])->count();//已认购总设备数
        $chargedevice['total_device_count'] = $total_device_count;//总设备数
        $chargedevice['auth_device_count'] = $auth_device_count;//已认购总设备数
        if($chargedevice['price'] == 39800){
            $chargedevice['day_bonus'] = '60~80';
            $chargedevice['limit_buy'] = 20;//限购
            $chargedevice['day_bonus_remark'] = '为期60个月，预计每日分红'.$chargedevice['day_bonus'].'元/台';
            $chargedevice['expect_remark'] = '70元*365天*5年=预计总收益127750元';
        }else{
            $chargedevice['day_bonus'] = '28';
            $chargedevice['limit_buy'] = 15;//
            $chargedevice['first_day_bonus_remark'] = '为期12个月，预计收益28元/台';
            $chargedevice['second_day_bonus_remark'] = '为期24个月，预计收益14元/台';
            $chargedevice['expect_remark'] = '28元*365天+14元*730天=预计总收益20440元';
        }
        $chargedevice['price'] = floor($chargedevice['price']);
        $chargedevice['buy_price_remark'] = '认购'.$chargedevice['price'].'元/台，每人限购'.$chargedevice['limit_buy'].'台';
        $chargedevice['project_scale'] = sprintf('%.2f',$chargedevice['price']*$total_device_count/10000).'万元';//项目规模
        $chargedevice['jstime_remark'] = '认购项目有效时间达到24小时，即可获得相应收益（例如在12:07认购成功，则在下个自然日获得收益），可在我的钱包查看收益记录';
        $chargedevice['kt_money'] = '项目未显示售罄，所有用户均可自由购买；';
        $this->success('获取成功',['chargedevice' =>$chargedevice]);
    }

    /**
     * 设备收益说明
     */
    public function getDeviceExplanation()
    {
        $device_id = $this->request->post('device_id');
        $device = Chargedevice::where(['id' =>$device_id])->find();
        $explanation=[];
        if($device['cycle']==3){
            $explanation[0]="1、10800元版设备，一个账户限购20台;";
            $explanation[1]="2、每台设备收益分为二期，第一期：为期12个月，每日收益28元；第二期：为期24个月，每日收益14元;";
            $explanation[2]="3、认购周期：3年。";
        }else{
            $explanation[0]="1、39800元版设备 一个账户限购15台;";
            $explanation[1]="2、每日收益=每日充电分红+每日广告分红+每日包月分红。";
            $explanation[2]="3、认购周期：5年。";
        }
        $this->success('获取设备收益说明成功',$explanation);
    }

    /**
     * 鹿马请求我的站点列表
     */
    public function mySelfSites(){
        if(!$this->request->isPost()){
            $this->error('获取失败');
        }
        $data = $params = $this->request->post();
        unset($params['sign']);
        unset($params['user_id']);
        ksort($params);
        if($data['sign'] == sha1(urldecode(http_build_query($params).'token='.config('luma.token')))) {

            $site_list = Site::where(['agent_user_id' => $data['user_id']])
                ->page($data['page'])
                ->limit($this->pageSize)
                ->select();
            foreach ($site_list as $key => $val) {
                $device_count = Chargedevice::where(['site_id' => $val['id'], 'user_id' => $data['user_id']])->count();//获取我的每个站点设备数
                $site_list[$key]['device_count'] = $device_count;
            }
            $total_device_count = Chargedevice::where(['user_id' => $data['user_id']])->count();
            $this->success('获取成功', ['site_list' => $site_list, 'total_device_count' => $total_device_count]);
        }else{
            $this->error('获取失败,签名错误');
        }
    }

    /**
     * 鹿马请求我的设备接口
     */
    public function mySelfDevices(){
        if(!$this->request->isPost()){
            $this->error('获取失败');
        }
        $data = $params = $this->request->post();
        unset($params['sign']);
        unset($params['user_id']);
        ksort($params);
        if($data['sign'] == sha1(urldecode(http_build_query($params).'token='.config('luma.token')))) {
            $where = ['user_id' =>$data['user_id']];
            $device_list = Chargedevice::where($where)
                ->page($data['page'])
                ->limit($this->pageSize)
                ->select();//获取我的每个站点设备详情
            $site_info = Site::alias('s')
                ->join('addr ad','ad.ID = s.area_id','left')
                ->field('s.*,ad.MergerName')
                ->where(['s.id' =>$data['site_id']])
                ->find();
            $site_device_count = Chargedevice::where($where)->count();//获取我的每个站点设备数
            $this->success('获取成功',['device_list' =>$device_list,'site_device_count' =>$site_device_count,'site_info' =>$site_info]);

        }else{
            $this->error('获取失败,签名错误');
        }
    }
}
