<?php

namespace App\Http\Controllers\Manage\Channel;

use App\Http\Controllers\Manage\BaseController;
use App\Http\Controllers\Manage\Channel\Transformers\ChannelQuestionNaireTransformer;
use App\Modules\Channel\Models\ChannelQuestionNaire;
use App\Modules\Channel\Services\ChannelQuestionNaireService;
use App\Modules\Channel\Services\CompanyService;
use Illuminate\Http\Request;

//结算比例

/**
 * 渠道问卷调查
 * Class ChannelSwitchController
 * @package App\Http\Controllers\Channel\Channel
 */
class ChannelQuestionNaireController extends BaseController
{
    /**
     * 获取问卷调查信息
     * @param Request $request
     * @return mixed
     */
    public function get_question_naires(Request $request)
    {
        $business_name = $request->input('business_name', '');

        $params = [];
        if ($business_name) {
            $params['business_name'] = $business_name;
        }

        $data = ChannelQuestionNaireService::getQuestionNaires($params, false);

        foreach ($data as $item) {
            $channel_user_id = $item->channel_user_id;
            $distribution_manages_id = $item->distribution_manages_id;

            $total_grade = $this->getTotalGradePreMonth($distribution_manages_id, false);
            $total_naire_company_count = $this->getNaireCompanyCountPreMonth($distribution_manages_id, false);

            $total_grade_pre_month = $this->getTotalGradePreMonth($distribution_manages_id, true);
            $naire_company_count_pre_month = $this->getNaireCompanyCountPreMonth($distribution_manages_id, true);

            $item->company_count = CompanyService::getCompanyCountByManageId($distribution_manages_id);;
            $item->un_naire_company_count = $item->company_count - $naire_company_count_pre_month;

            if ($naire_company_count_pre_month == 0) {
                $item->average_grade_pre_month = 0;
            } else {
                $item->average_grade_pre_month = round(($total_grade_pre_month / $naire_company_count_pre_month), 2);
            }

            if ($total_naire_company_count == 0) {
                $item->total_average_grade = 0;
            } else {
                $item->total_average_grade = round(($total_grade / $total_naire_company_count), 2);
            }
        }
        return response()->pagination(new ChannelQuestionNaireTransformer(), $data);
    }

    /**
     * 获取上个月调查的公司的数量
     * @param $channel_user_id
     * @return mixed
     */
    public static function getNaireCompanyCountPreMonth($distribution_manages_id, $isPreMonth = true)
    {
        return ChannelQuestionNaire::getNaireCompanyCount($distribution_manages_id, $isPreMonth);
    }

    /**
     * 获取商务上个月的总分数
     * @param $channel_user_id
     */
    public static function getTotalGradePreMonth($distribution_manages_id, $isPreMonth = true)
    {
        return ChannelQuestionNaire::getTotalGrade($distribution_manages_id, $isPreMonth);
    }
}