<?php
/**
 * 分销体现记录Model
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2020/07/22
 * Time: 15:00
 */
namespace JinDouYun\Model\Commission;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\Commission\MCommissionGrade;

use JinDouYun\Dao\Commission\DCommissionBusinessman;
use JinDouYun\Dao\Commission\DCommissionWithdrawals;

class MCommissionWithdrawals
{
    /**
     * @var int
     */
    private $userCenterId;

    /**
     * @var int
     */
    private $enterpriseId;

    /**
     * @var DCommissionWithdrawals
     */
    private $objDCommissionWithdrawals;
    /**
     * @var MCommissionCalculate
     */
    private $objMCommissionCalculate;

    /**
     * @var DCommissionBusinessman
     */
    private $objDCommissionBusinessman;

    /**
     * MCommissionWithdrawals constructor.
     * @param $enterpriseId
     * @param $userCenterId
     * @throws \Exception
     */
    public function __construct($userCenterId, $enterpriseId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;

        $this->objDCommissionWithdrawals = new DCommissionWithdrawals();
        $this->objDCommissionWithdrawals->setTable('qianniao_commission_withdrawals_'.$this->enterpriseId);
        $this->objMCommissionCalculate = new MCommissionCalculate($this->enterpriseId,$this->userCenterId);
        $this->objDCommissionBusinessman = new DCommissionBusinessman();
        $this->objDCommissionBusinessman->setTable('qianniao_commission_businessman_' . $this->enterpriseId);
    }

    /**
     * 添加提现记录
     * @throws \Exception
     */
    public function add($params)
    {
        $params['accountContent'] = json_encode($params['accountContent']);
        $this->objDCommissionWithdrawals->setTable('qianniao_commission_withdrawals_'.$this->enterpriseId);
        $this->objDCommissionWithdrawals->beginTransaction();

        $dbResult = $this->objDCommissionWithdrawals->insert($params);
        if ($dbResult === false) {
            $this->objDCommissionWithdrawals->rollBack();
            return ResultWrapper::fail($this->objDCommissionWithdrawals->error(), ErrorCode::$dberror);
        }
        $resAudit = self::updateAuditStatus($dbResult,StatusCode::$auditStatus['auditing']);
        if (!$resAudit->isSuccess()){
            $this->objDCommissionWithdrawals->rollBack();
            return ResultWrapper::fail($resAudit->getData(),ErrorCode::$dberror);
        }

        //查询配置项，是否开启自动审核
        $objMCommissionSetting = new MCommissionSetting($this->enterpriseId,$this->userCenterId);
        $settingResult = $objMCommissionSetting->getSetting('withdrawAudit');
        if (!$settingResult->isSuccess()){
            $this->objDCommissionWithdrawals->rollBack();
            return ResultWrapper::fail($settingResult->getData(),$settingResult->getErrorCode());
        }
        $withdrawAudit = $settingResult->getData();// 4:自动审核 5:手动审核
        if ($withdrawAudit == StatusCode::$delete){
            $resAudit = self::updateAuditStatus($dbResult,StatusCode::$auditStatus['auditIng']);
            if (!$resAudit->isSuccess()){
                $this->objDCommissionWithdrawals->rollBack();
                return ResultWrapper::fail($resAudit->getData(),ErrorCode::$dberror);
            }
        }
        $this->objDCommissionWithdrawals->commit();
        return ResultWrapper::success($dbResult);
    }


