<?php
namespace app\api\lists\property;

use app\api\lists\BaseApiDataLists;
use app\common\lists\ListsExtendInterface;
use app\common\lists\ListsSearchInterface;
use app\common\model\property\PropertyCommission;
use app\common\model\property\PropertyHead;
use app\common\model\property\PropertySurplusLog;
use app\common\model\works\ServiceWork;
use DateTime;

/**
 * 订单列表
 */
class PropertySurplusLogLists extends BaseApiDataLists implements ListsSearchInterface,ListsExtendInterface
{

    public function setSearch(): array
    {
        return [
            '=' => ['status','property_head_id'],
        ];
    }
    public function queryWhere()
    {
        // 指定用户
        $propertyHeadId = PropertyHead::where('user_id',$this->userId)->value('id');
        $where[] = ['property_head_id', '=', $propertyHeadId];
        isset($this->params['in_out']) && $this->params['in_out'] && $where[] = ['in_out', '=', $this->params['in_out']];
        if(isset($this->params['start_time']) && $this->params['start_time']){
            $startDateTime = $this->params['start_time'];
            $date = new DateTime($startDateTime);
            $date->modify('+1 month');
            $startDateTime = strtotime($startDateTime);
            $endDateTime = strtotime($date->format('Y-m'))-1;
            $where[] = ['create_time', 'BETWEEN', [$startDateTime, $endDateTime]];
        }
        return $where;
    }
    public function lists(): array
    {
        $lists = PropertySurplusLog::with(['propertyHead'])->where($this->searchWhere)
            ->where($this->queryWhere())
            ->limit($this->limitOffset, $this->limitLength)
            ->field(['id','in_out','property_commission_id','amount','status','remark','create_time','update_time','property_head_id'])
            ->order('create_time desc')
            ->select()
            ->toArray();
        foreach ($lists as &$item){
            if($item['property_commission_id']){
                $work_id = PropertyCommission::where('id',$item['property_commission_id'])->value('work_id');
                $item['work_title'] = ServiceWork::where('id',$work_id)->value('title');
            }
            $item['surplus_sn'] = date('YmdHis',strtotime($item['create_time']));
            $item['head_bank_card'] = $item['propertyHead']?$item['propertyHead']['head_bank_card']:'';
        }
        return $lists;
    }

    /**
     * @notes  获取数量
     * @return int
     */
    public function count(): int
    {
        return PropertySurplusLog::where($this->searchWhere)->where($this->queryWhere())->count();
    }
    /**
     * @notes  返回扩展数据
     * @return array|int
     */
    public function extend(): array
    {
        return [
            'month_amount' => PropertySurplusLog::where($this->searchWhere)->where($this->queryWhere())->sum('amount')
        ];
    }

}