<?php
namespace app\adminapi\lists\finance;

use app\adminapi\lists\BaseAdminDataLists;
use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\lists\ListsSearchInterface;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\user\UserAccountLog;
use app\common\service\FileService;


/**
 * 账记流水列表
 * Class WorkerAccountLogLists
 * @package app\adminapi\lists\finance
 */
class WorkerAccountLogLists extends BaseAdminDataLists implements ListsSearchInterface
{

    /**
     * @notes 搜索条件
     * @return array
     */
    public function setSearch(): array
    {
        return [
            '=' => ['al.change_type','worker_number'],
        ];
    }


    /**
     * @notes 搜索条件
     */
    public function queryWhere()
    {
        $where = [];
        // 用户余额
        if (isset($this->params['type']) && $this->params['type'] == 'um') {
            $where[] = ['change_type', 'in', WorkerAccountLogEnum::getUserMoneyChangeType()];
        }

        if (!empty($this->params['user_info'])) {
            $where[] = ['u.sn|u.nickname|u.mobile|u.account', 'like', '%' . $this->params['user_info'] . '%'];
        }

        if (!empty($this->params['start_time'])) {
            $where[] = ['al.create_time', '>=', strtotime($this->params['start_time'])];
        }

        if (!empty($this->params['end_time'])) {
            $where[] = ['al.create_time', '<=', strtotime($this->params['end_time'])];
        }

        return $where;
    }


    /**
     * @notes 获取列表
     * @return array
     */
    public function lists(): array
    {
        $field = 'u.nickname,u.account,u.sn,u.avatar,u.mobile,al.action,al.change_amount,al.left_amount,al.change_type,al.work_sn,al.create_time';
        $lists = MasterWorkerAccountLog::alias('al')
            ->join('master_worker u', 'u.id = al.worker_id')
            ->field($field)
            ->where($this->searchWhere)
            ->where($this->queryWhere())
            ->order('al.id', 'desc')
            ->limit($this->limitOffset, $this->limitLength)
            ->select()
            ->toArray();

        foreach ($lists as &$item) {
            $item['avatar'] = FileService::getFileUrl($item['avatar']);
            $item['change_type_desc'] = WorkerAccountLogEnum::getChangeTypeDesc($item['change_type']);
            $symbol = $item['action'] == WorkerAccountLogEnum::INC ? '+' : '-';
            $item['change_amount'] = $symbol . $item['change_amount'];
            $item['total_amount'] = bcadd($item['left_amount'], $item['change_amount'], 2);
        }

        return $lists;
    }


    /**
     * @notes 获取数量
     * @return int
     */
    public function count(): int
    {
        return MasterWorkerAccountLog::alias('al')
            ->join('master_worker u', 'u.id = al.worker_id')
            ->where($this->queryWhere())
            ->where($this->searchWhere)
            ->count();
    }
}