<?php
/**
 * 分红
 * Created by PhpStorm.
 * User: wxj
 * Date: 2019/10/31
 * Time: 15:02
 */
namespace JinDouYun\Controller\Holders;


use JinDouYun\Dao\Customer\DCustomer;
use JinDouYun\Dao\Customer\DMemberBalanceDetail;
use JinDouYun\Dao\Order\DOrder;
use JinDouYun\Model\Enterprise\MEnterprise;
use JinDouYun\Model\Holders\MHoldersBonus;
use JinDouYun\Model\System\MBasicSetup;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Cache\ShopCache;
use JinDouYun\Controller\BaseController;
use JinDouYun\Cache\TempSaveCache;

class HoldersBonus extends BaseController
{
    private $obj;
    private $objShopCache;
    private $objTempSaveCache;

    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->obj = new MHoldersBonus($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objShopCache = new ShopCache();
        $this->objTempSaveCache = new TempSaveCache();
    }

    /**
     * 添加和编辑商铺管理公共字段处理方法
     *
     * @return array
     */
    public function commonFieldFilter(){

        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $shopData = [
            'name' => isset($params['name']) ? $params['name'] : '',
            'price' => isset($params['price']) ? $params['price'] : '',
            'ot_price' => isset($params['ot_price']) ? $params['ot_price'] : '',
            'image' => isset($params['image']) ? $params['image'] : '',
        ];

        //非暂存则验空
        if (!isset($params['tempSave']) || $params['tempSave'] == false) {
            foreach($shopData as $key => $value){
                if(empty($value) && $value !== 0){
                    $this->sendOutput($key.'参数错误', ErrorCode::$paramError );
                }
            }
        }

        $shopData['info']= isset($params['info']) ? $params['info'] : false;
        $shopData['introduce']= isset($params['introduce']) ? $params['introduce'] : false;
        $shopData['status']= isset($params['status']) ? $params['status'] : 1;
        return $shopData;
    }

    /**
     * 列表
     */
    public function list()
    {
        $params = $this->request->getRawJson();
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];


        //uid
        if(isset($params['name']) && !empty($params['name'])){
            $selectParams['name'] = $params['name'];
        }

        if(isset($params['start_time']) && !empty($params['start_time'])){
            $selectParams['start_time'] = $params['start_time'];
        }

        if(isset($params['end_time']) && !empty($params['end_time'])){
            $selectParams['end_time'] = $params['end_time'];
        }

        if(isset($params['type']) && !empty($params['type'])){
            $selectParams['type'] = $params['type'];
        }

