<?php

namespace App\Services;

use App\Facilitator;
use App\Traits\ServiceAppAop;
use App\DischargeTask;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;

class DischargeTaskService
{
    use ServiceAppAop;

    protected $modelClass = DischargeTask::class;

    // 编辑卸货任务
    public function updateDischargeTask(DischargeTask $dischargeTask, array $param): array
    {
        if ($dischargeTask->status == 3) return ['success' => false, 'message' => '已完成的卸货任务不可进行编辑'];

        if(!empty($param['status'])){
            if( $param['status'] > 0 && $dischargeTask->facilitator_id == 0){
                return ['success' => false, 'message' => '未指定服务商的卸货任务,不可进行当前编辑'];
            }
            if($param['status'] ==3 && $dischargeTask->status == 0){
                return ['success' => false, 'message' => '未指定服务商的卸货任务,不可进行当前编辑'];
            }
        }

        $bool = $dischargeTask->update($param);

        if ($bool){
            $dischargeTask->refresh();
            $dischargeTask->loadMissing('owner','facilitator');
            return ['success' => true, 'data' => $dischargeTask];
        }
        else return ['success' => false];
    }

    // 删除卸货任务
    public function deleteDischargeTask(DischargeTask $dischargeTask): array
    {
        if ($dischargeTask->status == 3) return ['success' => false, 'message' => '已完成的卸货任务不可进行删除'];

        try {
            $dischargeTask->delete();
            return ['success' => true];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    // 指定服务商
    public function updateTaskFacilitator(DischargeTask $dischargeTask, array $param): array
    {
        unset($param['owner'],$param['income_at']);

        if ($param['id']) unset($param['id']);
        if ($dischargeTask->status >= 1) return ['success' => false, 'message' => '当前任务状态不可修改'];
        if (empty($param['expenditure_at'])) $param['expenditure_at'] = now();
        if (empty($param['status'])) $param['status'] = 1;

        $param['expenditure_total_cost'] = $param['expenditure_unit_price'] * $param['expenditure_amount'];

        $bool = $dischargeTask->update($param);

        if ($bool == 1) {
            $dischargeTask->loadMissing('owner','facilitator');
            return ['success' => true, 'data' => $dischargeTask];
        } else return ['success' => false];
    }

    // 创建卸货任务
    public function createTask(array $param): array
    {
        if (isset($param['id'])) unset($param['id']);
        if (empty($param['income_total_cost'])) $param['income_total_cost'] = $param['income_unit_price'] * $param['income_amount'];
        if (empty($param['income_at'])) $param['income_at'] = now();
        if (empty($param['status'])) $param['status'] = 0;

        $dischargeTask = DischargeTask::query()->create($param);
        $dischargeTask->loadMissing('facilitator', 'owner','warehouse');

        return ['success' => true, 'data' => $dischargeTask];
    }

    // 卸货任务
    public function getJson(Collection $dischargeTasks): array
    {
        $json = [];
        foreach ($dischargeTasks as $dischargeTask) {

            /** @var DischargeTask $dischargeTask */
            /** @var Carbon $date */
            $date = $dischargeTask['created_at'];

            $json[] = [
                $date->toDateTimeString(),
                $dischargeTask->owner->name ?? '',
                DischargeTask::types[$dischargeTask['type']] ?? '',
                $dischargeTask->numbers ?? '',
                ($dischargeTask['income_amount']).'',
                DischargeTask::units[$dischargeTask['income_unit']] ?? '',
                $dischargeTask->income_unit_price ?? '',
                $dischargeTask->income_total_cost ?? '',
                DischargeTask::status[$dischargeTask['status']] ?? '',
                $dischargeTask->income_remark  ?? ' ',
            ];
        }
        return $json;
    }

    // 结算报表
    public function getStatementsJson(Collection $dischargeTasks): array
    {
        $json = [];
        foreach ($dischargeTasks as $dischargeTask) {

            /** @var DischargeTask $dischargeTask */
            /** @var Carbon $date */
            $date = $dischargeTask['created_at'];

            $json[] = [
                $date->toDateTimeString() ,                          // 日期
                $dischargeTask->owner->name ?? '',                  // 客户名称
                $dischargeTask->warehouse->name ?? '',              // 仓库
                DischargeTask::types[$dischargeTask['type']] ?? '',   // 作业名称
                $dischargeTask['numbers'],                            // 入库单号
                // --- 收入信息
                ($dischargeTask['income_amount']).'',                                  // 数量
                DischargeTask::units[$dischargeTask['income_unit']] ?? '',        // 单位
                $dischargeTask['income_unit_price'],                              // 收入单价
                $dischargeTask['income_total_cost'],                              // 收入合计
                // --- 支出信息
                $dischargeTask->facilitator->name ?? '',                  // 服务商
                ($dischargeTask['expenditure_amount']).'',                             // 数量
                DischargeTask::units[$dischargeTask['expenditure_unit']] ?? '',   // 单位
                $dischargeTask['expenditure_unit_price'],                         // 支出单价
                $dischargeTask['expenditure_total_cost'],                         // 支出合计
                // --- 其他信息
                DischargeTask::status[$dischargeTask['status']] ?? '',    // 状态
                $dischargeTask->income_remark ?? '',                          // 收入备注
                $dischargeTask->expenditure_remark ?? '',                     // 支出备注
            ];
        }
        return $json;
    }

    // 服务商对账单
    public function getFacilitatorStatementsJson(Collection $dischargeTasks): array
    {
        $json = [];
        foreach ($dischargeTasks as $dischargeTask) {

            /** @var Carbon $date */
            $date = $dischargeTask->created_at;

            $json[] = [
                $date->toDateTimeString(),                           // 日期
                $dischargeTask->facilitator->name ?? '',      // 服务商
                $dischargeTask['expenditure_amount'].'',                             // 数量
                DischargeTask::units[$dischargeTask['expenditure_unit']] ?? '',   // 单位
                $dischargeTask['expenditure_unit_price'].'',                         // 支出单价
                $dischargeTask['expenditure_total_cost'].'',                         // 支出合计
            ];
        }
        return $json;
    }
}
