<?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\effective;


use app\adminapi\logic\works\ServiceWorkLogic;
use app\common\enum\GoodsEnum;
use app\common\enum\PayEnum;
use app\common\enum\WorkEnum;
use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\model\orders\OrderEffectiveLog;
use app\common\logic\BaseLogic;
use app\common\model\goods\Goods;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\master_worker\MasterWorkerRetentionMoneyLog;
use app\common\model\orders\RechargeOrder;
use app\common\model\recharge\OrderGoods;
use app\common\model\service_area\ServiceArea;
use app\common\model\works\ServiceWork;
use think\facade\Db;


/**
 * OrderEffectiveLog逻辑
 * Class OrderEffectiveLogLogic
 * @package app\adminapi\logic
 */
class OrderEffectiveLogLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/01/17 11:10
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            OrderEffectiveLog::create([
                'effective_id' => $params['effective_id'],
                'sn' => $params['sn'],
                'user_id' => $params['user_id'],
                'work_id' => $params['work_id'],
                'goods_id' => $params['goods_id'],
                'effective_unit' => $params['effective_unit'],
                'effective_num' => $params['effective_num'],
                'remark' => $params['remark'],
                'end_effective_time' => $params['end_effective_time'],
            ]);

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


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/01/17 11:10
     */
    public static function edit(array $params): bool
    {
        if($params['operation_type'] == 1){
            //无需保修 - 恢复状态
            OrderEffectiveLog::where('id', $params['id'])->update([
                'effective_status' => 0,
                'effective_time' => 0,
            ]);
            return true;
        }

        // 用户已提交 - 客服处理下单
        if($params['edit_status'] == 1){
            self::effectiveServiceWork($params);
        }
        // 保修中 - 客服处理新增定金 ，尾款可由工程师完成 =0 || >0 均可
        if($params['edit_status'] == 2){
            // 惩罚金额
            OrderEffectiveLog::where('id', $params['id'])->update([
                'penalty_amount' => $params['penalty_amount']
            ]);
        }
        return true;
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/01/17 11:10
     */
    public static function delete(array $params): bool
    {
        return OrderEffectiveLog::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2025/01/17 11:10
     */
    public static function detail($params): array
    {
        return OrderEffectiveLog::findOrEmpty($params['id'])->toArray();
    }
    /**
     * @notes 计算工单所得的 提成+质保金
     */
    public static function commissionAndAssuranceDeposit($serviceWork)
    {
        $change_amount = MasterWorkerAccountLog::where([
            'change_object'=>WorkerAccountLogEnum::UM,'change_type'=>WorkerAccountLogEnum::UM_INC_ADMIN,
            'action'=>WorkerAccountLogEnum::INC,'worker_id'=>$serviceWork['master_worker_id'],
            'work_sn'=>$serviceWork['work_sn']])->value('change_amount');
        $retentionAmount = MasterWorkerRetentionMoneyLog::where(['action'=>WorkerAccountLogEnum::INC,'source'=>2,'worker_id'=>$serviceWork['master_worker_id'],'work_id'=>$serviceWork['id']])->value('amount');
        return bcadd((string)$change_amount,(string)$retentionAmount,2);
    }


    /**
     * @notes 用户已提交 - 客服处理下单
     */
    public static function effectiveServiceWork($params)
    {
        Db::startTrans();
        try {
            /*{ name: '无需保修', value: 1 },
            { name: '原工程师修复', value: 2 },
            { name: '新工程师修复', value: 3 }*/
            $effectiveLog = OrderEffectiveLog::where('id', $params['id'])->find();

            /*$effectiveLog['user_id']
            $effectiveLog['work_id']
            $effectiveLog['goods_id']*/
            // 原工单信息 $effectiveLog['work_id']
            $serviceWork = ServiceWork::find($effectiveLog['work_id'])->toArray();

            if($params['operation_type'] == 2){
                //原工程师修复
                OrderEffectiveLog::where('id', $params['id'])->update([
                    'effective_status' => 2
                ]);
                // 原工程师为0
                $service_fee = 0;
                $master_worker_id = $serviceWork['master_worker_id'];

            }else if($params['operation_type'] == 3){
                //新工程师修复
                OrderEffectiveLog::where('id', $params['id'])->update([
                    'effective_status' => 2
                ]);
                // 计算原工程师的原工单的提成+质保金
                //$service_fee = self::commissionAndAssuranceDeposit($serviceWork);
                $service_fee = 0;
                if($serviceWork['master_worker_id'] == $params['master_worker_id']){
                    throw new \Exception('请选择新的工程师');
                }
                $master_worker_id = $params['master_worker_id'];
            }else{
                throw new \Exception('操作类型错误');
            }

            //生成服务工单
            $work_data = [
                'work_sn' => generate_sn(ServiceWork::class, 'work_sn'),
                'real_name' => $serviceWork['real_name'],
                'mobile' => $serviceWork['mobile'],
                'address' => $serviceWork['address'],

                'province' => $serviceWork['province']??0,
                'city' => $serviceWork['city']??0,
                'area_name' => $serviceWork['area_name']??'',
                'service_area_id' => $serviceWork['service_area_id']??0,

                'title' => $serviceWork['title']??'',
                'category_type' => $serviceWork['category_type'],
                'goods_category_ids' => $serviceWork['goods_category_ids'],
                'goods_category_id' => $serviceWork['goods_category_id'],

                'user_id'=>$serviceWork['user_id'],
                'lon'=>$serviceWork['lon'],
                'lat'=>$serviceWork['lat'],
                'property_activity_id'=>0,
                'user_equity_id'=>0,

                'work_pay_status'=>WorkEnum::IS_PAY_STATUS,
                'appointment_time' => $params['appointment_time']?strtotime($params['appointment_time']):0,
                'order_effective_id'=>$params['id'],
                'base_service_fee' => 0,
                'service_fee' => 0,
                'work_total'=>0,
                'work_amount'=>0,
            ];

            $service_work = ServiceWork::create($work_data);

            //生成支付订单
            $data = [
                'work_id'=> $service_work['id'],
                'sn' => generate_sn(RechargeOrder::class, 'sn'),
                'order_type'=>0,//服务订单
                'order_terminal' => 1,
                'payment_type'=>1,
                'user_id' => $serviceWork['user_id'],
                'pay_way' => 2,
                'pay_status' => PayEnum::ISPAID,
                'pay_time' => time(),
                'paid_amount' => 0,
                'coupon_id'=>0,
                'coupon_price'=>0,
                'order_total' => 0,
                'order_amount' => 0,
            ];
            $order = RechargeOrder::create($data);

            //生成订单服务详情
            $goods = Goods::findOrEmpty($effectiveLog['goods_id']);
            OrderGoods::create([
                'sn' => $order['sn'],
                'goods_id' => $effectiveLog['goods_id'],
                'category_type' => $goods['category_type'],
                'goods_category_ids' => $goods['goods_category_ids'],
                'goods_category_id' => $goods['goods_category_id'],
                'goods_name' => $goods['goods_name'],
                'goods_image' => $goods['goods_image'],
                'goods_video' => $goods['goods_video'],
                'goods_number' => $goods['goods_number'],
                'good_unit' => $goods['good_unit'],
                'goods_size' => $goods['goods_size'],
                'goods_type' => $goods['goods_type'],
                'goods_brand' => $goods['goods_brand'],
                'install_guide' => $goods['install_guide'],
                'goods_payment_type'=>1,
                'base_service_fee' => $goods['base_service_fee'],
                'service_total' => $goods['service_total'],
                'service_fee' => $goods['service_fee'],
                'service_image' => $goods['service_image'],
                'warranty_period'=>$goods['warranty_period'],
                'fee_schedule' => $goods['fee_schedule'],
                'goods_status' => $goods['goods_status'],
                'is_show' => 0,
            ]);

            Db::commit();

            //派单
            if(isset($service_work['id']) && !empty($service_work['id'])) ServiceWorkLogic::allocateWorker(['id'=>$service_work['id'],'master_worker_id'=>$master_worker_id],$params['adminInfo']);

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





}