        $result = $this->obj->list($selectParams);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }
    }


    /**
     * 添加
     * @throws \Exception
     */
    public function add()
    {
        $addStaffData = $this->commonFieldFilter();

//        $addStaffData['shop_id'] = $this->shopId;
        $addStaffData['enterprise_id'] = $this->onlineEnterpriseId;
        $result = $this->obj->insert($addStaffData);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }


    /**
     * 详情
     * @return void
     */
    public function details()
    {
        $where = [];
        $id = $this->request->param('id');
        if(!empty($id)){
            $where['id'] = $id;
        }
        $result = $this->obj->details($where);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 修改
     * @return void
     */
    public function update()
    {
        $id['id'] = $this->request->param('id');
        if (empty($id['id'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $params = $this->commonFieldFilter();

        $result = $this->obj->update($params, $id);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    public function delete()
    {

        $id['id'] = $this->request->param('id');
        if (empty($id['id'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }


        $result = $this->obj->delete($id);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }


    public function bonus()
    {
        $Menterprise = new MEnterprise();
        $en = $Menterprise->list([])->getData();
        foreach ($en['data'] as $item)
        {
            $Mbasi = new MBasicSetup($item['id']);
            $basi = $Mbasi->getBasicSetup()->getData();
            $Mholders = new \JinDouYun\Model\Holders\Holders();
            $objDOrder = new DOrder('default');
            $objDOrder->setTable('qianniao_order_'.$item['id'].'_1');
            $objCustomer = new DCustomer('default');
            $objCustomer->setTable('qianniao_customer_'.$item['id']);
            $objMenber = new DMemberBalanceDetail('default');
            $objMenber->setTable('qianniao_member_balance_detail_'.$item['id']);
            if ($basi){
                $holders_original =  $Mholders->getSum($item['id']);//所有股份
                $order = $objDOrder->select(['payStatus' => 5,'returnStatus' => 0], 'sum(payAmount) as payAmount');
                if ($holders_original['shares'] > 0 ||  $holders_original['dends'] > 0 and $order){
                    $original_bonus = $basi['basicData']['original_bonus'] / 100;//原始股份分红比列
                    $bonus =  $basi['basicData']['bonus'] / 100;//分红股份分红比列

                    if ($holders_original['shares'] > 0){
                        $originalPrice = round($order[0]['payAmount'] * $original_bonus,3); // 原始股分红总金额
                        $originalPriceOne = round($order[0]['payAmount'] * $original_bonus/$holders_original['shares'], 3); // 原始股分红单份金额
                    }

                    if ($holders_original['dends'] > 0){
                        $bonusPrice = round($order[0]['payAmount'] * $bonus,2); // 分红股分红总金额
                        $bonusPriceOne = round($order[0]['payAmount'] * $bonus/$holders_original['dends'], 3); // 分红股分红单份金额
                    }

                    $user = $Mholders->Lst(['limit' => 0])->getData();
                    foreach ($user['data'] as $vo)
                    {
                        if ($originalPriceOne > 0 and $vo['shares'] > 0){
                            $customer = $objCustomer->get(['id' => $vo['us_id']]);
                            $number = round($originalPriceOne * $vo['shares'], 3);//原始股份分红
                            $before = $customer['memberBalance'];//变动前
                            $after = $number + $before;//变动后

                            $bounsInsert = [
                                'hol_id' => $vo['id'],
                                'en_id' => $item['id'],
                                'mark' => '原始股份分红',
                                'type' => 1,
                                'number' => $number,
                                'before' => $before,
                                'after' => $after,
                                'total' => $originalPrice,
                                'total_shares' => $holders_original['shares'],
                                'shares' => $vo['shares']
                            ];
                            $memberInsert = [
                                'customerId' => $customer['id'],
                                'userCenterId' => $customer['userCenterId'],
                                'type' => 5,
                                'purpose' => '原始股份分红',
                                'money' => $number,
                                'afterMoney' => $after,
                                'beforeMoney' => $before,
                                'remark' => '原始股份分红',
                                'createTime' => time(),
                                'updateTime' => time(),
                            ];
                            $this->obj->insert($bounsInsert);
                            $objMenber->insert($memberInsert);
                            $objCustomer->update(['memberBalance' => $after], $vo['us_id']);
                        }

                        if ($bonusPriceOne > 0 and $vo['dends'] > 0){
                            $customer = $objCustomer->get(['id' => $vo['us_id']]);
                            $number = round($bonusPriceOne * $vo['dends'], 3);//原始股份分红
                            $before = $customer['memberBalance'];//变动前
                            $after = $number + $before;//变动后

                            $bounsInsert = [
                                'hol_id' => $vo['id'],
                                'en_id' => $item['id'],
                                'mark' => '分红股份分红',
                                'type' => 2,
                                'number' => $number,
                                'before' => $before,
                                'after' => $after,
                                'total' => $bonusPrice,
                                'total_shares' => $holders_original['dends'],
                                'shares' => $vo['shares']
                            ];
                            $memberInsert = [
                                'customerId' => $customer['id'],
                                'userCenterId' => $customer['userCenterId'],
                                'type' => 5,
                                'purpose' => '分红股份分红',
                                'money' => $number,
                                'afterMoney' => $after,
                                'beforeMoney' => $before,
                                'remark' => '分红股份分红',
                                'createTime' => time(),
                                'updateTime' => time(),
                            ];
                            $this->obj->insert($bounsInsert);
                            $objMenber->insert($memberInsert);
                            $objCustomer->update(['memberBalance' => $after], $vo['us_id']);
                        }
                    }
                    echo '企业'.$item['id'].'发放成功';
                }
            }
        }


    }

}