<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\sale;


use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\sale\SaleRulesLogic;
use app\common\model\property\PropertyHead;
use app\common\model\sale\Sale;
use app\common\lists\ListsSearchInterface;
use app\common\model\sale\SaleRules;
use think\facade\Db;


/**
 * SalePerformanceLists列表
 * Class SalePerformanceLists
 * @package app\adminapi\lists
 */
class SalePerformanceLists extends BaseAdminDataLists implements ListsSearchInterface
{

    public $count = 0;
    public $startDateTime = 0;
    public $endDateTime = 0;

    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/12/15 10:53
     */
    public function setSearch(): array
    {
        return [];
    }

    public function queryWhere()
    {
        $where = [];
        if(isset($this->params['time_range']) && $this->params['time_range']){
            $this->startDateTime = strtotime($this->params['time_range'][0]);
            $this->endDateTime = strtotime($this->params['time_range'][1])+86400-1;
        }else{
            $this->startDateTime = strtotime('-1 month');
            $this->endDateTime = time();
        }
        if(isset($this->params['sale_id']) && $this->params['sale_id']){
            $where[] = ['s.id','=',$this->params['sale_id']];
        }
        return $where;
    }

    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/12/15 10:53
     */
    public function lists(): array
    {
        $this->queryWhere();
        $directWorkerCountSub = Db::table('la_master_worker_register')
            ->field(['sale_id', Db::raw('COUNT(DISTINCT worker_id) AS direct_worker_count')])
            ->where('worker_id', '>', 0)
            ->where('sale_id', '>', 0)
            ->whereBetweenTime('create_time',$this->startDateTime, $this->endDateTime)
            ->group('sale_id')
            ->buildSql();
        $tenantWorkerCountSub = Db::table('la_tenant_register')
            ->alias('lr')
            ->join('la_master_worker mw', 'lr.tenant_id = mw.tenant_id')
            ->field(['lr.sale_id', Db::raw('COUNT(DISTINCT mw.id) AS tenant_worker_count')])
            ->where('lr.tenant_id', '>', 0)
            ->whereBetweenTime('lr.create_time',$this->startDateTime, $this->endDateTime)
            ->group('lr.sale_id')
            ->buildSql();
        $lists = Db::table('la_sale')
            ->alias('s')
            ->leftJoin([$directWorkerCountSub => 'dwc'], 's.id = dwc.sale_id')
            ->leftJoin([$tenantWorkerCountSub => 'twc'], 's.id = twc.sale_id')
            ->field([
                's.id',
                's.sale_name',
                's.mobile',
                Db::raw('COALESCE(dwc.direct_worker_count, 0) AS direct_worker_count'),
                Db::raw('COALESCE(twc.tenant_worker_count, 0) AS tenant_worker_count'),
                Db::raw('COALESCE(dwc.direct_worker_count, 0) + COALESCE(twc.tenant_worker_count, 0)*10 AS total_worker_count')
            ])
            ->limit($this->limitOffset, $this->limitLength)
            ->where($this->queryWhere())
            ->select()->toArray();
        foreach ($lists as &$v) {
            //$v['total_worker_count']
            //$v['total_worker_amount']
            $v['total_worker_amount'] = (SaleRulesLogic::getSaleAmountByRating((float)$v['total_worker_count'],1) * $v['total_worker_count']);
            //$v['id']
            $v['total_property_count'] = 0;
            $v['total_property_amount'] = $this->getSaleAmountBySaleId($v['id']);
        }
        return $lists;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/12/15 10:53
     */
    public function count(): int
    {
        $this->queryWhere();
        $directWorkerCountSub = Db::table('la_master_worker_register')
            ->field(['sale_id', Db::raw('COUNT(DISTINCT worker_id) AS direct_worker_count')])
            ->where('worker_id', '>', 0)
            ->where('sale_id', '>', 0)
            ->whereBetweenTime('create_time',$this->startDateTime, $this->endDateTime)
            ->group('sale_id')
            ->buildSql();
        $tenantWorkerCountSub = Db::table('la_tenant_register')
            ->alias('lr')
            ->leftJoin('la_master_worker mw', 'lr.tenant_id = mw.tenant_id')
            ->field(['lr.sale_id', Db::raw('COUNT(DISTINCT mw.id) AS tenant_worker_count')])
            ->where('lr.tenant_id', '>', 0)
            ->whereBetweenTime('lr.create_time',$this->startDateTime, $this->endDateTime)
            ->group('lr.sale_id')
            ->buildSql();
        return Db::table('la_sale')
            ->alias('s')
            ->leftJoin([$directWorkerCountSub => 'dwc'], 's.id = dwc.sale_id')
            ->leftJoin([$tenantWorkerCountSub => 'twc'], 's.id = twc.sale_id')
            ->field([
                's.id',
                's.sale_name',
                Db::raw('COALESCE(dwc.direct_worker_count, 0) AS direct_worker_count'),
                Db::raw('COALESCE(twc.tenant_worker_count, 0) AS tenant_worker_count'),
                Db::raw('COALESCE(dwc.direct_worker_count, 0) + COALESCE(twc.tenant_worker_count, 0) AS total_worker_count')
            ])
            ->where($this->queryWhere())
            ->count();
    }

    public function setExcelComplexFields(): array
    {
        $zh_cn_fields = [
            '姓名','手机号','入驻加盟总绩效金额','物业合作总绩效金额'
        ];
        $data_fields = ['sale_name','mobile','total_worker_amount','total_property_amount'];
        return [
            'zh_cn_fields' => $zh_cn_fields,
            'data_fields' => $data_fields
        ];
    }




    /**
     * 根据档位获取销售绩效金额
     *
     * @param int $rating 档位
     * @return float|null 对应的金额，若未找到匹配的档位则返回0
     */
    public function getSaleAmountBySaleId(int $sale_id): ?float
    {
        $this->queryWhere();
        $rating_values = PropertyHead::where('sale_id', $sale_id)
            ->where('is_cooperate', 1)
            ->whereBetweenTime('create_time',$this->startDateTime, $this->endDateTime)
            ->column('rating_value');
        $countAmount = 0;
        foreach ($rating_values as $rating_value) {
            $countAmount += SaleRulesLogic::getSaleAmountByRating((float)$rating_value, 2);
        }
        return $countAmount;
    }










}