<?php
/**
 * 企业管理Controller
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/04
 * Time: 11:50
 */

namespace JinDouYun\Controller\Enterprise;

use JinDouYun\Dao\Department\DStaff;
use JinDouYun\Model\Order\MOrderReturn;
use Mall\Framework\Core\ErrorCode;

use JinDouYun\Controller\BaseController;

use JinDouYun\Cache\EnterpriseCache;
use JinDouYun\Cache\OverviewCache;
use JinDouYun\Cache\CustomerCache;
use JinDouYun\Model\Order\MOrder;
use JinDouYun\Model\Stock\MInventoryOut;
use JinDouYun\Model\Stock\MInventory;
use JinDouYun\Model\Enterprise\MEnterprise;
use JinDouYun\Model\Finance\MReceived;
use JinDouYun\Model\Finance\MReceive;
use JinDouYun\Model\Finance\MPay;
use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\Purchase\MSupplier;
use JinDouYun\Model\GoodsCategory\MGoodsCategory;
use JinDouYun\Model\GoodsManage\MGoodsBasic;
use Mall\Framework\Core\StatusCode;

class Enterprise extends BaseController
{
    private $objMEnterprise;
    private $objEnterpriseCache;
    private $objOverviewCache;
    private $objMReceived;
    private $objMReceive;
    private $objMPay;
    private $objMCustomer;
    private $objMSupplier;
    private $objMGoodsCategory;
    private $objMGoodsBasic;


    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->objMEnterprise = new MEnterprise();
        $this->objEnterpriseCache = new EnterpriseCache();
        $this->objOverviewCache = new OverviewCache();
        $this->objMReceived = new MReceived($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objMReceive = new MReceive($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objMPay = new MPay($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objMSupplier = new MSupplier($this->onlineUserId, $this->onlineEnterpriseId);
        $this->objMGoodsCategory = new MGoodsCategory($this->onlineUserId, $this->onlineEnterpriseId);
        $this->objMGoodsBasic = new MGoodsBasic($this->onlineUserId, $this->onlineEnterpriseId);
    }

    /**
     * 获取参数
     *
     * @return array
     */
    public function commonFieldFilter()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $EnterpriseData = [
            "userCenterId"   => $this->onlineUserId, //客户id
            "enterpriseName" => isset($params['enterpriseName']) ? $params['enterpriseName'] : '', //企业名称
            "contact"        => isset($params['contact']) ? $params['contact'] : '', //联系人
            "mobile"         => isset($params['mobile']) ? $params['mobile'] : '', //联系电话
            "provinceCode"   => isset($params['provinceCode']) ? $params['provinceCode'] : '', //省份编码
            "cityCode"       => isset($params['cityCode']) ? $params['cityCode'] : '', //城市编码
            "districtCode"   => isset($params['districtCode']) ? $params['districtCode'] : '', //区县编码
            "address"        => isset($params['address']) ? $params['address'] : '', //详细地址
            "categoryId"     => isset($params['categoryId']) ? $params['categoryId'] : 0, //企业类别
            "startTime"      => isset($params['startTime']) ? $params['startTime'] : time(), //营业时间
            "expireTime"     =>strtotime( isset($params['expireTime']) ? $params['expireTime'] : time()), //到期时间
            "logo"           => isset($params['logo']) ? $params['logo'] : '', //企业logo
        ];
        //必填项
        foreach ($EnterpriseData as $key => $value) {
            if (empty($value) && $value !== 0) {
                $this->sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }

        //选填项
        $EnterpriseData['brandName'] = isset($params['brandName']) ? $params['brandName'] : '';
        $EnterpriseData['isoem']     = isset($params['isoem']) ? $params['isoem'] : StatusCode::$delete; //确认企业贴牌 4是确认，5是其他
        $EnterpriseData['updateTime'] = time();

        return $EnterpriseData;
    }

    

    /**
     * 企业删除
     * @throws
     */
    public function deleteEnterprise()
    {

        $params = $this->request->getRawJson();
        $params['enterpriseId'] = $this->onlineEnterpriseId;
        $params['userCenterId'] = $this->onlineUserId;
        //获取参数
        //获取参数
        $result = $this->objMEnterprise->deleteEnterprise($params);
        //删除redis里的企业id和用户id的关联
        $this->objEnterpriseCache->deleteEnterprise($params['userCenterId'], $params['enterpriseId']);

        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 企业修改
     * @throws \Exception
     */
    public function updateEnterprise()
    {
        $params['id'] = $this->onlineEnterpriseId;
        $EnterpriseData = $this->commonFieldFilter();
        $result = $this->objMEnterprise->updateEnterprise($EnterpriseData, $params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 企业详情
     * @throws \Exception
     */
    public function getEnterpriseInfo()
    {
        $params['enterpriseId'] = $this->onlineEnterpriseId;
        $params['userCenterId'] = $this->onlineUserId;
        
        $result = $this->objMEnterprise->getEnterpriseInfo($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 获取当前登录员工信息
     */
    public function getStaffByToken()
    {
        $roleType = $this->request->param('request_id');
        if (empty($roleType)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $params['roleType'] = $roleType;
        $params['userCenterId'] = $this->onlineUserId;
        $params['enterpriseId'] = $this->onlineEnterpriseId;
        $params['shopId'] = $this->shopId;
        $result = $this->objMEnterprise->getStaffByToken($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 首页概况
     * @throws \Exception
     */
    public function overview()
    {
        $params = $this->request->getRawJson();
        //经营概况:是否查找全店或指定店铺
        $businessOverviewShopId = isset($params['businessOverviewShopId']) ? $params['businessOverviewShopId'] : '';
        $ranking = isset($params['ranking']) ? $params['ranking'] : '1';//销量排行，销额排行
        //类目排行:是否查找全店或指定店铺
        $categoryRankingShopId = isset($params['categoryRankingShopId']) ? $params['categoryRankingShopId'] : '';
        //商品排行:是否查找全店或指定店铺
        $goodsRankingShopId = isset($params['goodsRankingShopId']) ? $params['goodsRankingShopId'] : '';
        //供应商排行:是否查找全店或指定店铺
        $supplierRankingShopId = isset($params['supplierRankingShopId']) ? $params['supplierRankingShopId'] : '';

        $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
        $objCustomerCache = new CustomerCache();
        $objMOrder = new MOrder($this->onlineUserId, $this->onlineEnterpriseId);
        $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
        // 统计订单未出库总数
        $modelResult = $objMInventoryOut->statisticsCountInventoryOut($businessOverviewShopId);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(),$modelResult->getErrorCode());
        }

        $objMOrderReturn = new MOrderReturn($this->onlineEnterpriseId,$this->onlineUserId);
        $result = $objMOrderReturn->getSubRetMoneyToday(['shopId' => $businessOverviewShopId]);
        if (!$result->isSuccess()){
            parent::sendOutput($result->getData(),$result->getErrorCode());
        }
        $subRetMoney = $result->getData();
        $numberUser = $this->objMCustomer->getNumberUser()->getData();

        if (!$numberUser['totalCount']){
            $numberUser['valid']=0;
            $numberUser['void']=0;
        }

        $orderNumOfNotOutOfStock = $modelResult->getData();
        $data = [
            'aggregateStatistics' => [
                'totalShouldReceive'      => $this->objMCustomer->getTotalShouldReceive(),//应收账款,先取redis，不存在，取数据库
                'totalShouldPay'          => $this->objMSupplier->getTotalShouldPay(),//应付账款
                'numberOfProductsInStock' => $objMInventory->statistics()['numberOfProductsInStock'],//库存商品数
                'totalMoneyOfInventory'   => $objMInventory->statistics()['totalMoneyOfInventory'],//库存总金额
                'customerTotalNum'        => $numberUser,//客户总数
            ],
            //经营概况
            'businessOverview'    => [
                'orderTotalMoney'                => bcsub($objMOrder->businessOverview('orderTotalMoney', $businessOverviewShopId),$subRetMoney,2),//今日下单金额，所有订单不分状态
                'orderConfirmedMoney'            => bcsub($objMOrder->businessOverview('orderConfirmedMoney', $businessOverviewShopId),$subRetMoney,2),//营业额：被确认以后的所有状态的订单总额
                'todayGrossProfit'               => bcsub($objMOrder->businessOverview('todayGrossProfit', $businessOverviewShopId),$subRetMoney,2),//今日毛利:被确认的订单的：售价减去成本之和
                'todayReceivedMoney'             => $this->objMReceived->getTodayReceivedMoney($businessOverviewShopId),//今日收款
                'todayNewCustomerNum'            => $this->objMCustomer->getTodayCustomerTotalNum($businessOverviewShopId),//今日新增客户
                'todayConfirmedOrderNum'         => $objMOrder->businessOverview('todayConfirmedOrderNum', $businessOverviewShopId),//今日订单：被确认以后的所有状态的订单总数
                'todayConfirmedOrderCustomerNum' => $objMOrder->getTodayCustomerOrderNum($businessOverviewShopId),//下单客户:被确认以后的所有状态的订单对应的客户总数
                //'customerAverageMoney'           => $objMOrder->customerAverageMoney('customerAverageMoney', $businessOverviewShopId),//客单价:被确认以后的所有状态的订单总额/订单总数
                'customerAverageMoney'           => $objMOrder->getTodayOrder($businessOverviewShopId),//客单价:今日确认下单的总金额数除以今日下单的总客户数
                //业务流程改为 所有未出库订单 所以查询方式改变
                'orderNumOfNotOutOfStock'        => $orderNumOfNotOutOfStock,
                'todayCanceledOrder'             => $objMOrder->businessOverview('todayCanceledOrder', $businessOverviewShopId),//今日取消订单
            ],
            //排行榜：销量排行/销额排行
            'ranking'             => [
                //类目排行
                'categoryRanking' => $this->objMGoodsCategory->todayCategoryRanking($ranking, $categoryRankingShopId),
                //商品排行
                'goodsRanking'    => $this->objMGoodsBasic->todayGoodsRanking($ranking, $goodsRankingShopId),
                //客户排行
                'customerRanking' => $this->objMCustomer->todayCustomerRanking($ranking),
                //供应商排行
                'supplierRanking' => $this->objMSupplier->todaySupplierRanking($ranking, $supplierRankingShopId),
            ],
            //近7天订单趋势
            'chartData'           => $this->objOverviewCache->getOrderTrend($this->onlineEnterpriseId)
        ];
        parent::sendOutput($data);
    }
}