    /**
     * 获取所有的提现记录
     */
    public function getAll($selectParams)
    {
        $condition = '';
        if(isset($selectParams['keyword']) && !empty($selectParams['keyword'])){
            $keyword = 'JSON_CONTAINS(b.info->'."'$[*].value'".','."'".'"'.$selectParams['keyword'].'"'."')";
            $condition .= !empty($condition) ? ' AND '.$keyword:' where '.$keyword;
        }

        if(isset($selectParams['type']) && !empty($selectParams['type'])){
            $type = 'w.type = '.$selectParams['type'];
            $condition .= !empty($condition) ? ' AND '.$type:' where '.$type;
        }

        if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])){
            $startime = 'w.createTime BETWEEN '.$selectParams['startTime'].' AND '.$selectParams['endTime'];
            $condition .= !empty($condition) ? ' AND '.$startime:' where '.$startime;
        }
        if(isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])){
            $auditStatus = 'w.auditStatus = '.$selectParams['auditStatus'];
            $condition .= !empty($condition) ? ' AND '.$auditStatus:' where '.$auditStatus;

        }

        $returnData = [
            'data'  => [],
            'total' => 0,
        ];

        $sql = 'select count(w.id) as total from qianniao_commission_withdrawals_'.$this->enterpriseId.' as w left join qianniao_commission_businessman_'.$this->enterpriseId.' as b on w.businessmanId = b.id'. $condition;
        $dbResult = $this->objDCommissionWithdrawals->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCommissionWithdrawals->error(), ErrorCode::$dberror);
        }
        $total = $dbResult[0]['total'];

        $data = [];
        if(!empty($total)){
            $sql = 'select w.*,b.grade from qianniao_commission_withdrawals_'.$this->enterpriseId.' as w left join qianniao_commission_businessman_'.$this->enterpriseId.' as b on w.businessmanId = b.id'.$condition;
            $dbResult = $this->objDCommissionWithdrawals->query($sql);
            if ($dbResult === false) {
                return ResultWrapper::fail($this->objDCommissionWithdrawals->error(), ErrorCode::$dberror);
            }
            $data = $dbResult;
        }

        $returnData = [
            'data'  => empty($data)?[]:self::format($data),
            'total' => $total,
        ];

        return ResultWrapper::success($returnData);
    }

    /**
     * 详情
     */
    public function detail($id)
    {
        $this->objDCommissionWithdrawals->setTable('qianniao_commission_withdrawals_'.$this->enterpriseId);
        $dbResult = $this->objDCommissionWithdrawals->get($id);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCommissionWithdrawals->error(), ErrorCode::$dberror);
        }
        if(!empty($dbResult)){
            $data = self::format([$dbResult]);
            $dbResult = array_pop($data);
        }

        return ResultWrapper::success($dbResult);
    }

    /**
     * 公共格式化
     */
    public function format($data)
    {
        // 提取所有userCenterIds
        $userCenterIds = [];
        // 提取所有分销商等级
        $gradeIds = [];

        foreach ($data as $key => $value){
            $userCenterIds[] = $value['userCenterId'];

            if(isset($value['grade'])){
                $gradeIds[] = $value['grade'];
            }
        }

        $allCustomerData = [];
        $allGrageData = [];
        if(!empty($userCenterIds)){
            // 查询客户信息
            $objMCustomer = new MCustomer($this->enterpriseId, $this->userCenterId);
            $result = $objMCustomer->getCustomerBasicInfoByUserCenterIds($userCenterIds);
            if($result->isSuccess()){
                $customerData = $result->getData();
                if(!empty($customerData)){
                    foreach ($customerData as $key => $value){
                        $allCustomerData[$value['userCenterId']] = $value;
                    }
                }
            }

            // 查询等级信息
            unset($result);
            $objMCommissionGrade = new MCommissionGrade($this->enterpriseId, $this->userCenterId);
            $result = $objMCommissionGrade->getAllGrade(['grade'=>$gradeIds]);
            if($result->isSuccess()){
                $gradeData = $result->getData();
                if(!empty($gradeData)){
                    foreach ($gradeData as $key => $value){
                        $allGrageData[$value['grade']] = $value;
                    }
                }
            }
        }

        foreach ($data as $key => $value){
            if(isset($value['grade'])){
                $data[$key]['gradeName'] = isset($allGrageData[$value['grade']]) ? $allGrageData[$value['grade']]['name'] : '';
            }
            $data[$key]['customer'] = isset($allCustomerData[$value['userCenterId']]) ? $allCustomerData[$value['userCenterId']]['name'] : '';
            $data[$key]['mobile'] = isset($allCustomerData[$value['userCenterId']]) ? $allCustomerData[$value['userCenterId']]['mobile'] : '';
            $data[$key]['accountContent'] = json_decode($value['accountContent'], true);
        }

        return $data;
    }

    /**
     * 修改提现记录状态
     * @param int $id 提现记录表id
     * @param int 状态
     * @return ResultWrapper
     * @throws \Exception
     */
    public function updateAuditStatus($id, $status)
    {
        if(!in_array($status, array_keys(StatusCode::$auditStatus))){
            return ResultWrapper::fail('状态不存在', ErrorCode::$notAllowAccess);
        }
        //查询当前记录
        $commissionWithdrawals = $this->objDCommissionWithdrawals->get(['id'=>$id],'userCenterId,businessmanId,money,auditStatus');
        if ($commissionWithdrawals === false){
            return ResultWrapper::fail($this->objDCommissionWithdrawals->error(),ErrorCode::$dberror);
        }
        if (empty($commissionWithdrawals)){
            return ResultWrapper::fail('获取提现记录失败',ErrorCode::$paramError);
        }

        $buildWithdrawUpdateResult = $this->objMCommissionCalculate->buildWithdraw($commissionWithdrawals,$status);
        if (!$buildWithdrawUpdateResult->isSuccess()){
            return ResultWrapper::fail($buildWithdrawUpdateResult->getData(),$buildWithdrawUpdateResult->getErrorCode());
        }
        $withdrawUpdate =  $buildWithdrawUpdateResult->getData();
        if (empty($withdrawUpdate)){
            return ResultWrapper::fail('更新数据为空',ErrorCode::$paramError);
        }
        $businessmanId = $withdrawUpdate['id'];
        unset($withdrawUpdate['id']);

        $this->objDCommissionWithdrawals->beginTransaction();
        $updateBusinessman = $this->objDCommissionBusinessman->update($withdrawUpdate,['id' => $businessmanId]);
        if ($updateBusinessman === false){
            $this->objDCommissionWithdrawals->rollBack();
            return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror);
        }

        $updateData = [
            'auditStatus' => $status,
            'updatetime'  => time(),
        ];

        // 审核通过时间
        if($status == StatusCode::$auditStatus['auditIng']){
            $updateData['auditTime'] = time();
        }

        // 打款完成时间
        if($status == StatusCode::$auditStatus['auditIng']){
            $updateData['payTime'] = time();
        }

        $dbResult = $this->objDCommissionWithdrawals->update($updateData, $id);
        if ($dbResult === false) {
            $this->objDCommissionWithdrawals->rollBack();
            return ResultWrapper::fail($this->objDCommissionWithdrawals->error(), ErrorCode::$dberror);
        }
        $this->objDCommissionWithdrawals->commit();
        return ResultWrapper::success($dbResult);
    }
}