<?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\logic\financial;


use app\common\model\financial\MasterSettlementDetails;
use app\common\logic\BaseLogic;
use app\common\model\master_worker\EngineerSettlement;
use think\facade\Db;
use think\facade\Log;


/**
 * MasterSettlementDetails逻辑
 * Class MasterSettlementDetailsLogic
 * @package app\adminapi\logic
 */
class MasterSettlementDetailsLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/12/02 15:57
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            MasterSettlementDetails::create([
                'account_log_id' => $params['account_log_id'],
                'payment_time' => $params['payment_time'],
                'batch_number' => $params['batch_number'],
                'status' => $params['status'],
                'master_worker_id' => $params['master_worker_id'],
                'amount_change' => $params['amount_change'],
                'change_time' => $params['change_time'],
                'remark' => $params['remark'],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/12/02 15:57
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            MasterSettlementDetails::where('id', $params['id'])->update([
                'account_log_id' => $params['account_log_id'],
                'payment_time' => $params['payment_time'],
                'batch_number' => $params['batch_number'],
                'status' => $params['status'],
                'master_worker_id' => $params['master_worker_id'],
                'amount_change' => $params['amount_change'],
                'change_time' => $params['change_time'],
                'remark' => $params['remark'],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/12/02 15:57
     */
    public static function delete(array $params): bool
    {
        return MasterSettlementDetails::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/12/02 15:57
     */
    public static function detail($params): array
    {
        return MasterSettlementDetails::findOrEmpty($params['id'])->toArray();
    }


    /**
     * @notes 更新批次
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/12/02 15:57
     */
    public static function upBatchStatus($params,$batch_number)
    {
        $deadline_time = $params['deadline_time'];
        $settlement_type = $params['settlement_type'];
        /*$lists =   Db::name('master_worker')->alias('a')->field([
            'a.id','a.real_name','a.nickname','a.worker_number','e.account_holder','e.bank_name','e.opening_branch','e.account as bank_account','b.id as detail_id'
        ])
            ->leftJoin('master_settlement_details b', 'a.id = b.master_worker_id AND b.status = 1')
            ->leftJoin('bank_account e', 'a.id = e.worker_id')
            ->where('a.audit_state', '=', 1)
            ->where('a.user_money', '>', 0)
            ->where('b.status', '=', 1)
            ->where('a.settlement_type', '=', $settlement_type)
            ->where('b.change_time', '<', $deadline_time)
            ->select()->toArray();*/
        $lists = Db::name('master_worker')->alias('a')->field([
                    'a.id','a.real_name','a.nickname','a.worker_number','a.user_money',
                    'e.account_holder','e.bank_name','e.opening_branch','e.account as bank_account',
                    Db::raw("sum(b.amount_change) as left_amount")
                ])
                ->leftJoin('master_settlement_details b', 'a.id = b.master_worker_id AND b.status = 1')
                ->leftJoin('bank_account e', 'a.id = e.worker_id')
                ->where('a.audit_state', '=', 1)
                ->where('a.user_money', '>', 0)
                ->where('b.status', '=', 1)
                ->where('a.settlement_type', '=', $settlement_type)
                ->where('b.change_time', '<', $deadline_time)
                ->group('a.id')
                ->order('a.id desc')
                ->having('left_amount > 0')
                ->select()->toArray();

        // 根据条件获取能打款的 工程师 left_amount user_money
        $can_payment_ids = [];
        $insertXlsData = [];
        foreach ($lists as $item) {
            if(!empty($item['left_amount']) && !empty($item['user_money']) && !((float)$item['left_amount'] > (float)$item['user_money'])){
                $can_payment_ids[] = $item['id'];
                $insertXlsData[] = [
                    'master_worker_id' => $item['id'],
                    'worker_number' => $item['worker_number'],
                    'engineer_name' => $item['account_holder'],

                    'bank_account' => $item['bank_account'],
                    'bank_name' => $item['bank_name'],
                    'opening_branch' => $item['opening_branch'],

                    'original_balance' => $item['user_money'],
                    'total_settlement_amount' => $item['left_amount'],
                    'payment_status' => 0,
                    'is_export' => 1,

                    'batch_number'=> $batch_number,
                    'create_time'=> time(),
                    'update_time'=> time(),
                    'admin_id'=> 0,
                    'is_deduction'=> 0,
                ];
            }
        }
        //由可发工程师， 修改该工程师 截止$deadline_time 的 状态和批号
        MasterSettlementDetails::where('master_worker_id','in', $can_payment_ids)
            ->where('change_time', '<', $deadline_time)
            ->where('status', '=', 1)
            ->update([
                'status' => 2,
                'batch_number' => $batch_number,
            ]);
        // 生成 可发 数据表格
        Db::name('engineer_settlement')->insertAll($insertXlsData);

        Log::info('insertXlsData:'.json_encode($insertXlsData));
        return $insertXlsData;
    }



}