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


use app\common\logic\finance\TownShareProfit;
use app\common\logic\finance\VillageShareProfit;
use app\common\logic\ShopRequestLogic;
use app\common\model\Approve;
use app\common\model\company\CompanyAccountLog;
use app\common\model\CompanyComplaintFeedback;
use app\common\model\contract\Contract;
use app\common\model\dict\DictData;
use app\common\model\ShopMerchantSettleinLog;
use app\common\model\task\Task;
use app\common\logic\BaseLogic;
use app\common\model\Company;
use app\common\model\informationg\UserInformationg;
use app\common\model\task_scheduling_plan\TaskSchedulingPlan;
use app\common\model\task_template\TaskTemplate;
use app\common\model\user\User;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

/**
 * 任务逻辑
 * Class TaskLogic
 * @package app\adminapi\logic\task
 */
class TaskLogic extends BaseLogic
{


    /**
     * @notes 添加任务
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/08/05 13:39
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            Task::create([
                'title' => $params['title'],
                'template_id' => $params['template_id'],
                'company_id' => $params['company_id'],
                // 'admin_id' => $params['admin_id'],
                'start_time' => strtotime($params['start_time']),
                'end_time' => strtotime($params['end_time']),
                'director_uid' => $params['director_uid'],
                'type' => $params['type'],
                'status' => $params['status'],
                'content' => $params['content'],
                'extend' => json_encode($params['extend'])
            ]);

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

    /**
     * 定时添加任务
     */
    public static function CronAdd(array $v, $datas): bool
    {
        try {
            if ($v['types'] == 3) {
                $task = Task::where('template_id', $v['id'])->find();
                if ($task) {
                    // 累计任务进行天数,单次任务结算时,用于判断任务是否超时
                    TaskTemplate::where('id', $v['id'])->inc('day_count')->update();
                    // Task::where('template_id', $v['id'])->update(['start_time' => strtotime($task['start_time']) + 86400, 'end_time' => strtotime($task['end_time']) + 86400]);
                    // TaskTemplate::where('id', $v['id'])->inc('day_count')->update();
                    return true;
                }
            }
            $v_day_count=$v['day_count'];
            $v_day_count=$v_day_count+1;
            $time = strtotime(date('Y-m-d'));
            Db::startTrans();
            $TaskSchedulingPlan_data = [
                'create_user_id' => 0,
                'company_id' => $v['company_id'],
                'template_id' => $v['id'],
                'scheduling_id' => $v['task_scheduling'],
                'start_time' => $time,
                'end_time' => $time + 86399,
                'sn' => User::createUserSn(),
                'status' => 1
            ];
            $TaskSchedulingPlan = TaskSchedulingPlan::create($TaskSchedulingPlan_data);
            $arr = [
                'template_id' => $v['id'],
                'scheduling_plan_id' => $TaskSchedulingPlan['id'],
                'company_id' => $v['company_id'],
                'title' => $v['title'],
                'money' => $v['money'],
                'type' => $v['type'],
                'content' => $v['content'],
                'start_time' => $time,
                'end_time' => $time + 86399,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $data = $arr;
            $data['money'] = self::task_money($v, $datas);
            $data['extend'] = json_encode($v['extend']);
            //信息更新
            if ($v['type'] == 31) {
                $finds = TaskTemplate::where('id', $v['id'])->field('information_count,information_day_count')->find();
                $update = 0;
                if ($finds['information_count'] > $finds['information_day_count']) {
                    $day_count = $finds['information_count'] - $finds['information_day_count'];
                    if ($day_count >= 5) {
                        $update = 5;
                    } else {
                        $update = $day_count;
                    }
                }
                $data["extend"] = json_encode(['informationg' => ['count' => 5, 'update' => $update]]);
                TaskTemplate::where('id', $v['id'])->inc('information_day_count', 5)->update();
            }
            if ($v['type'] == 32) {
                $data['director_uid'] = $datas['company_info']['user_id'];
            }
            //入股任务
            if ($v['type'] == 35) {
                $responsible_area = Company::where('id', $v['company_id'])->value('responsible_area');
                if ($responsible_area) {
                    $responsible_area = explode(',', $responsible_area);
                } else {
                    Log::error('定时任务添加失败:没有区域' . json_encode($v));
                    return false;
                }
                if (isset($v['extend']['shareholder'])) {
                    $shareholder_user = User::where('id', $v['extend']['shareholder']['user_id'])->field('id,nickname,brigade')->find();

                    $v['extend']['shareholder']['money'] = $v['recharge'];
                    $v['extend']['shareholder']['over_decimal'] = $v['over_decimal'];
                    foreach ($responsible_area as $kkk => $vvv) {
                        $v['extend']['shareholder']['user_list'][$kkk] = ['info' => $shareholder_user['nickname'] . '需缴纳' . $vvv . '队,股金:' . bcdiv($v['recharge'], count($responsible_area), 2), 'time' => $v['create_time']];
                    }
                    $data['director_uid'] = $v['extend']['shareholder']['user_id'];
                }
                $data['extend'] = json_encode($v['extend']);
                $money_one = bcmul($v['stage_day_one'], $v['money'], 2);
                $money_two = bcmul($v['stage_day_two'], $v['money_two'], 2);
                $data['money'] = bcadd($money_one, $money_two);
            }
            //片区交易
            if ($v['type'] == 33) {
                //基础金额*(每日基户数*天数)//且户数小于公司总户数
                $user_count = UserInformationg::where('company_id', $v['company_id'])->count();
                //
                if ($v_day_count == 0) {
                    $user_count_two = 5 * 1;
                } else {
                    $user_count_two = 5 * $v_day_count;
                }
                if ($user_count_two > $user_count) {
                    $user_count_money = 58 * $user_count;
                } else {
                    $user_count_money = 58 * $user_count_two;
                }
                $extend = [
                    'transaction' => ['arr' => ['day_money' => $user_count_money, 'total_price' => 0]]
                ];
                $data['extend'] = json_encode($extend);
            }
            // 其他任务
            if ($v['type'] == 34) {
                // is_commit 是否提交 note 详情描述 annex 附件
                $extend = [
                    'other'=> [
                            'is_commit' => 0,
                            'note' => '',
                            'annex' => [],
                            'video_annex' => [],
                    ]
                ];
                $data['extend'] = json_encode($extend);
            }
            $task_id = (new Task())->insertGetId($data);
            TaskSchedulingPlan::where('id', $TaskSchedulingPlan['id'])->update(['task_id' => $task_id, 'is_execute' => 1]);
            TaskTemplate::where('id', $v['id'])->inc('day_count')->update();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('定时任务添加失败'.$e->getMessage().'。line:'.$e->getLine());
            return false;
        }
    }
    //任务金额
    private static function task_money($v, $datas)
    {
        $v_day_count=$v['day_count'];
        $v_day_count=$v_day_count+1;
        $stageDayOneAccumulative = $v['stage_day_one']; // 第一阶段天数
        $stageDayTwoAccumulative = bcadd($v['stage_day_one'], $v['stage_day_two']); // 第二阶段天数 第一+第二
        if ($v['types'] == 1 || $v['types'] == 3) {
            if ($v_day_count <= $stageDayOneAccumulative) {
                return $v['money'];
            } else {
                return  $v['money_two'];
            }
        } elseif ($v['types'] == 2) {
            if ($v_day_count<= $stageDayOneAccumulative) {
                return $v['money'];
            } elseif ($stageDayOneAccumulative < $v_day_count && $v_day_count <= $stageDayTwoAccumulative) {
                return  $v['money_two'];
            } else {
                return  $v['money_three'];
            }
        } else {
            if ($v_day_count <= $v['stage_day_one']) {
                $a = $v['money'];
            } else {
                $a =  $v['money_two'];
            }
            if ($v_day_count >= $v['stage_day_two']) {
                TaskTemplate::where('id', $v['id'])->update(['status' => 0]);
            }
            return $a;
        }
    }

    /**
     * @notes 更新任务状态
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/08/05 13:39
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            Task::where('id', $params['id'])->update(['status' => 3, 'update_time' => 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 2023/08/05 13:39
     */
    public static function delete(array $params): bool
    {
        return Task::destroy($params['id']);
    }


    /**
     * @notes 获取任务详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2023/08/05 13:39
     */
    public static function detail($params): array
    {
        $task = Task::findOrEmpty($params['id'])->toArray();
        if ($task) {
            if (isset($task['extend']['informationg'])) {
                $task['extend']['informationg'] = UserInformationg::where('id', $task['extend']['informationg'])->field('name,phone,sex,age,update_time')
                    ->find()->toArray();
            }
        }
        return $task;
    }

    /**
     * 定时添加任务
     */
    public static function VillageCronAdd(array $taskTemplate)
    {
        try {
            Log::info(['村管理公司定时任务下发-任务模板', $taskTemplate]);
            // 单次任务不重复下发,在结算时刷新任务时间
            if ($taskTemplate['types'] == 3) {
                $task = Task::where('template_id', $taskTemplate['id'])->find();
                if ($task) {
                    // 累计任务进行天数,单次任务结算时,用于判断任务是否超时
                    TaskTemplate::where('id', $taskTemplate['id'])->inc('day_count')->update();
                    return true;
                }
            }
            Db::startTrans();

            $time = strtotime(date('Y-m-d'));
            $directorUid = 0; // 指派给
            $marketingManagerUser = (new User())->searchLiaisonMan($taskTemplate['company_id']);
            Log::info(['村管理公司定时任务下发-村联络员user信息', $marketingManagerUser]);
            $directorUid = $marketingManagerUser['id'];

            // 添加任务计划
            $TaskSchedulingPlan = self::addTaskSchedulePlan($taskTemplate, $time);
            Log::info(['村管理公司定时任务下发-添加plan结果', $TaskSchedulingPlan]);

            // 添加任务
            $task_id = self::addVillageTask($taskTemplate, $TaskSchedulingPlan, $time, $directorUid);
            Log::info(['村管理公司定时任务下发-添加task结果', $task_id]);

            // 关联任务计划和任务
            TaskSchedulingPlan::where('id', $TaskSchedulingPlan['id'])->update(['task_id' => $task_id, 'is_execute' => 1]);

            // 任务累计进行天数 +1
            TaskTemplate::where('id', $taskTemplate['id'])->inc('day_count')->update();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error(['村管理公司定时任务添加失败', $e->getFile(), $e->getLine(), $e->getMessage()]);
        }
    }
    private static function addVillageTask($taskTemplate, $TaskSchedulingPlan, $time, $directorUid)
    {
        $arr = [
            'template_id' => $taskTemplate['id'],
            'scheduling_plan_id' => $TaskSchedulingPlan['id'],
            'company_id' => $taskTemplate['company_id'],
            'title' => $taskTemplate['title'],
            'money' => $taskTemplate['money'],
            'type' => $taskTemplate['type'],
            'content' => $taskTemplate['content'],
            'start_time' => $time,
            'end_time' => $time + 86399,
            'director_uid' => $directorUid, // 指派给
            'create_time' => time(),
            'update_time' => time(),
        ];
        $data = $arr;
        $data['money'] = self::countVillageTaskMoney($taskTemplate);
        $task_id = (new Task())->insertGetId($data);
        return $task_id;
    }

    private static function countVillageTaskMoney($template)
    {
        $v_day_count = $template['day_count'];
        $v_day_count = $v_day_count + 1;
        $stageDayOneAccumulative = $template['stage_day_one']; // 第一阶段天数
        $stageDayTwoAccumulative = bcadd($template['stage_day_one'], $template['stage_day_two']); // 第二阶段天数 第一+第二
        $stageDayThreeAccumulative = bcadd($stageDayTwoAccumulative, $template['stage_day_three']); // 第三阶段天数 第二阶段累计值+第三

        // 单次和循环任务
        if ($template['types'] == 1 || $template['types'] == 3) {
            if ($v_day_count <= $stageDayOneAccumulative) {
                // 第一阶段金额
                return $template['money'];
            } else if ($stageDayOneAccumulative < $v_day_count && $v_day_count<= $stageDayTwoAccumulative) {
                // 第二阶段金额
                return  $template['money_two'];
            } else if ( $stageDayTwoAccumulative < $v_day_count && $v_day_count <= $stageDayThreeAccumulative) {
                // 第三阶段金额
                return  $template['new_money_three'];
            }
        } elseif ($template['types'] == 2) {
            // 长期任务

            // 协助小组服务团队完成辖区内的交易 第二个阶段即长期
            $townTaskTypeList = DictData::where(['type_value' => 'village_task_type', 'status' => 1])->column('value', 'id');
            if (isset($townTaskTypeList[$template['type']]) && $townTaskTypeList[$template['type']]=== 'village_task_type_2') {
                if ($v_day_count<= $stageDayOneAccumulative) {
                    // 第一阶段金额
                    return $template['money'];
                } elseif ( $v_day_count > $stageDayOneAccumulative) {
                    // 长期金额
                    return  $template['money_three'];
                }
            }

            if ($v_day_count<= $stageDayOneAccumulative) {
                // 第一阶段金额
                return $template['money'];
            } elseif ( $stageDayOneAccumulative < $v_day_count && $v_day_count <= $stageDayTwoAccumulative) {
                // 第二阶段金额
                return  $template['money_two'];
            } else if ($stageDayTwoAccumulative < $v_day_count && $template['stage_day_three'] == 0) {
                // 第三阶段为空,返回长期金额
                return  $template['money_three'];
            } else if ( $stageDayTwoAccumulative < $v_day_count && $v_day_count <=$stageDayThreeAccumulative) {
                // 第三阶段金额
                return  $template['new_money_three'];
            } else {
                // 长期金额
                return  $template['money_three'];
            }
        }
    }

    /**
     * 定时添加任务
     */
    public static function TownCronAdd(array $taskTemplate)
    {
        try {
            Log::info(['镇农科公司定时任务下发-任务模板', $taskTemplate]);
            // 单次任务不重复下发,在结算时刷新任务时间
            if ($taskTemplate['types'] == 3) {
                $task = Task::where('template_id', $taskTemplate['id'])->find();
                if ($task) {
                    // 累计任务进行天数,单次任务结算时,用于判断任务是否超时
                    TaskTemplate::where('id', $taskTemplate['id'])->inc('day_count')->update();
                    return true;
                }
            }
            Db::startTrans();

            $time = strtotime(date('Y-m-d'));
            $directorUid = 0; // 指派给
            if ($taskTemplate['extend']['task_role'] == 1) {
                $marketingManagerUser = (new User())->searchMaster($taskTemplate['company_id']);
                Log::info(['镇农科公司定时任务下发-负责人user信息', $marketingManagerUser]);
                $directorUid = $marketingManagerUser['id'];
            }
            if ($taskTemplate['extend']['task_role'] == 2) {
                $marketingManagerUser = (new User())->searchMarketingManager($taskTemplate['company_id']);
                Log::info(['镇农科公司定时任务下发-市场部长user信息', $marketingManagerUser]);
                $directorUid = $marketingManagerUser['id'];
            }

            if ($taskTemplate['extend']['task_role'] == 3) {
                $serviceManagerUser = (new User())->searchServiceManager($taskTemplate['company_id']);
                Log::info(['镇农科公司定时任务下发-服务部长user信息', $serviceManagerUser]);
                $directorUid = $serviceManagerUser['id'];
            }

            // 添加任务计划
            $TaskSchedulingPlan = self::addTaskSchedulePlan($taskTemplate, $time);
            Log::info(['镇农科公司定时任务下发-添加plan结果', $TaskSchedulingPlan]);

            // 添加任务
            $task_id = self::addTask($taskTemplate, $TaskSchedulingPlan, $time, $directorUid);
            Log::info(['镇农科公司定时任务下发-添加task结果', $task_id]);

            // 关联任务计划和任务
            TaskSchedulingPlan::where('id', $TaskSchedulingPlan['id'])->update(['task_id' => $task_id, 'is_execute' => 1]);

            // 任务累计进行天数 +1
            TaskTemplate::where('id', $taskTemplate['id'])->inc('day_count')->update();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error(['镇农科公司定时任务添加失败', $e->getFile(), $e->getLine(), $e->getMessage()]);
        }
    }

    private static function addTaskSchedulePlan($taskTemplate, $time)
    {
        $TaskSchedulingPlan_data = [
            'create_user_id' => 0,
            'company_id' => $taskTemplate['company_id'],
            'template_id' => $taskTemplate['id'],
            'scheduling_id' => $taskTemplate['task_scheduling'],
            'start_time' => $time,
            'end_time' => $time + 86399,
            'sn' => User::createUserSn(),
            'status' => 1
        ];
        $TaskSchedulingPlan = TaskSchedulingPlan::create($TaskSchedulingPlan_data);

        return $TaskSchedulingPlan;
    }

    private static function addTask($taskTemplate, $TaskSchedulingPlan, $time, $directorUid)
    {
        $arr = [
            'template_id' => $taskTemplate['id'],
            'scheduling_plan_id' => $TaskSchedulingPlan['id'],
            'company_id' => $taskTemplate['company_id'],
            'title' => $taskTemplate['title'],
            'money' => $taskTemplate['money'],
            'type' => $taskTemplate['type'],
            'content' => $taskTemplate['content'],
            'start_time' => $time,
            'end_time' => $time + 86399,
            'director_uid' => $directorUid, // 指派给
            'create_time' => time(),
            'update_time' => time(),
        ];
        $data = $arr;

        // 不同角色,计算任务金额有差异
        if($taskTemplate['extend']['task_role'] == 1) {
            $data['money'] = self::countTownMasterTaskMoney($taskTemplate);
        }
        if($taskTemplate['extend']['task_role'] == 2) {
            $data['money'] = self::countTownTaskMarketingMoney($taskTemplate);
        }
        if($taskTemplate['extend']['task_role'] == 3) {
            $data['money'] = self::countTownTaskMoney($taskTemplate);
        }


        $extend = [];
        // 任务类型code
        $taskType = (new DictData())->getTownTaskType($taskTemplate['type']);
        // 督促小组服务团队学习任务 扩展信息
        if ($taskType == 'town_task_type_4') {
            $extend = ['town_task_type_4' => ['study_photo'=>[], 'sign_in_table'=>'', 'study_content'=> '']];
        }
        $data['extend'] = json_encode($extend);
        $task_id = (new Task())->insertGetId($data);
        return $task_id;
    }

    private static function countTownTaskMoney($template)
    {
        $v_day_count = $template['day_count'];
        $v_day_count = $v_day_count + 1;
        $stageDayOneAccumulative = $template['stage_day_one']; // 第一阶段天数
        $stageDayTwoAccumulative = bcadd($template['stage_day_one'], $template['stage_day_two']); // 第二阶段天数 第一+第二
        $stageDayThreeAccumulative = bcadd($stageDayTwoAccumulative, $template['stage_day_three']); // 第三阶段天数 第二阶段累计值+第三

        // 单次和循环任务
        if ($template['types'] == 1 || $template['types'] == 3) {
            if ($v_day_count <= $stageDayOneAccumulative) {
                // 第一阶段金额
                return $template['money'];
            } else if ($stageDayOneAccumulative < $v_day_count && $v_day_count<= $stageDayTwoAccumulative) {
                // 第二阶段金额
                return  $template['money_two'];
            } else if ( $stageDayTwoAccumulative < $v_day_count && $v_day_count <= $stageDayThreeAccumulative) {
                // 第三阶段金额
                return  $template['new_money_three'];
            }
        } elseif ($template['types'] == 2) {
            // 长期任务

            // 督促完成需求收集和交易任务 第二个阶段即长期
            $townTaskTypeList = DictData::where(['type_value' => 'town_task_type', 'status' => 1])->column('value', 'id');
            if (isset($townTaskTypeList[$template['type']]) && $townTaskTypeList[$template['type']]=== 'town_task_type_5') {
                if ($v_day_count<= $stageDayOneAccumulative) {
                    // 第一阶段金额
                    return $template['money'];
                } elseif ( $v_day_count > $stageDayOneAccumulative) {
                    // 长期金额
                    return  $template['money_three'];
                }
            }

            if ($v_day_count<= $stageDayOneAccumulative) {
                // 第一阶段金额
                return $template['money'];
            } elseif ( $stageDayOneAccumulative < $v_day_count && $v_day_count <= $stageDayTwoAccumulative) {
                // 第二阶段金额
                return  $template['money_two'];
            } else if ( $stageDayTwoAccumulative < $v_day_count && $v_day_count <=$stageDayThreeAccumulative) {
                // 第三阶段金额
                return  $template['new_money_three'];
            } else {
                // 长期金额
                return  $template['money_three'];
            }
        }
    }

    private static function countTownTaskMarketingMoney($template) 
    {
        $v_day_count = $template['day_count'];
        $v_day_count = $v_day_count + 1;
        $stageDayOneAccumulative = $template['stage_day_one']; // 第一阶段天数
        $stageDayTwoAccumulative = bcadd($template['stage_day_one'], $template['stage_day_two']); // 第二阶段天数 第一+第二
        $stageDayThreeAccumulative = bcadd($stageDayTwoAccumulative, $template['stage_day_three']); // 第三阶段天数 第二阶段累计值+第三

        // 单次和循环任务
        if ($template['types'] == 1 || $template['types'] == 3) {
            if ($v_day_count <= $stageDayOneAccumulative) {
                // 第一阶段金额
                return $template['money'];
            } else if ($stageDayOneAccumulative < $v_day_count && $v_day_count<= $stageDayTwoAccumulative) {
                // 第二阶段金额
                return  $template['money_two'];
            } else if ( $stageDayTwoAccumulative < $v_day_count && $v_day_count <= $stageDayThreeAccumulative) {
                // 第三阶段金额
                return  $template['new_money_three'];
            }
        } elseif ($template['types'] == 2) {
            // 长期任务

            // 市场部长协助总负责人开展日常工作 第一个阶段即长期
            $townTaskTypeList = DictData::where(['type_value' => 'town_task_type_marketing_director', 'status' => 1])->column('value', 'id');
            if (isset($townTaskTypeList[$template['type']]) && $townTaskTypeList[$template['type']]=== 'town_task_type_marketing_director_1') {
                return  $template['money_three'];
            }

            if ($v_day_count<= $stageDayOneAccumulative) {
                // 第一阶段金额
                return $template['money'];
            } elseif ( $stageDayOneAccumulative < $v_day_count && $v_day_count <= $stageDayTwoAccumulative) {
                // 第二阶段金额
                return  $template['money_two'];
            } else if ( $stageDayTwoAccumulative < $v_day_count && $v_day_count <=$stageDayThreeAccumulative) {
                // 第三阶段金额
                return  $template['new_money_three'];
            } else {
                // 长期金额
                return  $template['money_three'];
            }
        }
    }

    private static function countTownMasterTaskMoney($template)
    {
        $v_day_count = $template['day_count'];
        $v_day_count = $v_day_count + 1;
        $stageDayOneAccumulative = $template['stage_day_one']; // 第一阶段天数
        $stageDayTwoAccumulative = bcadd($template['stage_day_one'], $template['stage_day_two']); // 第二阶段天数 第一+第二
        $stageDayThreeAccumulative = bcadd($stageDayTwoAccumulative, $template['stage_day_three']); // 第三阶段天数 第二阶段累计值+第三

        // 单次和循环任务
        if ($template['types'] == 1 || $template['types'] == 3) {
            if ($v_day_count <= $stageDayOneAccumulative) {
                // 第一阶段金额
                return $template['money'];
            } else if ($stageDayOneAccumulative < $v_day_count && $v_day_count<= $stageDayTwoAccumulative) {
                // 第二阶段金额
                return  $template['money_two'];
            } else if ( $stageDayTwoAccumulative < $v_day_count && $v_day_count <= $stageDayThreeAccumulative) {
                // 第三阶段金额
                return  $template['new_money_three'];
            }
        } elseif ($template['types'] == 2) {
            // 长期任务

            if ($v_day_count<= $stageDayOneAccumulative) {
                // 第一阶段金额
                return $template['money'];
            } elseif ( $stageDayOneAccumulative < $v_day_count && $v_day_count <= $stageDayTwoAccumulative) {
                // 第二阶段金额
                return  $template['money_two'];
            } else if ( $stageDayTwoAccumulative < $v_day_count && $v_day_count <=$stageDayThreeAccumulative) {
                // 第三阶段金额
                return  $template['new_money_three'];
            } else {
                // 长期金额
                return  $template['money_three'];
            }
        }
    }

    /**
     *  先判定任务是否已完成 再按每个任务对应的结算方式结算
     * $taskSchedulePlan  包含 task_tempalte、task_schedule、task_schedule_plan 三张表的信息
     */
    public static function townTaskSettlement($taskSchedulePlan)
    {
        try {
            Log::info(['镇农科公司定时任务结算执行-任务计划', $taskSchedulePlan]);
            $taskTemplateInfo = $taskSchedulePlan['template_info'];
            // 负责人任务结算
            if ($taskTemplateInfo['extend']['task_role'] == 1) {
                self::masterTaskSettlement($taskSchedulePlan);
            }
            // 市场部长任务结算
            if ($taskTemplateInfo['extend']['task_role'] == 2) {
                self::marketingManagerTaskSettlement($taskSchedulePlan);
            }
            // 服务部长任务结算
            if ($taskTemplateInfo['extend']['task_role'] == 3) {
                self::serviceManagerTaskSettlement($taskSchedulePlan);
            }

        } catch (Exception $e) {
            Log::error(['镇农科任务结算失败',$e->getFile(), $e->getLine(), $e->getMessage()]);
        }

    }

    /**
     * 镇农科负责人任务结算
     */
    private static function masterTaskSettlement($taskSchedulePlan)
    {
        try {
            $taskTemplateInfo = $taskSchedulePlan['template_info'];
            // 任务类型用的数据字典主键id,将id和value作映射,避免测试和正式环境数据字典数据不一致时出问题
            $townTaskTypeList = DictData::where(['type_value' => 'town_task_type_master', 'status' => 1])->column('value', 'id');
            switch ($townTaskTypeList[$taskTemplateInfo['type']]){
                // 应用软件推广
                case 'town_task_type_master_2':
                    self::masterTask2Settlement($taskSchedulePlan);
                    break;
                // 信息收集与促销
                case 'town_task_type_master_3':
                    self::masterTask3Settlement($taskSchedulePlan);
                    break;
                // 种养殖基地订单匹配
                case 'town_task_type_master_4':
                    self::masterTask4Settlement($taskSchedulePlan);
                    break;
                // 村联络员招募
                case 'town_task_type_master_5':
                    self::masterTask5Settlement($taskSchedulePlan);
                    break;
                // 促成村联络员入股甲方
                case 'town_task_type_master_6':
                    Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
                    $taskTemplateInfo = $taskSchedulePlan['template_info'];
                    $dayCount = $taskTemplateInfo['day_count'];
                    // 任务累计天数 <= 任务天数 刷新任务
                    if ($dayCount <= $taskTemplateInfo['stage_day_one']) {
                        self::flushTaskTime($taskSchedulePlan);
                    } else {
                        // 超期关闭任务
                        (new Task())->closeTask($taskSchedulePlan['task_id']);
                    }
//                    self::masterTask6Settlement($taskSchedulePlan);
                    break;
                // 政策补贴申请
                case 'town_task_type_master_7':
                    Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
                    $taskTemplateInfo = $taskSchedulePlan['template_info'];
                    $dayCount = $taskTemplateInfo['day_count'];
                    $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
                    $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
                    if($dayCount < $taskTemplateInfo['stage_day_one']) {
                        self::flushTaskTime($taskSchedulePlan);
                        return true;
                    }
//                    self::masterTask7Settlement($taskSchedulePlan);
                    break;
                // 日常管理及其他临时任务
                case 'town_task_type_master_8':
                    // 如果当天做了临时任务的情况下,需要通过审批才结算
                    $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
                    if(isset($task['extend']['is_commit']) && $task['extend']['is_commit'] == 1) {
                        return true;
                    }
                    self::masterTask8Settlement($taskSchedulePlan);
                    break;
                default:
                    return true;
            }
        } catch (Exception $e) {
            Log::error(['镇农科任务结算失败',$e->getFile(), $e->getLine(), $e->getMessage()]);
        }
    }

    /**
     *  应用软件推广 单次任务
     *  提前完成,截止提交时间,前面的钱一次性结算,往后至任务结束每天发放
     */
    private static function masterTask2Settlement($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        // 任务累计天数 < 第一阶段天数 如果任务状态为已完成,则一次性结算截止到今日的金额。
        if($dayCount < $taskTemplateInfo['stage_day_one']) {
            // 如果任务状态为已完成,表示今天用户有提交提前完成的凭证并且已通过审批,则一次性结算截止到今日的金额。
            if ($taskInfo['status'] == 3) {
                $taskInfo['money'] = bcmul($dayCount, $taskTemplateInfo['money'], 2);
                (new TownShareProfit())->dealTaskSettlementMaster2($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                // 任务状态为未完成,查看该任务模板是否有提前完成标识,有则每日结算当天的金额。
                $extend = $taskTemplateInfo['extend'];
                if (isset($extend['early_finish']) && $extend['early_finish'] == 1) {
                    $taskInfo['money'] = $taskTemplateInfo['money'];
                    (new TownShareProfit())->dealTaskSettlementMaster2($taskInfo, $townCompany, $taskSchedulePlan);
                }
            }
            // 刷新任务时间
            self::flushTaskTime($taskSchedulePlan);
        }

        // 任务最后一天结算
        if ($dayCount == $taskTemplateInfo['stage_day_one']) {
            if (isset($extend['early_finish']) && $extend['early_finish'] == 1) {
                $taskInfo['money'] = $taskTemplateInfo['money'];
                (new TownShareProfit())->dealTaskSettlementMaster2($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                // 状态为已完成,表示后台已通过审批
                if ($taskInfo['status'] == 3) {
                    // 结算分润
                    $approve = Approve::where(['business_id'=>$taskTemplateInfo['id']])->find();
                    $amount = $approve['amount'];
                    // 计算实际完成率
                    $rate = bcdiv($amount, 300000, 2);
                    if (bccomp($rate, 0.5, 2) == 1) {
                        (new Task())->closeTask($taskSchedulePlan['task_id']);
                        return false;
                    }
                    $totalMoney = bcmul($taskTemplateInfo['money'], $taskTemplateInfo['stage_day_one'], 2);
                    $taskInfo['money'] = self::countTaskMarketingDirector4TaskMoney($totalMoney, $rate);
                    (new TownShareProfit())->dealTaskSettlementMaster2($taskInfo, $townCompany, $taskSchedulePlan);
                }
            }
        }

    }


    /**
     * @param $taskSchedulePlan
     * 信息收集与促销
     * 任务累计天数 小于 第一阶段 关闭任务
     * 任务累计天数 = 第一阶段  判断信息收集任务是否完成,完成则结算
     * 任务累计天数 大于 第一阶段  小于第一+第二阶段 判断交易任务是否完成,完成则结算
     * 任务累计天数 = 第一+第二阶段  判断信息收集和交易任务是否完成,完成则结算
     * 任务累计天数 大于 第一+第二阶段  小于第一+第二+第三阶段 判断交易任务是否完成,完成则结算,否则关闭任务
     */
    private static function masterTask3Settlement($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $stageDayTwoCount = bcadd($taskTemplateInfo['stage_day_one'],$taskTemplateInfo['stage_day_two']);
        $target = $taskTemplateInfo['extend']['target'];
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();

        // 任务交易池,用于叠加交易额
        $townTransactionPool = $taskTemplateInfo['transaction_pool'];

        // 任务累计天数 小于 第一阶段 关闭任务
        if ($dayCount < $taskTemplateInfo['stage_day_one']) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
            return false;
        }

        // 任务累计天数 = 第一阶段  收集信息 >= 1家
        if ($dayCount == $taskTemplateInfo['stage_day_one']) {
            $purchaseSalesInfo = $taskTemplateInfo['extend']['purchase_sales_info'];
            $purchaseSalesCount = count($purchaseSalesInfo['planting']) + count($purchaseSalesInfo['supply']);
            if ($purchaseSalesCount >= 1) {
                $taskInfo['money'] = bcmul($taskTemplateInfo['money'],  $taskTemplateInfo['stage_day_one'], 2);
                (new TownShareProfit())->dealTaskSettlementMaster3($taskInfo, $townCompany, $taskSchedulePlan, $townTransactionPool);
            }
        }


        // 判断收集任务,整体是否已完成
        if ($dayCount == 60) {
            $purchaseSalesInfo = $taskTemplateInfo['extend']['purchase_sales_info'];
            $purchaseSalesCount = count($purchaseSalesInfo['planting']) + count($purchaseSalesInfo['supply']);

            $rate = bcdiv($purchaseSalesCount, $target, 2);
            if ($rate >= 1) {
                $rate = 1;
            }

            $totalMoney = bcmul(bcdiv($taskTemplateInfo['money_two'], 2, 2),55, 2);

            $taskInfo['money'] = bcmul($totalMoney, $rate, 2);
            (new TownShareProfit())->dealTaskSettlementMaster3($taskInfo, $townCompany, $taskSchedulePlan, $townTransactionPool);
        }


        // 任务累计天数 大于 第一阶段  小于第一+第二阶段 判断交易任务是否完成,完成则结算,否则关闭任务
        if ($dayCount > $taskTemplateInfo['stage_day_one'] && $dayCount < $stageDayTwoCount) {
            $purchaseSalesInfo = $taskTemplateInfo['extend']['purchase_sales_info'];
            $purchaseSalesCount = bcadd(count($purchaseSalesInfo['planting']), count($purchaseSalesInfo['supply']));
            // 判断交易任务是否完成
           self::judgeMasterTask3Trade($taskInfo, $taskTemplateInfo, $townCompany, $taskSchedulePlan, $purchaseSalesInfo, $townTransactionPool, $purchaseSalesCount);
        }

        // 任务累计天数 = 第一+第二阶段  判断信息收集和交易任务是否完成,完成则结算,否则关闭任务
//        if ($dayCount == $stageDayTwoCount) {
//            $purchaseSalesInfo = $taskTemplateInfo['extend']['purchase_sales_info'];
//            $purchaseSalesCount = count($purchaseSalesInfo['planting']) + count($purchaseSalesInfo['supply']);
//            if ($purchaseSalesCount >= $target) {
//                $taskInfo['money'] = bcmul(bcdiv($taskTemplateInfo['money_two'], 2, 2),  $taskTemplateInfo['stage_day_two'], 2);
//                (new TownShareProfit())->dealTaskSettlementMaster3($taskInfo, $townCompany, $taskSchedulePlan, $townTransactionPool);
//            }
//        }

        // 任务累计天数 大于 第一+第二阶段 每日结算 判断交易任务是否完成,完成则结算,否则关闭任务
        if ($dayCount >= $stageDayTwoCount) {
            // 判断交易任务是否完成
            self::judgeMasterTask3Trade($taskInfo, $taskTemplateInfo, $townCompany, $taskSchedulePlan, $purchaseSalesInfo, $townTransactionPool, $target);
        }
    }

    private static function judgeMasterTask3Trade($taskInfo, $taskTemplateInfo, $townCompany, $taskSchedulePlan, $purchaseSalesInfo, $townTransactionPool, $target)
    {
        // 查询收集到的用户在商城的交易金额(前置条件:信息收集中的手机号注册商城并交易)
        $phoneList = [];
        foreach ($purchaseSalesInfo['planting'] as $item) {
            $phoneList[] = $item['phone'];
        }
        foreach ($purchaseSalesInfo['supply'] as $item) {
            $phoneList[] = $item['shopkeeperPhone'];
        }
        $param = [
            'start_time' => strtotime(date('Y-m-d', time())),
            'end_time' => strtotime(date('Y-m-d', time())) + 86399,
            'phone' => implode(',', $phoneList)
        ];

        $result = ShopRequestLogic::getUserTradeAmount($param);

        if(isset($result['status']) && $result['status']== 400) {
            $tradeAmount = 0;
        }
        if(isset($result['status']) && $result['status']== 200) {
            $tradeAmount = $result['data']['trade_amount'];
        }

        $totalAmount = bcadd($tradeAmount, $townTransactionPool, 2); // 总的交易金额 = 当日交易额 +  累计交易池

        // 目标金额 = 274 * 收集用户数
        $targetTradeAmount = bcmul($target, 274, 2);

        // 完成条件: 交易金额 >= 目标金额
        if (bccomp($totalAmount, $targetTradeAmount, 2) ==0 || bccomp($totalAmount, $targetTradeAmount, 2) ==1) {
            $taskInfo['money'] = bcdiv($taskTemplateInfo['money_two'], 2, 2);
            $leftTransactionPool = bcsub($totalAmount, $targetTradeAmount, 2);
            (new TownShareProfit())->dealTaskSettlementMaster3($taskInfo, $townCompany, $taskSchedulePlan, $leftTransactionPool);
        } else {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }
    }

    /**
     * @param $taskSchedulePlan
     *  督促种养殖商户和供应链商户交易
     */
    private static function masterTask4Settlement($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();

        // 任务交易池,用于叠加交易额
        $townTransactionPool = $taskTemplateInfo['transaction_pool'];
        // 行政村数量
        $villageCount = Db::name('geo_village')->where(['street_code' => $townCompany['street']])->count();
        // 每日目标金额
        $targetAmount = bcmul($villageCount, 329 , 2);
        // 查询镇农科辖区 当日的 种养殖商户和供应链商户交易额
        $param = [
            'start_time' => strtotime(date('Y-m-d', time())),
            'end_time' => strtotime(date('Y-m-d', time())) + 86399,
            'responsible_area' => $townCompany['responsible_area'],
            'type' => 'street',
        ];
        $result = ShopRequestLogic::getTownTradeAmount($param);

        $tradeAmount = $result['data']['trade_amount'];

        // 总交易额 交易池金额+商城交易额
        $totalAmount = bcadd($townTransactionPool, $tradeAmount, 2);

        // 完成条件: 总交易额 >= 每日目标金额
        if (bccomp($totalAmount, $targetAmount, 2) == 0 || bccomp($totalAmount, $targetAmount, 2) == 1) {
            $leftTransactionPool = bcsub($totalAmount, $targetAmount, 2);
            // 任务结算
            (new TownShareProfit())->dealTaskSettlementMaster4($taskInfo, $townCompany, $taskSchedulePlan, $leftTransactionPool);
        } else {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }
    }

    private static function masterTask5Settlement($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        // 行政村数量
        $villageCount = Db::name('geo_village')->where(['street_code' => $townCompany['street']])->count();
        if ($villageCount == 0) {
            throw new Exception('没有找到对应的行政村'.__FILE__.__LINE__);
        }
        // 村公司
        $villageCompanyList = Db::query("select id from la_company where company_type=:company_type and FIND_IN_SET(street,:responsible_area)", ['company_type' => 17,'responsible_area'=>$townCompany['responsible_area']], true);
        $ids = array_column($villageCompanyList, 'id');
        // 村联络员数量
        $liaisonManCount = User::where(['group_id'=>17])->whereIn('company_id', $ids)->count();

        // 第一周期天数
        $stageOneDayCount = bcmul($villageCount, 4);

        // 任务累计天数 小于 第一周期天数 关闭任务
        if ($dayCount < $stageOneDayCount) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }
        // 任务累计天数第一个周期结算
        if ($dayCount == $stageOneDayCount) {
            $rate = bcdiv($liaisonManCount, $villageCount, 2);
            if (bccomp($rate, 0.5, 2) == 1 || bccomp($rate, 0.5, 2) == 0) {
                // 按个数结算
                $taskInfo['money'] = bcmul($liaisonManCount, 120, 2);
                (new TownShareProfit())->dealTaskSettlementMaster5($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }

        // 任务累计天数 大于 第一周期天数, 每天结算
        if ($dayCount > $stageOneDayCount) {
            $rate = bcdiv($liaisonManCount, $villageCount, 2);
            if (bccomp($rate, 0.5, 2) == 1) {
                // 按实际完成率结算
                $taskInfo['money'] = bcmul($rate, $taskTemplateInfo['money_three'], 2);
                (new TownShareProfit())->dealTaskSettlementMaster5($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }
    }

    /**
     * @param $taskSchedulePlan
     * 促成村联络员入股甲方 单次
     * 任务累计天数 小于 第一阶段 刷新任务时间
     * 任务累计天数 = 第一阶段 结算
     */
    public static function masterTask6Settlement($taskSchedulePlan, $approve)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        // 行政村数量
        $villageCount = Db::name('geo_village')->where(['street_code' => $townCompany['street']])->count();
        // 小组服务公司总数
        $groupServiceCompanyList = Company::where(['company_type'=> 18])->whereIn('street', $townCompany['responsible_area'])->select()->toArray();
        $groupServiceCompanyCount = count($groupServiceCompanyList);

        // 任务累计天数 = 第一阶段 任务期限内才结算
        if ($dayCount <= $taskTemplateInfo['stage_day_one']) {
            // 目标任务金额 行政村数量*6000 + 小组服务团队数量*3000
            $targetShareholderedMoney =  bcadd(bcmul($villageCount, 6000, 2), bcmul($groupServiceCompanyCount, 3000, 2), 2);
            if ($targetShareholderedMoney == 0) {
                throw new Exception('目标任务金额为0异常'.__FILE__.__LINE__);
            }
            // 已入股股金总额
            $shareholderedMoney = $approve->amount;

           $rate = bcdiv($shareholderedMoney, $targetShareholderedMoney, 2);

            if (bccomp($rate, 0.5, 2) == -1) {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
                return true;
            }
            $totalMoney = bcmul($taskTemplateInfo['money'], $taskTemplateInfo['stage_day_one'], 2);
            $taskInfo['money'] = self::countSettelmentMoney($rate, $totalMoney);
            (new TownShareProfit())->dealTaskSettlementMaster6($taskInfo, $townCompany, $taskSchedulePlan);
        }
    }

    /**
     * @param $taskSchedulePlan
     * 政策补贴申请 单次
     */
    public static function masterTask7Settlement($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();

        if ($dayCount <= $taskTemplateInfo['stage_day_one']) {
            // 审批通过后,任务状态会变更为已完成状态,审批是会根据凭证填入实际申请的政策补贴金额,根据该金额计算任务结算金额
            if ($taskInfo['status'] == 3) {
                $approve = Approve::where(['task_id' => $taskSchedulePlan['task_id']])->find();
                if ($approve->check_status == 2) {
                    $amount = $approve['amount'];  // 审批通过后的金额
                    $rate = bcdiv($amount, $taskTemplateInfo['extend']['target'], 2);
                    if (bccomp($rate, 0.5, 2) == -1) {
                        (new Task())->closeTask($taskSchedulePlan['task_id']);
                    }
                    $totalMoney = bcmul($taskTemplateInfo['money'], $taskTemplateInfo['stage_day_one'], 2);
                    $taskInfo['money'] = self::countTaskMarketingDirector4TaskMoney($totalMoney, $rate);
                    (new TownShareProfit())->dealTaskSettlementMaster7($taskInfo, $townCompany, $taskSchedulePlan);
                }
            } else {
                // 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }
    }

    public static function masterTask8Settlement($taskSchedulePlan)
    {
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $villageCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
        $task['money'] = $taskTemplateInfo['money_three'];
        (new TownShareProfit())->dealTaskSettlementMaster8($task, $villageCompany, $taskSchedulePlan);
    }

    /**
     * @param $taskSchedulePlan
     * 市场部长任务结算
     */
    private static function marketingManagerTaskSettlement($taskSchedulePlan)
    {
        try {
            $taskTemplateInfo = $taskSchedulePlan['template_info'];
            // 任务类型用的数据字典主键id,将id和value作映射,避免测试和正式环境数据字典数据不一致时出问题
            $townTaskTypeList = DictData::where(['type_value' => 'town_task_type_marketing_director', 'status' => 1])->column('value', 'id');
            switch ($townTaskTypeList[$taskTemplateInfo['type']]){
                // 协助总负责人开展工作
                case 'town_task_type_marketing_director_1':
                    self::dealTaskMarketingDirector1($taskSchedulePlan);
                    break;
                // 招驻供应链商户
                case 'town_task_type_marketing_director_2':
                    self::dealTaskMarketingDirector2($taskSchedulePlan);
                    break;
                // 协助供应链商户上架商品和库存更新
                case 'town_task_type_marketing_director_3':
                    self::dealTaskMarketingDirector3($taskSchedulePlan);
                    break;
                // 督促供应链商户完成采购
                case 'town_task_type_marketing_director_4':
                    self::dealTaskMarketingDirector4($taskSchedulePlan);
                    break;
                // 督促供应链商户完成销售
                case 'town_task_type_marketing_director_5':
                    self::dealTaskMarketingDirector5($taskSchedulePlan);
                    break;
                // 招驻一般商户
                case 'town_task_type_marketing_director_6':
                    self::dealTaskMarketingDirector6($taskSchedulePlan);
                    break;
                // 协助一般商户上架商品和库存更新
                case 'town_task_type_marketing_director_7':
                    self::dealTaskMarketingDirector7($taskSchedulePlan);
                    break;
                // 督促一般商户完成采购
                case 'town_task_type_marketing_director_8':
                    self::dealTaskMarketingDirector8($taskSchedulePlan);
                    break;
                // 督促一般商户完成销售
                case 'town_task_type_marketing_director_9':
                    self::dealTaskMarketingDirector9($taskSchedulePlan);
                    break;
                // 数字农贸宣传、加工业务建设和招商任务
                case 'town_task_type_marketing_director_10':
                    // 该任务的判定都需要上传资料,后台审批任务是否完成.   因此每天自动结算时,任务状态不为完成的,都做关闭任务处理
                    $task = Task::where(['id'=>$taskSchedulePlan['task_id']])->find();
                    if ($task['status'] != 3) {
                        (new Task())->closeTask($taskSchedulePlan['task_id']);
                    }
//                self::dealTaskMarketingDirector10($taskSchedulePlan);
                    break;
                default:
                    return true;
            }
        } catch (Exception $e) {
            Log::error(['镇农科任务结算失败',$e->getFile(), $e->getLine(), $e->getMessage()]);
        }

    }

    /**
     * @param $taskSchedulePlan
     * 市场部长协助总负责人开展工作 任务完成判定和结算
     */
    private static function dealTaskMarketingDirector1($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $isDone = 1; // 任务是否完成标记
        $isTaskSchedule = 0; // 下属小组服务公司是否有每日任务安排标记

        // 负责人任务类型id列表
        $typeIds = [];
        $townMasterTaskTypeList = DictData::where(['type_value' => 'town_task_type_master', 'status' => 1])->column('value', 'id');
        foreach ($townMasterTaskTypeList as $k => $item) {
            if ($item == 'town_task_type_master_3') {
                $typeIds[] = $k;
            }
            if ($item == 'town_task_type_master_4') {
                $typeIds[] =$k;
            }
//            if ($item == 'town_task_type_master_5') {
//                $typeIds[] = $k;
//            }
            if ($item == 'town_task_type_master_8') {
                $typeIds[] = $k;
            }
        }

        // 查询 镇农科公司负责人是否有对应的每日任务安排
        $templateList = TaskTemplate::where(['company_id'=>$townCompany['id']])->whereIn('type', $typeIds)->select()->toArray();
        // 未做任务安排的小组服务公司不在判定范围内,跳出本次循环
        if(count($templateList) === 3) {
            $isTaskSchedule = 1;
            // 查询负责人的循环任务有没有全部做完 任意有一个任务没有做完,则判定为 协助总负责人开展工作任务 失败
            foreach ($templateList as $template) {
                $task = Task::where(['template_id' => $template['id'], 'status' => 3])->find();
                if (empty($task)) {
                    $isDone = 0;
                    break;
                }
            }
        }
        // 镇农科公司负责人有任务安排,也完成了任务
        if ($isDone === 1 && $isTaskSchedule === 1) {
            // 做任务结算,分润
            (new TownShareProfit())->dealTaskSettlementMarketingDirector1($taskInfo, $townCompany, $taskSchedulePlan);
        } else {
            // 关闭任务
            (new Task())->closeTask($taskSchedulePlan['task_id']);
            Log::info('协助总负责人开展工作任务,结算失败:' . $taskTemplateInfo['title'] . '未完成。任务:' . json_encode($taskInfo));
        }
    }

    /**
     * 招驻供应链商户 单次任务 任务完成判定和结算
     * 判定条件 : 任务下发60天内,供应链商户在商城开户并缴纳押金不少于5000,>=6家
     * 当前任务进行天数 < 第一阶段天数  只刷新任务时间
     * 当前任务进行天数 = 第一阶段天数  判定任务完成情况,结算
     */
    private static function dealTaskMarketingDirector2($taskSchedulePlan)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $templateInfo['day_count'];
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        // 当前任务进行天数 < 第一阶段天数  只刷新任务时间
        if ($dayCount < $templateInfo['stage_day_one']) {
            self::flushTaskTime($taskSchedulePlan);
            return true;
        }

        // 当前任务进行天数 = 第一阶段天数  判定任务完成情况,结算
        if ($dayCount ==  $templateInfo['stage_day_one']) {
            // 请求商城接口,获取完成几家
            $param['start_time'] = strtotime(date('Y-m-d', strtotime($templateInfo['create_time']))) + 86400;
            $param['end_time'] = time();
            $param['responsible_area'] = $townCompany['responsible_area'];
            $param['type'] = 'street';
            $param['type_id'] = 17;

            $result = ShopRequestLogic::getSupplyChainMerchantCount($param);

            if ($result['status'] != 200) {
                Log::error('查询供应链商户统计接口失败'.ShopRequestLogic::getError());
                $count = 0;
            } else {
                $count = $result['data']['count'];
            }


            // 完成数小于3,关闭任务,不做结算
            if ($count <  3){
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
            // 完成数大于等于3,结算
            $target = $templateInfo['extend']['target'];
            $perMoney = bcdiv(bcmul($templateInfo['stage_day_one'], $templateInfo['money']), $target); // 完成单个金额

            if ($count >= 6) {
                $count = 6;
            }
            $taskInfo['money'] = bcmul($count, $perMoney); // 任务金额
            // 结算,分润
            (new TownShareProfit())->dealTaskSettlementMarketingDirector2($taskInfo, $townCompany, $taskSchedulePlan);
        }
    }

    /**
     * 协助供应链商户商品上架和库存更新 长期 判定与结算
     *  请求商城接口,查询每个商户入驻5天内是否完成商品上架
     *  请求商城接口,查询每个商户商品上架构后15天内是否完成库存更新
     *
     */
    public static function dealTaskMarketingDirector3($taskSchedulePlan)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        // 商城商户入驻申请id 与商户已关联
        $shopMerchantSettleinLogList= ShopMerchantSettleinLog::where(['town_company_id'=>$townCompany['id']])->select()->toArray();

        // 遍历农科公司区域下的商户,对每个商户进行判定
        foreach ($shopMerchantSettleinLogList as $item) {

            // 入驻5天内是否完成商品上架
            $startTime = strtotime($item['create_time']); // 入驻时间 读取时间戳会被自动转换为 Y-m-d H:i:s格式的字符串
            $endTime = bcadd($startTime, bcmul(86400, $templateInfo['stage_day_one']));
            // 只在入驻5天后的最后一天结算,不然会重复结算
            if (date('Y-m-d', $endTime) == date('Y-m-d', time())) {
                $merIntentionId = $item['mer_intention_id'];
                $param = [
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'mer_intention_id' => $merIntentionId,
                    'type_id' => 17,
                ];

                $result = ShopRequestLogic::getProductListing($param);

                if ($result['status'] != 200) {
                    Log::info(['4.市场部长-供应链商户完成商品上架和库存更新任务-查询商城接口失败', json_encode($result)]);
                    $count = 0;
                } else {
                    $count = $result['data']['count'];
                }

                // 达到目标数  完成则结算
                if ($count >= $templateInfo['extend']['target']){
                    // 结算金额 任务金额/目标数 * 天数
                    $taskInfo['money'] = bcmul($templateInfo['stage_day_one'], bcdiv($templateInfo['money'], $templateInfo['extend']['target']));
                    Log::info(['5.市场部长-供应链商户完成商品上架任务-$taskSchedulePlan', json_encode($taskSchedulePlan)]);
                    (new TownShareProfit())->dealTaskSettlementMarketingDirector3($taskInfo, $townCompany, $taskSchedulePlan);
                }
            }


            // 商品上架构后15天内是否完成库存更新
            $startTime = strtotime($item['create_time']);
            $endTime = bcadd($startTime, bcmul( 86400, bcadd($templateInfo['stage_day_one'], $templateInfo['stage_day_two']))) ;
            // 只在上架完成15天后的最后一天结算
            if (date('Y-m-d', $endTime) == date('Y-m-d', time())) {
                $merIntentionId = $item['mer_intention_id'];
                $param = [
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'mer_intention_id' => $merIntentionId,
                    'type_id' => 17
                ];
                $result1 = ShopRequestLogic::getStockUpdate($param);

                if ($result1['status'] != 200) {
                    Log::info(['4.市场部长-供应链商户完成库存更新任务-查询商城接口结果', json_encode($result)]);
                    $count = 0;
                } else {
                    $count = $result1['data']['count'];
                }

                if ($count >= 1){
                    // 结算金额 任务金额/目标数 * 天数
                    $taskInfo['money'] = bcmul($templateInfo['stage_day_two'], bcdiv($templateInfo['money_two'], $templateInfo['extend']['target']));
                    Log::info(['5.市场部长-供应链商户完成商品上架任务-$taskSchedulePlan', json_encode($taskSchedulePlan)]);
                    (new TownShareProfit())->dealTaskSettlementMarketingDirector3($taskInfo, $townCompany, $taskSchedulePlan);
                }
            }
        }

        // 未完成的情况下,每天自动关闭任务
        $task = Task::where(['id'=>$taskSchedulePlan['task_id']])->find();
        if ($task['status'] != 3) {
            (new Task())->closeTask($task['id']);
        }
    }

    /**
     * 协助供应链商户采购任务 长期 判定与结算
     * 根据每个商户入驻时间,推出各个周期范围的起始时间,商户申请id,指定商品id。请求商城接口
     */
    public static function dealTaskMarketingDirector4($taskSchedulePlan)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        // 商城商户入驻申请id 与商户已关联
        $shopMerchantSettleinLogList= ShopMerchantSettleinLog::where(['town_company_id'=>$townCompany['id']])->select()->toArray();

        // 遍历农科公司区域下的商户,对每个商户进行判定
        foreach ($shopMerchantSettleinLogList as $item) {

            // 第一阶段 从入驻时间累计到第一阶段周期天数 为结算日期  只在截止日当天才结算
            $startTime = strtotime(date('Y-m-d', strtotime($item['create_time']))); // 入驻当日 00:00:00
            $endTime = strtotime("+{$templateInfo['stage_day_one']} day", $startTime); //  $templateInfo['stage_day_one']天后的 00:00:00

            if (date('Y-m-d', $endTime) == date('Y-m-d', time())){
                // 任务判定
                self::judgeTaskMarketingDirector4($templateInfo, $item, $taskSchedulePlan, $startTime, $endTime, 1, $townCompany, $taskInfo);
            }

            // 第二阶段 从入驻时间累计到第二阶段周期天数 为结算日期  只在截止日当天才结算
            $startTime1 = $endTime; // 第一阶段 截止日 00:00:00
            $stageDayTwoCount = bcadd($templateInfo['stage_day_one'], $templateInfo['stage_day_two']);
            $endTime1 = strtotime("+{$stageDayTwoCount} day", $startTime);
            if (date('Y-m-d', $endTime) == date('Y-m-d', time())){
                self::judgeTaskMarketingDirector4($templateInfo, $item, $taskSchedulePlan, $startTime1, $endTime1, 2, $townCompany, $taskInfo);
            }

            // 第三阶段 从入驻时间累计到第三阶段周期天数 为结算日期  只在截止日当天才结算
            $startTime2 = $endTime1; // 第二阶段 截止日 00:00:00
            $stageDayThreeCount = bcadd(bcadd($templateInfo['stage_day_one'], $templateInfo['stage_day_two']), $templateInfo['stage_day_three']);
            $endTime2 = strtotime("+{$stageDayThreeCount} day", $startTime);
            if (date('Y-m-d', $endTime) == date('Y-m-d', time())){
                self::judgeTaskMarketingDirector4($templateInfo, $item, $taskSchedulePlan, $startTime2, $endTime2, 3, $townCompany, $taskInfo);
            }

            // 长期 间隔天数 = 当前日期的00:00:00时间戳 - 商户入驻时间累计三个阶段天数的日期00:00:00时间戳
            $startTime3 = $endTime2; // 第三阶段 截止日 00:00:00
            $intervalDayCount = intdiv(bcsub( strtotime(date('Y-m-d', time())), $endTime2), 86400);
            $endTime3 = strtotime(date('Y-m-d', time()));
            //  间隔天数能整除30  表示可以结算
            if ($intervalDayCount % 30 === 0) {
                $step = bcadd(3, intdiv($intervalDayCount, 30));
                self::judgeTaskMarketingDirector4($templateInfo, $item, $taskSchedulePlan, $startTime3, $endTime3, $step, $townCompany, $taskInfo);
            }
        }
        // 未完成的情况下,每天自动关闭任务
        $task = Task::where(['id'=>$taskSchedulePlan['task_id']])->find();
        if ($task['status'] != 3) {
            (new Task())->closeTask($task['id']);
        }
    }

    /**
     * @param $templateInfo
     * @param $item
     * @param $taskSchedulePlan
     * @param $startTime
     * @param $endTime
     *  判定任务是否完成 完成则结算分润
     */
    private static function judgeTaskMarketingDirector4($templateInfo, $item, $taskSchedulePlan, $startTime, $endTime, $step, $townCompany, $taskInfo)
    {
        // 只在截止日当天才结算
        $merIntentionId = $item['mer_intention_id'];
        $directorGoodsId = $templateInfo['extend']['goods_id'];
        $param = [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'mer_intention_id' => $merIntentionId,
            'goods_id' => $directorGoodsId,
            'type'=>200
        ];
        $result1 = ShopRequestLogic::getPurchaseAmount($param);
        if ($result1['status'] != 200) {
            Log::info(['4.市场部长-协助供应链商户采购任务-查询商城接口失败', json_encode($result1)]);
            $result1['data']['procure_amount'] = 0;
        }
        if ($result1['data']['procure_amount'] > 0) {
            $procureAmount = $result1['data']['procure_amount'];
            // 采购金额 实际完成率
            $rate = self::countRate($procureAmount, $step);

            if (bccomp($rate, 0.5, 2)  == -1) {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            } else {
                $taskMoney = 0;
                // 全额完成可获得的总金额
                $totalMoney = bcmul(30, bcdiv($templateInfo['money_three'], $templateInfo['extend']['target'], 2), 2);
                // 已完成 计算结算金额
                if ($step == 1) {
                    $totalMoney = bcmul($templateInfo['stage_day_one'], bcdiv($templateInfo['money'], $templateInfo['extend']['target'], 2), 2);
                }
                if ($step == 2) {
                    $totalMoney = bcmul($templateInfo['stage_day_two'], bcdiv($templateInfo['money_two'], $templateInfo['extend']['target'], 2), 2);
                }
                if ($step == 3) {
                    $totalMoney = bcmul(20, bcdiv($templateInfo['money_two'], $templateInfo['extend']['target'], 2), 2) + bcmul(10, bcdiv($templateInfo['money_three'], $templateInfo['extend']['target'], 2), 2);
                }

                if ($procureAmount >= 300000) {
                    $taskMoney = $totalMoney;
                } else {
                    // 计算结算金额 周期天数*(money/目标数)*实际完成率*对应发放比例
                    $taskMoney= self::countTaskMarketingDirector4TaskMoney($totalMoney, $rate);
                }
                $taskInfo['money'] = $taskMoney;
                Log::info(['5.市场部长-供应链商户完成采购任务-$taskSchedulePlan', json_encode($taskSchedulePlan)]);
                (new TownShareProfit())->dealTaskSettlementMarketingDirector4($taskInfo, $townCompany, $taskSchedulePlan);
            }
        }
    }

    /**
     * @param $totalMoney 每完成一次目标金额
     * @param $rate 实际完成率
     * 计算结算金额 全额任务金额*对应发放比例*实际完成率
     */
    private static function countTaskMarketingDirector4TaskMoney($totalMoney, $rate)
    {
        $taskMoney = 0;

        // =50% - %59    x40%
        if (bccomp($rate, 0.5, 2)  == 0 || (bccomp($rate, 0.5, 2)  == 1 && bccomp($rate, 0.59, 2)  == -1) || bccomp($rate, 0.59, 2)  == 0) {
            $taskMoney = bcmul($rate, bcmul($totalMoney, 0.4, 2), 2);
        }
        // =60% - %69    x50%
        if (bccomp($rate, 0.6, 2)  == 0 || (bccomp($rate, 0.6, 2)  == 1 && bccomp($rate, 0.69, 2)  == -1) || bccomp($rate, 0.69, 2)  == 0) {
            $taskMoney = bcmul($rate, bcmul($totalMoney, 0.5, 2), 2);
        }

        // =70% - %79    x60%
        if (bccomp($rate, 0.7, 2)  == 0 || (bccomp($rate, 0.7, 2)  == 1 && bccomp($rate, 0.79, 2)  == -1) || bccomp($rate, 0.79, 2)  == 0) {
            $taskMoney = bcmul($rate, bcmul($totalMoney, 0.6, 2), 2);
        }

        // =80% - %89    x70%
        if (bccomp($rate, 0.8, 2)  == 0 || (bccomp($rate, 0.8, 2)  == 1 && bccomp($rate, 0.89, 2)  == -1) || bccomp($rate, 0.89, 2)  == 0) {
            $taskMoney = bcmul($rate, bcmul($totalMoney, 0.7, 2), 2);
        }
        // =90%-99%       x80%
        if (bccomp($rate, 0.9, 2)  == 0 || (bccomp($rate, 0.9, 2)  == 1  && bccomp($rate, 0.99, 2)  == -1) || bccomp($rate, 0.99, 2)  == 0) {
            $taskMoney = bcmul($rate, bcmul($totalMoney, 0.8, 2), 2);
        }
        // >=100%            x100%
        if($rate >= 1) {
            $taskMoney = $totalMoney;
        }
        return $taskMoney;
    }

    /**
     *  协助供应链商户销售任务 长期 判定与结算
     */
    private static  function dealTaskMarketingDirector5($taskSchedulePlan)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        // 商城商户入驻申请id 与商户已关联
        $shopMerchantSettleinLogList= ShopMerchantSettleinLog::where(['town_company_id'=>$townCompany['id']])->select()->toArray();

        // 遍历农科公司区域下的商户,对每个商户进行判定
        foreach ($shopMerchantSettleinLogList as $item) {

            // 第一阶段 从入驻时间累计到第一阶段周期天数 为结算日期  只在截止日当天才结算
            $startTime = strtotime(date('Y-m-d', strtotime($item['create_time']))); // 入驻当日 00:00:00
            $endTime = strtotime("+{$templateInfo['stage_day_one']} day", $startTime); //  $templateInfo['stage_day_one']天后的 00:00:00
            if (date('Y-m-d', $endTime) == date('Y-m-d', time())){
                // 任务判定
                self::judgeTaskMarketingDirector5($templateInfo, $item, $taskSchedulePlan, $startTime, $endTime, 1, $townCompany, $taskInfo);
            }

            // 第二阶段 从入驻时间累计到第二阶段周期天数 为结算日期  只在截止日当天才结算
            $startTime1 = $endTime; // 第一阶段 截止日 00:00:00
            $stageDayTwoCount = bcadd($templateInfo['stage_day_one'], $templateInfo['stage_day_two']);
            $endTime1 = strtotime("+{$stageDayTwoCount} day", $startTime);
            if (date('Y-m-d', $endTime) == date('Y-m-d', time())){
                self::judgeTaskMarketingDirector5($templateInfo, $item, $taskSchedulePlan, $startTime1, $endTime1, 2, $townCompany, $taskInfo);
            }

            // 第三阶段 从入驻时间累计到第三阶段周期天数 为结算日期  只在截止日当天才结算
            $startTime2 = $endTime1; // 第二阶段 截止日 00:00:00
            $stageDayThreeCount = bcadd(bcadd($templateInfo['stage_day_one'], $templateInfo['stage_day_two']), $templateInfo['stage_day_three']);
            $endTime2 = strtotime("+{$stageDayThreeCount} day", $startTime);
            if (date('Y-m-d', $endTime) == date('Y-m-d', time())){
                self::judgeTaskMarketingDirector5($templateInfo, $item, $taskSchedulePlan, $startTime2, $endTime2, 3, $townCompany, $taskInfo);
            }

            // 长期 间隔天数 = 当前日期的00:00:00时间戳 - 商户入驻时间累计三个阶段天数的日期00:00:00时间戳
            $startTime3 = $endTime2; // 第三阶段 截止日 00:00:00
            $intervalDayCount = intdiv(bcsub( strtotime(date('Y-m-d', time())), $endTime2), 86400);
            $endTime3 = strtotime(date('Y-m-d', time()));
            //  间隔天数能整除30  表示可以结算
            if ($intervalDayCount % 30 === 0) {
                $step = bcadd(3, intdiv($intervalDayCount, 30));
                self::judgeTaskMarketingDirector5($templateInfo, $item, $taskSchedulePlan, $startTime3, $endTime3, $step, $townCompany, $taskInfo);
            }
        }
        // 未完成的情况下,每天自动关闭任务
        $task = Task::where(['id'=>$taskSchedulePlan['task_id']])->find();
        if ($task['status'] != 3) {
            (new Task())->closeTask($task['id']);
        }
    }

    /**
     * @param $templateInfo
     * @param $item
     * @param $taskSchedulePlan
     * @param $startTime
     * @param $endTime
     *  判定任务是否完成 完成则结算分润
     */
    private static function judgeTaskMarketingDirector5($templateInfo, $item, $taskSchedulePlan, $startTime, $endTime, $step, $townCompany, $taskInfo)
    {
        // 只在截止日当天才结算
        $merIntentionId = $item['mer_intention_id'];
        $directorGoodsId = $templateInfo['extend']['goods_id'];
        $param = [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'mer_intention_id' => $merIntentionId,
            'goods_id' => $directorGoodsId,
            'type'=>300
        ];
        $result1 = ShopRequestLogic::getTradeAmount($param);
        if ($result1['status'] == 200) {
            $tradeAmount = $result1['data']['procure_amount'];
        } else {
            Log::info(['4.市场部长-协助供应链商户销售任务-查询商城接口失败', json_encode($result1)]);
            $tradeAmount = 0;
        }


        if ($tradeAmount > 0) {
            // 采购金额 实际完成率
            $rate = self::countRate($tradeAmount, $step);

            if (bccomp($rate, 0.5, 2)  == -1) {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            } else {
                $taskMoney = 0;
                // 全额完成可获得的总金额
                $totalMoney = bcmul(30, bcdiv($templateInfo['money_three'], $templateInfo['extend']['target'], 2), 2);

                // 已完成 计算结算金额
                if ($step == 1) {
                    $totalMoney = bcmul($templateInfo['stage_day_one'], bcdiv($templateInfo['money'], $templateInfo['extend']['target'], 2), 2);
                }
                if ($step == 2) {
                    $totalMoney = bcmul($templateInfo['stage_day_two'], bcdiv($templateInfo['money_two'], $templateInfo['extend']['target'], 2), 2);
                }
                if ($step == 3) {
                    $totalMoney = bcmul(20, bcdiv($templateInfo['money_two'], $templateInfo['extend']['target'], 2), 2) + bcmul(10, bcdiv($templateInfo['money_three'], $templateInfo['extend']['target'], 2), 2);
                }

                if ($tradeAmount >= 300000) {
                    $taskMoney = $totalMoney;
                } else {
                    // 计算结算金额 周期天数*(money/目标数)*实际完成率*对应发放比例
                    $taskMoney= self::countTaskMarketingDirector4TaskMoney($totalMoney, $rate);
                }

                $taskInfo['money'] = $taskMoney;
                Log::info(['5.市场部长-供应链商户完成商品销售任务-$taskSchedulePlan', json_encode($taskSchedulePlan)]);
                (new TownShareProfit())->dealTaskSettlementMarketingDirector5($taskInfo, $townCompany, $taskSchedulePlan);
            }
        }
    }
    /**
     * 计算实际完成率
     */
    public static function countRate($procureAmount,$step)
    {
        $targetProcureAmount = 10000;
        //  目标采购额每阶段增幅30%
        for ($i = 1; $i < $step; $i++) {
            $targetProcureAmount = self::increase($targetProcureAmount);
        }
        $rate = bcdiv($procureAmount, $targetProcureAmount, 2);
        return $rate;
    }

    /**
     * 采购目标金额,增幅为30%
     */
    private static function increase($value)
    {
        return bcmul($value, 1.3,2);
    }

    /**
     * @param $taskSchedulePlan
     *  招驻一般商户
     * 自任务下发第60天结算,
     *      15天内>=$target(目标数),100%发放 60*20=1200
     *      30天内>=$target(目标数),90%发放 60*20*90%=1080
     *      60天内>=$target(目标数),80%发放 60*20*80%=960
     *      60天内>50%$target(目标数),40%发放 60*20*40%=640
     */
    private static function dealTaskMarketingDirector6($taskSchedulePlan)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $taskMoney = self::countTaskMarketingDirector6TaskMoney($templateInfo, $townCompany);
        // 0 未到结算日期 刷新任务  -1 未完成任务,关闭任务
        if ($taskMoney == 0) {
            self::flushTaskTime($taskSchedulePlan); // 刷新任务
        } else if($taskMoney == -1) {
            (new Task())->closeTask($taskSchedulePlan['task_id']); // 关闭任务
        } else {
            // 结算分润
            (new TownShareProfit())->dealTaskSettlementMarketingDirector6($taskInfo, $townCompany, $taskSchedulePlan);
        }

    }
    private static function countTaskMarketingDirector6TaskMoney($templateInfo, $townCompany)
    {
        $dayCount = $templateInfo['day_count'];
        $totalMoney = bcmul($templateInfo['stage_day_one'], $templateInfo['money']); // 任务最多可得金额
        $target = $templateInfo['extend']['target'];
        $taskMoney = 0;
        if ($dayCount == $templateInfo['stage_day_one']) {
            $taskMoney = -1;
            // 15 自任务下发第15天
            $startTime = strtotime($templateInfo['create_time']);
            $endTime = strtotime("+15 day", $startTime);
            $responsibleArea = $townCompany['responsible_area'];
            $param = [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'responsible_area' => $responsibleArea,
                'type' => 'street',
                'type_id' => 10
            ];
            $result = ShopRequestLogic::getGeneralMerchantCount($param);
            if ($result['status'] == 200) {
                $count = $result['data']['count'];
            } else {
                $count = 0;
            }

            if ($count >= $target) {
                $taskMoney = $totalMoney;
                return $taskMoney;
            }

            // 30 自任务下发第30天
            $startTime = strtotime($templateInfo['create_time']);
            $endTime = strtotime("+30 day", $startTime);
            $responsibleArea = $townCompany['responsible_area'];
            $param = [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'responsible_area' => $responsibleArea,
                'type' => 'street',
                'type_id' => 10
            ];
            $result = ShopRequestLogic::getGeneralMerchantCount($param);
            Log::error('查询供应链商户统计接口失败'.ShopRequestLogic::getError());
            $count = $result['data']['count'];
            if ($count >= $target) {
                $taskMoney = bcmul($totalMoney, 0.9, 2);
                return $taskMoney;
            }

            // 60 自任务下发第60天
            $startTime = strtotime($templateInfo['create_time']);
            $endTime = strtotime("+60 day", $startTime);
            $responsibleArea = $townCompany['responsible_area'];
            $param = [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'responsible_area' => $responsibleArea,
                'type' => 'street',
                'type_id' => 10
            ];
            $result = ShopRequestLogic::getGeneralMerchantCount($param);
            Log::error('查询供应链商户统计接口失败'.ShopRequestLogic::getError());
            $count = $result['data']['count'];
            if ($count >= $target) {
                $taskMoney = bcmul($totalMoney, 0.8, 2);
                return $taskMoney;
            } else {
                $rate = bcdiv($count, $target, 1);
                if (bccomp($rate, 0.5, 1) == 0 || bccomp($rate, 0.5, 1) == 1) {
                    $taskMoney = bcmul($totalMoney, 0.4, 2);
                    return $taskMoney;
                }
            }
        }
        return $taskMoney;
    }

    /**
     * 协助一般商户商品上架和库存更新
     * 任务累计天数小于第一阶段 关闭任务不做其他操作
     * 任务累计天数==第一阶段 查询第一阶段期间入驻的商户是否完成商品上架任务
     * 任务累计天数>第一阶段 小于第一+第二阶段 关闭任务,不做其他操作
     * 任务累计天数 == 第一+第二阶段 查询第一+第二阶段期间入驻的商户是否完成商品上架任务
     * 长期 当日时间戳 - 第一+第二阶段天数 不能整除30 关闭任务,不做其他操作
     * 长期 当日时间戳 - 第一+第二阶段天数 能整除30 则查询这段时间内所有商户是否完成库存更新任务
     */
    private static function dealTaskMarketingDirector7($taskSchedulePlan)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $templateInfo['day_count'];
        $stageDayOne = $templateInfo['stage_day_one'];
        $stageDayTwoCount= bcadd($stageDayOne, $templateInfo['stage_day_two']);
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();

        // 任务累计天数小于第一阶段 关闭任务不做其他操作
        if ($dayCount < $stageDayOne) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 任务累计天数==第一阶段 查询第一阶段期间入驻的商户是否完成商品上架任务
        if ($dayCount == $stageDayOne) {
            $taskIsDone = self::judgeTaskMarketingDirector7($townCompany);
            // 结算分润
            if($taskIsDone) {
                $taskInfo['money'] = bcmul($stageDayOne, $templateInfo['money'], 2);
                (new TownShareProfit())->dealTaskSettlementMarketingDirector7($taskInfo,$townCompany, $taskSchedulePlan);
            } else {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }

        }

        // 任务累计天数>第一阶段 小于第一+第二阶段 关闭任务,不做其他操作
        if($dayCount > $stageDayOne && $dayCount < $stageDayTwoCount) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 任务累计天数 == 第一+第二阶段 查询第一+第二阶段期间入驻的商户是否完成商品上架任务
        if ($dayCount == $stageDayTwoCount) {
            $taskIsDone = self::judgeTaskMarketingDirector7($townCompany);
            // 结算分润
            if($taskIsDone) {
                $taskInfo['money'] = bcmul($templateInfo['stage_day_two'], $templateInfo['money'], 2);
                (new TownShareProfit())->dealTaskSettlementMarketingDirector7($taskInfo,$townCompany, $taskSchedulePlan);
            } else {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }

        // 长期 当日时间戳 - 第一+第二阶段天数 不能整除30 关闭任务,不做其他操作
        if($dayCount > $stageDayTwoCount && $dayCount%30 != 0) {
            (new Task())->closeTask($taskInfo['id']);
        }

        // 长期 当日时间戳 - 第一+第二阶段天数 能整除30 则查询这段时间内所有商户是否完成库存更新任务
        if($dayCount > $stageDayTwoCount && $dayCount%30 == 0) {
            $taskIsDone = true;
            $shopMerchantSettleinLogList= ShopMerchantSettleinLog::where(['town_company_id'=>$townCompany['id']])->select()->toArray();
            // 遍历农科公司区域下的商户,对每个商户进行判定
            foreach ($shopMerchantSettleinLogList as $item) {
                // 库存更新 当前日期00:00:00 往前推30日
                $startTime = strtotime("-30 day", strtotime(date('Y-m-d', time())));
                $endTime = strtotime(date('Y-m-d', time()));
                $merIntentionId = $item['mer_intention_id'];
                $param = [
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'mer_intention_id' => $merIntentionId,
                    'type_id' => 10
                ];
                $result = ShopRequestLogic::getGeneralMerchantStockUpdate($param);
                $count = $result['data']['count'];
                Log::info(['4.市场部长-一般商户完成库存更新任务-查询商城接口结果', json_encode($result)]);
                // 任一商户未完成,判定为未完成
                if ($count == 0){
                    $taskIsDone = false;
                }
            }
            if($taskIsDone) {
                $taskInfo['money'] = bcmul(30, $templateInfo['money_three'], 2);
                (new TownShareProfit())->dealTaskSettlementMarketingDirector7($taskInfo,$townCompany, $taskSchedulePlan);
            }
        }
    }

    /**
     * 判定一般商户是否完成任务
     */
    private static function judgeTaskMarketingDirector7($townCompany)
    {
        $taskIsDone = true;
        // 商城商户入驻申请id 与商户已关联
        $shopMerchantSettleinLogList= ShopMerchantSettleinLog::where(['town_company_id'=>$townCompany['id']])->select()->toArray();
        // 遍历农科公司区域下的商户,对每个商户进行判定
        foreach ($shopMerchantSettleinLogList as $item) {
            // 商品上架
            $startTime = strtotime($item['create_time']); // 入驻时间
            $endTime = bcadd($startTime, bcmul(86400, 5));
            // 第一阶段
            $merIntentionId = $item['mer_intention_id'];
            $param = [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'mer_intention_id' => $merIntentionId,
                'type_id' => 10
            ];

            $result = ShopRequestLogic::getGeneralMerchantProductListing($param);
            Log::info(['4.市场部长-一般商户完成商品上架任务-查询商城接口结果失败', json_encode($result)]);
            $count = $result['data']['count'];
            // 任一商户未完成,判定为未完成
            if ($count < 200) {
                $taskIsDone = false;
            }
        }
        return $taskIsDone;

    }

    /**
     * @param $taskSchedulePlan
     * 督促一般商户完成采购
     * 任务累计天数 < 第一阶段 关闭任务
     * 任务累计天数 = 第一阶段  判定条件完成,结算
     * 长期 任务累计天数 > 第一阶段 且 不整除30 关闭
     * 长期 任务累计天数 > 第一阶段 且 整除30 结算
     */
    private static function dealTaskMarketingDirector8($taskSchedulePlan)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $templateInfo['day_count'];
        $stageDayOne = $templateInfo['stage_day_one'];
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        // 任务累计天数 < 第一阶段 关闭任务
        if ($dayCount < $stageDayOne) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 任务累计天数 = 第一阶段  判定条件完成,结算
        if ($dayCount == $stageDayOne) {
            // 第一个月
            $startTime = strtotime(date('Y-m-d', strtotime($taskInfo['create_time']))); // 任务下发当天 00:00:00
            $endTime = strtotime("+30 day", $startTime); // 30天后的00:00:00
            $taskMoney1 = self::countMonthTaskMoney($templateInfo, $townCompany, 10000, $startTime,  $endTime);

            // 第二个月
            $startTime = strtotime(date('Y-m-d', $endTime)); // 第一个月截止日 00:00:00
            $endTime = strtotime("+30 day", $startTime); // 30天后的00:00:00
            $taskMoney2 = self::countMonthTaskMoney($templateInfo, $townCompany, 20000, $startTime,  $endTime);

            $taskMoney = bcadd($taskMoney1, $taskMoney2, 2);
            if ($taskMoney != 0) {
                $taskInfo['money'] = $taskMoney;
                (new TownShareProfit())->dealTaskSettlementMarketingDirector8($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                // 两次都等于0 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }

        // 长期 任务累计天数 > 第一阶段 且 不整除30 关闭
        if ($dayCount > $stageDayOne && $dayCount % 30 != 0) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 长期 任务累计天数 > 第一阶段 且 整除30 结算
        if ($dayCount > $stageDayOne && $dayCount % 30 == 0) {
            $totalMoney = bcmul(30, $templateInfo['money_three']);
            $startTime = strtotime('-30 day',strtotime(date('Y-m-d', time()))); // 当前日期00:00:00 倒推30天
            $endTime = strtotime(date('Y-m-d', time()));  // 当前日期00:00:00
            $param = [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'responsible_area' => $townCompany['responsible_area'], // 镇农科管理区域
                'goods_id' => $templateInfo['extend']['goods_id'],
                'type'=>200
            ];
            $result = ShopRequestLogic::getGeneralMerchantPurchaseAmount($param);
            $procureAmount = $result['data']['procure_amount'];

            $step = bcdiv(bcsub($dayCount,  $stageDayOne), 30);
            $target = $templateInfo['extend']['target'];
            $rate = self::countRate1($procureAmount, $target, $step); // 实际完成率
            if (bccomp($rate, 0.5, 1) == -1) {
                // 完成率低于50% 未完成 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            } else {
                $taskMoney = 0;
                if ($procureAmount >= 100000) {
                    $taskMoney = $totalMoney;
                } else {
                    // 计算结算金额 周期天数*(money/目标数)*实际完成率*对应发放比例
                    $taskMoney= self::countTaskMarketingDirector4TaskMoney($totalMoney, $rate);
                }
                $taskInfo['money'] = $taskMoney;
                (new TownShareProfit())->dealTaskSettlementMarketingDirector8($taskInfo, $townCompany, $taskSchedulePlan);
            }
        }
    }

    private static function countMonthTaskMoney($templateInfo, $townCompany, $targetProcureAmount, $startTime, $endTime)
    {
        $totalMoney = bcmul(30, $templateInfo['money']);
        $param = [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'responsible_area' => $townCompany['responsible_area'], // 镇农科管理区域
            'goods_id' => $templateInfo['extend']['goods_id'],
            'type'=>200
        ];
        $result = ShopRequestLogic::getGeneralMerchantPurchaseAmount($param);
        $procureAmount = $result['data']['procure_amount'];
        $rate = bcdiv($procureAmount, $targetProcureAmount, 1);
        if (bccomp($rate, 0.5, 1) == -1) {
            return 0;
        }
        $taskMoney = 0;
        if ($procureAmount >= 100000) {
            $taskMoney = $totalMoney;
        } else {
            // 计算结算金额 周期天数*(money/目标数)*实际完成率*对应发放比例
            $taskMoney= self::countTaskMarketingDirector4TaskMoney($totalMoney, $rate);
        }
        return $taskMoney;
    }
    /**
     * 计算实际完成率
     */
    public static function countRate1($procureAmount, $target, $step)
    {
        $targetProcureAmount = bcmul($target, 1000, 2);
        //  目标采购额每阶段增幅20%
        for ($i = 1; $i < $step; $i++) {
            $targetProcureAmount = self::increase1($targetProcureAmount);
        }
        $rate = bcdiv($procureAmount, $targetProcureAmount, 2);
        return $rate;
    }

    /**
     * 采购目标金额,增幅为30%
     */
    private static function increase1($value)
    {
        return bcmul($value, 1.2,2);
    }

    /**
     * @param $taskSchedulePlan
     *  督促一般商户完成销售
     *  任务累计天数 < 第一阶段 关闭任务
     *  任务累计天数 = 第一阶段  判定条件完成,计算任务金额,分润结算
     *  长期 任务累计天数 > 第一阶段 且 不整除30 关闭
     *  长期 任务累计天数 > 第一阶段 且 整除30 计算任务金额,分润结算
     */
    private static function dealTaskMarketingDirector9($taskSchedulePlan)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $templateInfo['day_count'];
        $stageDayOne = $templateInfo['stage_day_one'];
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();

        // 任务累计天数 < 第一阶段 关闭任务
        if ($dayCount < $stageDayOne) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 任务累计天数 = 第一阶段  判定条件完成,计算任务金额,分润结算
        if ($dayCount == $stageDayOne) {
            // 第一个月
            $startTime = strtotime(date('Y-m-d', strtotime($taskInfo['create_time']))); // 任务下发当天 00:00:00
            $endTime = strtotime("+30 day", $startTime); // 30天后的00:00:00
            $taskMoney1 = self::countTradeAmountMonthTaskMoney($templateInfo, $townCompany, 10000, $startTime,  $endTime);

            // 第二个月
            $startTime = strtotime(date('Y-m-d', $endTime)); // 第一个月截止日 00:00:00
            $endTime = strtotime("+30 day", $startTime); // 30天后的00:00:00
            $taskMoney2 = self::countTradeAmountMonthTaskMoney($templateInfo, $townCompany, 20000, $startTime,  $endTime);

            $taskMoney = bcadd($taskMoney1, $taskMoney2, 2);
            if ($taskMoney != 0) {
                $taskInfo['money'] = $taskMoney;
                (new TownShareProfit())->dealTaskSettlementMarketingDirector8($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                // 两次都等于0 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }

        // 长期 任务累计天数 > 第一阶段 且 不整除30 关闭
        if ($dayCount > $stageDayOne && $dayCount % 30 != 0) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }
        //  长期 任务累计天数 > 第一阶段 且 整除30 计算任务金额,分润结算
        if ($dayCount > $stageDayOne && $dayCount % 30 == 0) {
            $totalMoney = bcmul(30, $templateInfo['money_three']);
            $startTime = strtotime('-30 day',strtotime(date('Y-m-d', time()))); // 当前日期00:00:00 倒推30天
            $endTime = strtotime(date('Y-m-d', time()));  // 当前日期00:00:00
            $param = [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'responsible_area' => $townCompany['responsible_area'], // 镇农科管理区域
                'goods_id' => $templateInfo['extend']['goods_id'],
                'type'=>200
            ];
            $result = ShopRequestLogic::getGeneralMerchantPurchaseAmount($param);
            $procureAmount = $result['data']['procure_amount'];

            $step = bcdiv(bcsub($dayCount,  $stageDayOne), 30);
            $target = $templateInfo['extend']['target'];
            $rate = self::countRate1($procureAmount, $target, $step); // 实际完成率
            if (bccomp($rate, 0.5, 1) == -1) {
                // 完成率低于50% 未完成 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            } else {
                $taskMoney = 0;
                if ($procureAmount >= 100000) {
                    $taskMoney = $totalMoney;
                } else {
                    // 计算结算金额 周期天数*(money/目标数)*实际完成率*对应发放比例
                    $taskMoney= self::countTaskMarketingDirector4TaskMoney($totalMoney, $rate);
                }
                $taskInfo['money'] = $taskMoney;
                (new TownShareProfit())->dealTaskSettlementMarketingDirector8($taskInfo, $townCompany, $taskSchedulePlan);
            }
        }
    }

    private static function countTradeAmountMonthTaskMoney($templateInfo, $townCompany, $targetProcureAmount, $startTime, $endTime)
    {
        $totalMoney = bcmul(30, $templateInfo['money']);
        $param = [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'responsible_area' => $townCompany['responsible_area'], // 镇农科管理区域
            'goods_id' => $templateInfo['extend']['goods_id'],
            'type'=>300
        ];
        $result = ShopRequestLogic::getGeneralMerchantTradeAmount($param);
        $tradeAmount = $result['data']['procure_amount'];
        $rate = bcdiv($tradeAmount, $targetProcureAmount, 1);
        if (bccomp($rate, 0.5, 1) == -1) {
            return 0;
        }
        $taskMoney = 0;
        if ($tradeAmount >= $targetProcureAmount) {
            $taskMoney = $totalMoney;
        } else {
            // 计算结算金额 周期天数*(money/目标数)*实际完成率*对应发放比例
            $taskMoney= self::countTaskMarketingDirector4TaskMoney($totalMoney, $rate);
        }
        return $taskMoney;
    }


    /**
     *  伪代码注释 自动判定时逻辑
     *  任务累计天数 < 第一阶段天数 关闭任务
     *  任务累计天数 = 第一阶段  判定任务完成情况,计算任务金额,分润结算
     *  第一阶段  < 任务累计天数 < 第一+第二阶段天数 关闭任务
     *  任务累计天数 = 第一+第二阶段  判定任务完成情况,计算任务金额,分润结算
     *  第一+第二阶段 < 任务累计天数 < 第一+第二+第三阶段天数 关闭任务
     *  任务累计天数 = 第一+第二+第三阶段  判定任务完成情况,计算任务金额,分润结算
     *  第一+第二+第三阶段天数 < 任务累计天数  且不能整除30 关闭任务
     *  任务累计天数 > 第一+第二+第三阶段天数  且能整除30 判定任务完成情况,计算金额,分润结算
     */

    /**
     * @param $taskSchedulePlan
     * 数字农贸宣传业务、加工业务的建设和招商工作  后台审批通过时做结算 把凭证保存到任务的extend中
     * 第一阶段 审批通过,判断任务是否还在第一阶段,在就结算,不在则关闭任务
     * 第二阶段 审批通过,判断任务是否还在第一阶段,在就结算,不在则关闭任务
     * 第三阶段 审批通过,判断任务是否还在第一阶段,在就结算,不在则关闭任务
     * 第四阶段 审批通过,判断任务是否还在第一阶段,在就结算,不在则关闭任务
     */
    public static function dealTaskMarketingDirector10($taskSchedulePlan, $approve)
    {
        $templateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $templateInfo['day_count'];
        $stageDayOne = $templateInfo['stage_day_one'];
        $stageDayTwoCount = bcadd($templateInfo['stage_day_one'], $templateInfo['stage_day_two']);
        $stageDayThreeCount = bcadd($templateInfo['stage_day_three'], $stageDayTwoCount);
        $townCompany = Company::where(['id' => $templateInfo['company_id']])->find();
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $approveExtend = json_decode($approve['extend'], true);

        // 第一阶段 审批通过,判断任务是否还在第一阶段,在就结算,不在则关闭任务
        if ($approveExtend['stage'] == 1) {
            if ($dayCount <= $stageDayOne) {
               // 结算
                $taskMoney = bcmul($templateInfo['money'], $stageDayOne, 2);
                $taskInfo['money'] = $taskMoney;
                (new TownShareProfit())->dealTaskSettlementMarketingDirector10($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                // 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }

        // 第二阶段 审批通过,判断任务是否还在第二阶段,在就结算,不在则关闭任务
        if ($approveExtend['stage'] == 2) {
            if ($stageDayOne < $dayCount && $dayCount <= $stageDayTwoCount) {
                // 结算
                $taskMoney = bcmul($templateInfo['money_two'], $templateInfo['stage_day_two'], 2);
                $taskInfo['money'] = $taskMoney;
                (new TownShareProfit())->dealTaskSettlementMarketingDirector10($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                // 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }

        // 第三阶段 审批通过,判断任务是否还在第三阶段,在就结算,不在则关闭任务
        if ($approveExtend['stage'] == 3) {
            if ($stageDayTwoCount < $dayCount && $dayCount <= $stageDayThreeCount) {
                // 结算
                $taskMoney = bcmul($templateInfo['new_money_three'], $templateInfo['stage_day_three'], 2);
                $taskInfo['money'] = $taskMoney;
                (new TownShareProfit())->dealTaskSettlementMarketingDirector10($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                // 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }

        // 第四阶段 长期 审批通过,判断任务是否还在第四阶段,在就结算,不在则关闭任务
        if ($approveExtend['stage'] == 4) {
            if ($dayCount > $stageDayThreeCount) {
                // 结算
                $taskMoney = bcmul($templateInfo['money_three'], 30, 2);
                $taskInfo['money'] = $taskMoney;
                (new TownShareProfit())->dealTaskSettlementMarketingDirector10($taskInfo, $townCompany, $taskSchedulePlan);
            } else {
                // 关闭任务
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            }
        }
    }
    /**
     * @param $taskSchedulePlan
     * 服务部长任务结算
     */
    private static function serviceManagerTaskSettlement($taskSchedulePlan)
    {
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        // 任务类型用的数据字典主键id,将id和value作映射,避免测试和正式环境数据字典数据不一致时出问题
        $townTaskTypeList = DictData::where(['type_value' => 'town_task_type', 'status' => 1])->column('value', 'id');
        switch ($townTaskTypeList[$taskTemplateInfo['type']]){

            case 'town_task_type_1':
                // 协助总负责人开展工作任务
                self::dealTownTask1($taskSchedulePlan);
                break;
            case 'town_task_type_2':
                // 拓展小组服务团队工作任务
                self::dealTownTask2($taskSchedulePlan);
                break;
            case 'town_task_type_3':
                // 督促小组服务团队完成任务,协助开展工作,解决问题任务
                self::dealTownTask3($taskSchedulePlan);
                break;
            case 'town_task_type_4':
                // 督促小组服务团队学习任务
                self::dealTownTask4($taskSchedulePlan);
                break;
            case 'town_task_type_5':
                // 督促小组服务团队完成需求收集和交易任务
                self::dealTownTask5($taskSchedulePlan);
                break;
            case 'town_task_type_6':
                // 督促小组服务团队入股村联络员所成立的公司任务
                // 后台手动审核 只判断任务是否超时
                Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
                $taskTemplateInfo = $taskSchedulePlan['template_info'];
                $taskDayCount = $taskTemplateInfo['day_count']; // 任务累计进行天数
                $stageDayTwoAccumulative = intval(bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two'])); // 第二阶段累计天数 第一+第二
                // 当前任务进行天数 <= 第一+第二阶段天数  只刷新任务时间
                if ($taskDayCount <= $stageDayTwoAccumulative) {
                    self::flushTaskTime($taskSchedulePlan);
                    return true;
                } else {
                    (new Task())->closeTask($taskSchedulePlan['task_id']);
                }
//                self::dealTownTask6($taskSchedulePlan);
                break;
            case 'town_task_type_7':
                // 安全工作任务
                self::dealTownTask7($taskSchedulePlan);
                break;
            default :
                return true;
        }
    }

    /**
     * 系统自动判定镇农科公司下属小组服务公司 是否100%完成每日任务:三轮车任务,档案更新任务,平台交易任务
     */
    private static function dealTownTask1($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $taskInfo = Task::where(['id' => $taskSchedulePlan['task_id']])->find();
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $isDone = 1; // 任务是否完成标记
        $isTaskSchedule = 0; // 下属小组服务公司是否有每日任务安排标记

        // 负责人 每日任务类型id列表
        $typeIds = [];
        $townMasterTaskTypeList = DictData::where(['type_value' => 'town_task_type_master', 'status' => 1])->column('value', 'id');
        foreach ($townMasterTaskTypeList as $k=>$item) {
            if ($item == 'town_task_type_master_3') {
                $typeIds[] = $k;
            }
            if ($item == 'town_task_type_master_4') {
                $typeIds[] = $k;
            }
//            if ($item == 'town_task_type_master_5') {
//                $typeIds[] = $k;
//            }
            if ($item == 'town_task_type_master_8') {
                $typeIds[] = $k;
            }
        }
        // 查询 镇农科公司负责人是否有对应的每日任务安排
        $templateList = TaskTemplate::where(['company_id'=>$townCompany['id']])->whereIn('type', $typeIds)->select()->toArray();
        // 未做任务安排的小组服务公司不在判定范围内,跳出本次循环
        if(count($templateList) === 3) {
            $isTaskSchedule = 1;
            // 查询负责人的循环任务有没有全部做完 任意有一个任务没有做完,则判定为 协助总负责人开展工作任务 失败
            foreach ($templateList as $template) {
                $task = Task::where(['template_id' => $template['id'], 'status' => 3])->find();
                if (empty($task)) {
                    $isDone = 0;
                    break;
                }
            }
        }

        // 下属小组服务公司有任务安排,也完成了任务
        if ($isDone === 1 && $isTaskSchedule === 1) {
            // 做任务结算,分润
            (new TownShareProfit())->townTaskType1($taskInfo, $townCompany, $taskSchedulePlan);
        } else {
            // 关闭任务
            (new Task())->closeTask($taskSchedulePlan['task_id']);
            Log::info('协助总负责人开展工作任务,结算失败:' . $taskTemplateInfo['title'] . '未完成。任务:' . json_encode($taskInfo));
        }
    }

    /**
     * 拓展小组服务团队工作任务 单次任务
     *  当前任务进行天数 < 第一阶段天数  只刷新任务时间
     *  当前任务进行天数 = 第一阶段天数  做第一阶段结算 如果第一阶段已完成全部任务,也要刷新任务时间,等到第二阶段结算时才结束任务
     *  当前任务进行天数 > 第一阶段天数  但未到第二阶段结算时间  继续刷新任务时间
     *  当前任务进行天数 = (第一阶段+第二阶段)天数  未完成则关闭任务 完成则结算第二阶段金额
     */
    private static function dealTownTask2($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $day = $taskTemplateInfo['stage_day_one'] + $taskTemplateInfo['stage_day_two'];
        $task = Task::where('id', $taskSchedulePlan['task_id'])->with('director_info')->find();

        // 当前任务进行天数 < 第一阶段天数  只刷新任务时间
        if($taskTemplateInfo['day_count'] < $taskTemplateInfo['stage_day_one']) {
            self::flushTaskTime($taskSchedulePlan);
            return true;
        }

        // 当前任务进行天数 = 第一阶段天数   做第一阶段结算 如果第一阶段已完成全部任务,也要刷新任务时间,等到第二阶段结算时才结束任务
        if($taskTemplateInfo['day_count'] == $taskTemplateInfo['stage_day_one']) {
            // 已签约的小组服务合同个数
            $contractCount = Contract::where(['party_a' => $townCompany['id'], 'status' => 1, 'contract_type' => 25])->count();
            if ($contractCount < 9) {
                self::flushTaskTime($taskSchedulePlan);
                return false;
            }
            $totalMoney = bcmul($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['money'], 2);
            $taskMoney = 0;
            switch ($contractCount) {
                case 9:
                    $taskMoney = bcmul($totalMoney, 0.4, 2);
                    break;
                case 10:
                    $taskMoney = bcmul($totalMoney, 0.4, 2);
                    break;
                case 11:
                    $taskMoney = bcmul($totalMoney, 0.5, 2);
                    break;
                case 12:
                    $taskMoney = bcmul($totalMoney, 0.6, 2);
                    break;
                case 13:
                    $taskMoney = bcmul($totalMoney, 0.6, 2);
                    break;
                case 14:
                    $taskMoney = bcmul($totalMoney, 0.7, 2);
                    break;
                case 15:
                    $taskMoney = bcmul($totalMoney, 1, 2);
                    break;
            }
            if ($contractCount > 15) {
                $taskMoney = bcmul($totalMoney, 1, 2);
            }
            $task['money'] = $taskMoney; // 任务金额
            (new TownShareProfit())->townTaskType2($task, $townCompany, $taskSchedulePlan, 1, $contractCount);
        }

        // 当前任务进行天数 > 第一阶段天数 但未到第二阶段结算  继续刷新任务时间
        if($taskTemplateInfo['day_count'] > $taskTemplateInfo['stage_day_one'] &&  $taskTemplateInfo['day_count'] < $day){
            self::flushTaskTime($taskSchedulePlan);
        }

        // 当前任务进行天数 = 第一+第二阶段天数  第二阶段结算
        if ($taskTemplateInfo['day_count'] == $day) {
            // 已签约的小组服务合同个数
            $contractCount = Contract::where(['party_a' => $townCompany['id'], 'status' => 1, 'contract_type' => 25])->count();
            // 第二阶段未完成
            if ($contractCount < 15) {
                // 关闭任务,并且没有奖励
                (new Task())->closeTask($taskSchedulePlan['task_id']);
                Log::info('结算失败:' . $taskTemplateInfo['title'] . '第二阶段未完成。任务:' . json_encode($task));
                return false;
            }

            $taskMoney = bcmul($taskTemplateInfo['stage_day_two'], $taskTemplateInfo['money_two'], 2);
            $task['money'] = $taskMoney; // 任务金额

            (new TownShareProfit())->townTaskType2($task, $townCompany, $taskSchedulePlan, 2, $contractCount);
        }


    }

    private static function flushTaskTime($taskSchedulePlan)
    {
        $time = strtotime(date('Y-m-d')); // 今天的 00:00:00

        TaskSchedulingPlan::where(['id' => $taskSchedulePlan['id']])->update(
            [
                'update_time' =>time(),
                'start_time'=>$time+86400, //第二天的00:00:00
                'end_time'=>$time+86400+86399 //第二天的 23:59:59
            ]);

        Task::where('id', $taskSchedulePlan['task_id'])->update(
            [
                'update_time' => time(),
                'start_time'=> $time+86400,
                'end_time'=> $time+86400+86399
            ]);
    }

    private static function dealTownTask3($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $groupServiceCompanyList = Db::query("select * from la_company where company_type=:company_type and FIND_IN_SET(street,:responsible_area)", ['company_type' => 18,'responsible_area'=>$townCompany['responsible_area']], true);
//        $groupServiceCompanyList = Company::where(['street' => $townCompany['street'], 'company_type' => 18])->select()->toArray();
        $task = Task::where('id', $taskSchedulePlan['task_id'])->with('director_info')->find();
        // 完成任务情况
        list($groupServiceCompanyCount, $doneTaskGroupServiceCompanyCount) = self::taskType3DoneInfo($groupServiceCompanyList);
        if ($groupServiceCompanyCount == 0) {
            throw new Exception('小组服务公司数量为0异常'.__FILE__.__LINE__);
        }
        $doneRate = bcdiv($doneTaskGroupServiceCompanyCount, $groupServiceCompanyCount,2);
        // <80%  未完成任务 关闭本次任务
        if (bccomp($doneRate, 0.8, 2) == -1) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
            return true;
        } else {
            // 结算 分润
            (new TownShareProfit())->townTaskType3($task, $townCompany, $taskSchedulePlan);
        }
    }

    public static function taskType3DoneInfo($groupServiceCompanyList)
    {
        $groupServiceCompanyCount = count($groupServiceCompanyList); // 团队总数
        $doneTaskGroupServiceCompanyCount = 0; // 完成任务团队总数
        // 判定完成条件 组建成功的小组服务团队 每日完成档案更新任务和三轮车任务 的团队数量 >= 80%  小于80%则视为未完成
        foreach ($groupServiceCompanyList as $groupServiceCompany) {
            // 档案更新任务
            $taskType31 = Task::where(['company_id' => $groupServiceCompany['id'], 'type' => 31, 'status' => 3])->whereDay('start_time', 'today')->find();
            // 三轮车任务
            $taskType32 = Task::where(['company_id' => $groupServiceCompany['id'], 'type' => 32, 'status' => 3])->whereDay('start_time', 'today')->find();
            if (!empty($taskType31) && !empty($taskType32)) {
                $doneTaskGroupServiceCompanyCount++;
            }
        }
        return [$groupServiceCompanyCount, $doneTaskGroupServiceCompanyCount];
    }

    /**
     * 督促小组服务团队学习任务  长期任务   前置操作:每天要从APP端提交资料上来,根据提交资料来判定当天任务有没有完成
     *  任务完成条件:(学习照片5张,签到表一份,培训内容大纲 >= 50个字),每月提交>=4次
     *  1 当前任务进行天数 < 第一阶段天数  只判断当天是否完成  状态未完成则关闭任务
     *  2 当前任务进行天数 = 第一阶段天数  做第一阶段结算  且更改 task_schedule_plan 状态为已结算,后续将会根据这个时间来统计、判断各阶段的周期内是否达成完成条件(*)
     *  3 第一阶段天数 < 当前任务进行天数  <   (第一 + 第二) 只判断当天是否完成  状态未完成则关闭任务
     *  4 当前任务进行天数 = (第一阶段+第二阶段)天数  第二阶段结算 且更改 task_schedule_plan 状态为已结算
     *  5 第一阶段+第二阶段 < 当前任务进行天数 < (第一 + 第二 + 第三阶段天数)  只判断当天是否完成  状态未完成则关闭任务
     *  6 当前任务进行天数 = (第一 + 第二 + 第三阶段天数)  第三阶段结算 且更改 task_schedule_plan 状态为已结算
     *  7 当前任务进行天数 > (第一 + 第二 + 第三阶段天数) 但 当前任务进行天数/30 != 0  只判断当天是否完成  状态未完成则关闭任务
     *  8 当前任务进行天数/30 = 0, 长期阶段结算 且更改 task_schedule_plan 状态为已结算
     */
    private static function dealTownTask4($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $taskDayCount = $taskTemplateInfo['day_count']; // 任务累计进行天数
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
        $stageDayOneAccumulative = $taskTemplateInfo['stage_day_one']; // 第一阶段累计天数
        $stageDayTwoAccumulative = intval(bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two'])); // 第二阶段累计天数 第一+第二
        $stageDayThreeAccumulative = intval(bcadd($stageDayTwoAccumulative, $taskTemplateInfo['stage_day_three'])); // 第三阶段累计天数 第二阶段累计值+第三阶段天数

        // 1 当前任务进行天数 < 第一阶段天数  只判断当天是否完成 状态未完成则关闭任务
        if ($taskDayCount < $stageDayOneAccumulative) {
            if ($task['status'] != 3) {
                (new Task())->closeTask($task['id']);
            }
            return false;
        }

        // 2 当前任务进行天数 = 第一阶段天数  做第一阶段结算  且更改 task_schedule_plan 状态为已结算,后续将会根据这个时间来筛选、统计、判断各阶段周期内是否达成完成条件
        if($taskDayCount  == $stageDayOneAccumulative){
            $doneTaskCount = Task::where(['template_id'=>$taskTemplateInfo['id'], 'status'=>3])->count();
            if ($doneTaskCount >= 4) {
                $task['money'] = bcmul($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['money'], 2);
                (new TownShareProfit())->townTaskType4($task, $townCompany, $taskSchedulePlan);
            }
            return false;
        }

        // 3 第一阶段天数 < 当前任务进行天数  <   (第一 + 第二) 只判断当天是否完成  状态未完成则关闭任务
        if ($stageDayOneAccumulative < $taskDayCount  && $taskDayCount < $stageDayTwoAccumulative) {
            if ($task['status'] != 3) {
                (new Task())->closeTask($task['id']);
            }
            return false;
        }

        // 4 当前任务进行天数 = (第一阶段+第二阶段)天数  第二阶段结算 且更改 task_schedule_plan 状态为已结算
        if ($taskDayCount == $stageDayTwoAccumulative) {
            // 上一次做了结算的任务计划
            $lastTaskSchedulePlan = TaskSchedulingPlan::where(['template_id'=>$taskTemplateInfo['id'], 'is_pay'=>1])->order('start_time', 'desc')->find();
            // 上一次结算后到现在,完成的任务次数
            $doneTaskCount = Task::where(['template_id'=>$taskTemplateInfo['id'], 'status'=>3])->whereBetween('start_time', [$lastTaskSchedulePlan['start_time'], time()])->count();
            if ($doneTaskCount >= 8) {
                $task['money'] = bcmul($taskTemplateInfo['stage_day_two'], $taskTemplateInfo['money_two'], 2);
                (new TownShareProfit())->townTaskType4($task, $townCompany, $taskSchedulePlan);
            }
            return false;
        }

        // 5 第一阶段+第二阶段 < 当前任务进行天数 < (第一 + 第二 + 第三阶段天数)  只判断当天是否完成  状态未完成则关闭任务
        if ($stageDayTwoAccumulative < $taskDayCount && $taskDayCount < $stageDayThreeAccumulative) {
            if ($task['status'] != 3) {
                (new Task())->closeTask($task['id']);
            }
            return false;
        }

        // 6 当前任务进行天数 = (第一 + 第二 + 第三阶段天数)  第三阶段结算 且更改 task_schedule_plan 状态为已结算
        if ($taskDayCount == $stageDayThreeAccumulative) {
            // 上一次做了结算的任务计划
            $lastTaskSchedulePlan = TaskSchedulingPlan::where(['template_id'=>$taskTemplateInfo['id'], 'is_pay'=>1])->order('start_time', 'desc')->find();
            // 上一次结算后到现在,完成的任务次数
            $doneTaskCount = Task::where(['template_id'=>$taskTemplateInfo['id'], 'status'=>3])->whereBetween('start_time', [$lastTaskSchedulePlan['start_time'], time()])->count();
            if ($doneTaskCount >= 8) {
                $task['money'] = bcmul($taskTemplateInfo['stage_day_three'], $taskTemplateInfo['new_money_three'], 2);
                (new TownShareProfit())->townTaskType4($task, $townCompany, $taskSchedulePlan);
            }
            return false;
        }

        // 7 当前任务进行天数 > (第一 + 第二 + 第三阶段天数) 但 当前任务进行天数/30 != 0  只判断当天是否完成  状态未完成则关闭任务
        if($taskDayCount > $stageDayThreeAccumulative && $taskDayCount%30 != 0) {
            if ($task['status'] != 3) {
                (new Task())->closeTask($task['id']);
            }
            return false;
        }

        // 8 当前任务进行天数/30 = 0, 长期阶段结算 且更改 task_schedule_plan 状态为已结算
        if ($taskDayCount > $stageDayThreeAccumulative && $taskDayCount%30 == 0) {
            // 上一次做了结算的任务计划
            $lastTaskSchedulePlan = TaskSchedulingPlan::where(['template_id'=>$taskTemplateInfo['id'], 'is_pay'=>1])->order('start_time', 'desc')->find();
            // 上一次结算后到现在,完成的任务次数
            $doneTaskCount = Task::where(['template_id'=>$taskTemplateInfo['id'], 'status'=>3])->whereBetween('start_time', [$lastTaskSchedulePlan['start_time'], time()])->count();
            if ($doneTaskCount >= 4) {
                $task['money'] = bcmul(30, $taskTemplateInfo['money_three'], 2);
                (new TownShareProfit())->townTaskType4($task, $townCompany, $taskSchedulePlan);
            }
            return false;
        }
    }

    /**
     * 查镇所属小组服务公司当日实际完成金额总和+镇农科公司的资金池
     * 查镇所属小组服务公司当日任务目标金额总和
     */
    private static function dealTownTask5($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $townCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $townTask = Task::where('id', $taskSchedulePlan['task_id'])->find();
//        $groupServiceCompanyList = Company::where(['street' => $townCompany['street'], 'company_type'=> 18])->select()->toArray();
        $groupServiceCompanyList = Db::query("select * from la_company where company_type=:company_type and FIND_IN_SET(street,:responsible_area)", ['company_type' => 18,'responsible_area'=>$townCompany['responsible_area']], true);

        $townTransactionPool = $taskTemplateInfo['transaction_pool']; // 镇交易池
        $townTotalTradeAmount = 0; // 镇下属小组服务公司 每日实际总交易额
        $targetAmount = 0; // 镇下属小组服务公司每日 目标总交易额
        // 查镇所属小组服务公司当日任务目标金额总和
        foreach ($groupServiceCompanyList as $groupServiceCompany) {
            $tempTask = Task::where(['company_id'=> $groupServiceCompany['id'], 'status'=>3, 'type'=>33])
                ->whereDay('start_time','today')
                ->find();
            if ($tempTask) {
                $plan = TaskSchedulingPlan::where(['id'=>$tempTask['scheduling_plan_id']])->find();
                if ($plan['is_pay'] == 1) {
                    $extend = $tempTask['extend'];
                    $targetAmount += $extend['transaction']['arr']['day_money'];
                    $townTotalTradeAmount += $extend['transaction']['arr']['total_price'];
                }
            }
        }

        // 完成条件: 查镇所属小组服务公司当日实际完成金额总和+镇农科公司的资金池 > 查镇所属小组服务公司当日任务目标金额总和
        if($targetAmount != 0 && bcadd($townTransactionPool, $townTotalTradeAmount, 2) >= $targetAmount) {
            // 将余下金额放入镇交易池
            $leftTransactionPool = bcsub(bcadd($townTransactionPool, $townTotalTradeAmount, 2), $targetAmount, 2);
            (new TownShareProfit())->townTaskType5($townTask, $townCompany, $taskSchedulePlan, $leftTransactionPool);
        } else {
            // 关闭任务
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }
    }

    /**
     *  督促小组服务团队入股村联络员所成立的公司任务  单次任务
     *  当前任务进行天数 < 第一+第二阶段天数  只刷新任务时间
     *  当前任务进行天数 = 第一+第二阶段天数   判定任务是否完成 结算 分润
     */
    public static function dealTownTask6($taskSchedulePlan, $approve)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $taskDayCount = $taskTemplateInfo['day_count']; // 任务累计进行天数
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
        $stageDayTwoAccumulative = intval(bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two'])); // 第二阶段累计天数 第一+第二
        $townCompany = Company::where('id', $taskTemplateInfo['company_id'])->find(); // 镇农科公司

        dd($taskDayCount, $stageDayTwoAccumulative);
        // 当前任务进行天数 <= 第一+第二阶段天数   判定任务是否完成 结算 分润
        if($taskDayCount <= $stageDayTwoAccumulative) {
            // 小组服务公司总数
            $groupServiceCompanyCount = Company::where(['street' => $townCompany['street'], 'company_type'=> 18])->count();
            if ($groupServiceCompanyCount == 0) {
                throw new Exception('小组服务公司数量为0异常'.__FILE__.__LINE__);
            }
            // 小组服务完成股金上交数
            $sharecapitalPaidCount = intdiv($approve->amount, 3000);
            $rate = bcdiv($sharecapitalPaidCount, $groupServiceCompanyCount, 2);

            // 小于50% 未完成 关闭任务
            if (bccomp($rate, 0.5, 2)  == -1) {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
            } else {
                // 已完成 计算结算金额
                $totalMoney = bcadd(bcmul($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['money'], 2) , bcmul($taskTemplateInfo['stage_day_two'], $taskTemplateInfo['money_two'], 2), 2);
                // =50% - %59.9    x40%
                if (bccomp($rate, 0.5, 2)  == 0 || (bccomp($rate, 0.5, 2)  == 1 && bccomp($rate, 0.599, 2)  == -1)) {
                    $task['money'] = bcmul($totalMoney, 0.4, 2);
                }
                // =60% - %69.9    x50%
                if (bccomp($rate, 0.6, 2)  == 0 || (bccomp($rate, 0.6, 2)  == 1 && bccomp($rate, 0.699, 2)  == -1)) {
                    $task['money'] = bcmul($totalMoney, 0.5, 2);
                }

                // =70% - %79.9    x60%
                if (bccomp($rate, 0.7, 2)  == 0 || (bccomp($rate, 0.7, 2)  == 1 && bccomp($rate, 0.799, 2)  == -1)) {
                    $task['money'] = bcmul($totalMoney, 0.6, 2);
                }

                // =80% - %89.9    x70%
                if (bccomp($rate, 0.8, 2)  == 0 || (bccomp($rate, 0.8, 2)  == 1 && bccomp($rate, 0.899, 2)  == -1)) {
                    $task['money'] = bcmul($totalMoney, 0.7, 2);
                }
                // >=90%           x100%
                if (bccomp($rate, 0.9, 2)  == 0 || bccomp($rate, 0.9, 2)  == 1) {
                    $task['money'] = $totalMoney;
                }
                // 分润
                (new TownShareProfit())->townTaskType6($task, $townCompany, $taskSchedulePlan);
            }
        }
    }

    // 安全任务结算
    private static function dealTownTask7($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];

        $townCompany = Company::where('id', $taskTemplateInfo['company_id'])->find(); // 镇农科公司
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();

        // 片区下公司有任一投诉都判定为未完成
        $isDone = 1;
        $companyList = Company::where('street', $townCompany['street'])->select()->toArray();
        foreach ($companyList as $company) {
            $complain = CompanyComplaintFeedback::where(['company_id'=>$company['id']])->whereDay('create_time', 'today')->find();
            if (!empty($complain)) {
                $isDone = 0;
                break;
            }
        }

        // 完成任务 结算 分润
        if ($isDone === 1) {
            (new TownShareProfit())->townTaskType7($task, $townCompany, $taskSchedulePlan);
        } else {
            // 关闭任务
            (new Task())->closeTask($task['id']);
        }
    }

    /**
     * 村管理公司任务结算
     */
    public static function villageTaskSettlement($taskSchedulePlan)
    {
        try {
            Log::info(['存管理公司定时任务结算执行-任务计划', $taskSchedulePlan]);
            $taskTemplateInfo = $taskSchedulePlan['template_info'];
            // 任务类型用的数据字典主键id,将id和value作映射,避免测试和正式环境数据字典数据不一致时出问题
            $townTaskTypeList = DictData::where(['type_value' => 'village_task_type', 'status' => 1])->column('value', 'id');
            switch ($townTaskTypeList[$taskTemplateInfo['type']]){
                // 组建小组服务团队
                case 'village_task_type_1':
                    self::dealVillageTask1($taskSchedulePlan);
                    break;
                // 协助小组服务团队完成辖区内的交易任务
                case 'village_task_type_2':
                    self::dealVillageTask2($taskSchedulePlan);
                    break;
                // 负责辖区内农产品安检和溯源
                case 'village_task_type_3':
                    self::dealVillageTask3($taskSchedulePlan);
                    break;
                // 督促小组服务团队入股
                case 'village_task_type_4':
                    // 结算逻辑由手动审核,任务超时则关闭
                    $taskTemplateInfo = $taskSchedulePlan['template_info'];
                    $dayCount = $taskTemplateInfo['day_count'];
                    $stageDayCount = bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two']);
                    // 任务累计天数 < 第一阶段+第二阶段 刷新任务
                    if ($dayCount <= $stageDayCount) {
                        self::flushTaskTime($taskSchedulePlan);
                        return true;
                    } else {
                        (new Task())->closeTask($taskSchedulePlan['task_id']);
                    }
//                    self::dealVillageTask4($taskSchedulePlan);
                    break;
                // 入股甲方公司
                case 'village_task_type_5':
                    // 结算逻辑由手动审核,任务超时则关闭
                    $taskTemplateInfo = $taskSchedulePlan['template_info'];
                    $dayCount = $taskTemplateInfo['day_count'];
                    $stageDayCount = bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two']);
                    // 任务累计天数 < 第一阶段+第二阶段 刷新任务
                    if ($dayCount <= $stageDayCount) {
                        self::flushTaskTime($taskSchedulePlan);
                        return true;
                    } else {
                        (new Task())->closeTask($taskSchedulePlan['task_id']);
                    }
//                    self::dealVillageTask5($taskSchedulePlan);
                    break;
                // 信息平台铺设工作
                case 'village_task_type_6':
                    // 该任务的判定都需要上传资料,后台审批任务是否完成.   因此每天自动结算时,任务状态不为完成的,都做关闭任务处理
                    $task = Task::where(['id'=>$taskSchedulePlan['task_id']])->find();
                    if ($task['status'] != 3) {
                        (new Task())->closeTask($taskSchedulePlan['task_id']);
                    }
                    break;
                // 种养殖基地订单匹配
                case 'village_task_type_7':
                    self::dealVillageTask7($taskSchedulePlan);
                    break;
                // 日常管理及其他临时任务
                case 'village_task_type_8':
                    // 如果当天做了临时任务的情况下,需要通过审批才结算
                    $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
                    if(isset($task['extend']['is_commit']) && $task['extend']['is_commit'] == 1) {
                        return true;
                    }
                    self::dealVillageTask8($taskSchedulePlan);
                    break;
                default:
                    return true;
            }
        } catch (Exception $e) {
            Log::error(['村管理任务结算失败',$e->getFile(), $e->getLine(), $e->getMessage()]);
        }

    }

    /**
     * @param $taskSchedulePlan
     * 组建小组服务团队  单次任务
     * 任务累计天数 < 第一阶段+第二阶段 刷新任务
     * 任务累计天数 = 第一阶段+第二阶段 任务判定,计算金额,结算分润
     */
    private static function dealVillageTask1($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $target = $taskTemplateInfo['extend']['target'];
        $stageDayCount = bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two']);
        $villageCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
        // 村地区码与村管理公司一样
        $groupServiceCompanyList = Company::where(['village' => $villageCompany['village'], 'company_type'=> 18, 'is_contract'=>1])->select()->toArray();
        // 任务累计天数 < 第一阶段+第二阶段 刷新任务
        if ($dayCount < $stageDayCount) {
            self::flushTaskTime($taskSchedulePlan);
            return true;
         }
        // 任务累计天数 = 第一阶段+第二阶段 任务判定,计算金额,结算分润
        if ($dayCount == $stageDayCount) {
            $totalMoney = bcadd(bcmul($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['money'], 2), bcmul($taskTemplateInfo['stage_day_two'], $taskTemplateInfo['money_two'], 2), 2) ;
            $taskMoney = 0;
            $groupServiceCompanyCount = count($groupServiceCompanyList);
            $rate = bcdiv($groupServiceCompanyCount, $target, 2);
            if (bccomp($rate, 0.5, 2) == -1) {
                (new Task())->closeTask($taskSchedulePlan['task_id']);
                return true;
            }
            if (bccomp($rate, 0.5, 2) == 0 || bccomp($rate, 0.5, 2) == 1 ||  bccomp(0.8, $rate, 2) == 1) {
                $taskMoney = bcmul($totalMoney, bcmul($rate, 0.6, 2), 2);
            }

            if (bccomp($rate, 0.8, 2) == 0 || bccomp($rate, 0.8, 2) == 1) {
                $taskMoney = bcmul($totalMoney, bcmul($rate, 1, 2), 2);
            }
            $task['money'] = $taskMoney;
            (new VillageShareProfit())->dealVillageTaskSettlement1($task, $villageCompany, $taskSchedulePlan);
        }
    }

    /**
     * @param $taskSchedulePlan
     * 协助小组服务团队完成交易任务
     *
     */
    private static function dealVillageTask2($taskSchedulePlan)
    {
        Log::info(['村管理公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $villageCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
        $groupServiceCompanyList = Company::where(['village' => $villageCompany['village'], 'company_type'=> 18, 'is_contract'=>1])->select()->toArray();

        $villageTransactionPool = $taskTemplateInfo['transaction_pool']; // 村交易池
        $villageTotalTradeAmount = 0; // 村下属小组服务公司 每日实际总交易额
        $targetAmount = 0; // 村下属小组服务公司每日 目标总交易额
        // 查村所属小组服务公司当日任务目标金额总和
        foreach ($groupServiceCompanyList as $groupServiceCompany) {
            $tempTask = Task::where(['company_id'=> $groupServiceCompany['id'], 'status'=>3, 'type'=>33])
                ->whereDay('start_time','today')
                ->find();
            if ($tempTask) {
                $plan = TaskSchedulingPlan::where(['id'=>$tempTask['scheduling_plan_id']])->find();
                if ($plan['is_pay'] == 1) {
                    $extend = $tempTask['extend'];
                    $targetAmount += $extend['transaction']['arr']['day_money'];
                    $villageTotalTradeAmount += $extend['transaction']['arr']['total_price'];
                }
            }
        }

        // 完成条件: 查村所属小组服务公司当日实际完成金额总和+村管理公司的资金池 > 查镇所属小组服务公司当日任务目标金额总和
        if($targetAmount != 0 && bcadd($villageTransactionPool, $villageTotalTradeAmount, 2) >= bcmul($targetAmount, 0.8, 2)) {
            // 将余下金额放入镇交易池
            $leftTransactionPool = bcsub(bcadd($villageTransactionPool, $villageTotalTradeAmount, 2), $targetAmount, 2);
            (new VillageShareProfit())->dealVillageTaskSettlement2($task, $villageCompany, $taskSchedulePlan, $leftTransactionPool);
        } else {
            // 关闭任务
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }
    }

    /**
     * @param $taskSchedulePlan
     * 负责辖区内农产品安检和溯源
     */
    private static function dealVillageTask3($taskSchedulePlan)
    {
        Log::info(['村管理公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];

        $villageCompany = Company::where('id', $taskTemplateInfo['company_id'])->find(); // 村管理公司
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();

        // 片区下公司有任一投诉都判定为未完成
        $isDone = 1;
        $companyList = Company::where(['village' => $villageCompany['village'], 'company_type'=> 18])
                                ->whereIn('brigade', $villageCompany['responsible_area'])
                                ->select()
                                ->toArray();

        foreach ($companyList as $company) {
            $complain = CompanyComplaintFeedback::where(['company_id'=>$company['id']])->whereDay('create_time', 'today')->find();
            if (!empty($complain)) {
                $isDone = 0;
                break;
            }
        }

        // 完成任务 结算 分润
        if ($isDone === 1) {
            (new VillageShareProfit())->dealVillageTaskSettlement3($task, $villageCompany, $taskSchedulePlan);
        } else {
            // 关闭任务
            (new Task())->closeTask($task['id']);
        }
    }

    /**
     * @param $taskSchedulePlan
     * 督促小组服务团队入股 手动审核通过后才结算
     */
    public static function dealVillageTask4($taskSchedulePlan, $approve)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $target = $taskTemplateInfo['extend']['target'];
        $stageDayCount = bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two']);
        $villageCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
        // 在任务期限内才结算
        if($dayCount <= $stageDayCount) {
            // 目标入股金额
            $targetShareholderedMoney = bcmul($target, 3000, 2);
            // 小组服务股金上交金额
            $shareholderedMoney = $approve->amount;

            $rate = bcdiv($shareholderedMoney, $targetShareholderedMoney, 2);
            if (bccomp($rate, 0.5, 2) == -1) {
                (new Task())->closeTask($task['id']);
                return true;
            }
            $totalMoney = bcadd(bcmul($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['money'], 2), bcmul($taskTemplateInfo['stage_day_two'], $taskTemplateInfo['money_two'], 2), 2) ;

            $task['money'] = self::countSettelmentMoney($rate, $totalMoney);
            (new VillageShareProfit())->dealVillageTaskSettlement4($task, $villageCompany, $taskSchedulePlan);
        }


    }

    private static function countSettelmentMoney($rate, $totalMoney)
    {
        $settlementMoney = 0;

        // =50% - %59.9    x40%
        if (bccomp($rate, 0.5, 2)  == 0 || (bccomp($rate, 0.5, 2)  == 1 && bccomp($rate, 0.599, 2)  == -1)) {
            $settlementMoney= bcmul($rate, bcmul($totalMoney, 0.4, 2), 2);
        }
        // =60% - %69.9    x50%
        if (bccomp($rate, 0.6, 2)  == 0 || (bccomp($rate, 0.6, 2)  == 1 && bccomp($rate, 0.699, 2)  == -1)) {
            $settlementMoney = bcmul($rate, bcmul($totalMoney, 0.5, 2), 2);;
        }

        // =70% - %79.9    x60%
        if (bccomp($rate, 0.7, 2)  == 0 || (bccomp($rate, 0.7, 2)  == 1 && bccomp($rate, 0.799, 2)  == -1)) {
            $settlementMoney = bcmul($rate, bcmul($totalMoney, 0.6, 2), 2);
        }

        // =80% - %89.9    x70%
        if (bccomp($rate, 0.8, 2)  == 0 || (bccomp($rate, 0.8, 2)  == 1 && bccomp($rate, 0.899, 2)  == -1)) {
            $settlementMoney = bcmul($rate, bcmul($totalMoney, 0.7, 2), 2);
        }
        // >=90%           x100%
        if (bccomp($rate, 0.9, 2)  == 0 || bccomp($rate, 0.9, 2)  == 1) {
            $settlementMoney = $totalMoney;
        }
        return $settlementMoney;
    }

    /**
     * @param $taskSchedulePlan
     * 入股甲方公司 手动审核通过后才结算
     */
    public static function dealVillageTask5($taskSchedulePlan, $approve)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $target = $taskTemplateInfo['extend']['target'];
        $stageDayCount = bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two']);
        if ($dayCount <= $stageDayCount) {
            //  任务累计天数 = 第一阶段+第二阶段 任务判定,计算金额,结算分润
            $villageCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
            $task = Task::where('id', $taskSchedulePlan['task_id'])->find();

            // 小组服务和村公司股金上交金额
            $shareholderedMoney = $approve->amount;
            // 目标上交股金金额 小组应组建团队数量*3000 + 村 6000
            $targetShareholderedMoney = bcadd(bcmul($target, 3000), 6000);
            $rate = bcdiv($shareholderedMoney, $targetShareholderedMoney, 2);
            $totalMoney = bcadd(bcmul($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['money'], 2), bcmul($taskTemplateInfo['stage_day_two'], $taskTemplateInfo['money_two'], 2), 2) ;
            $task['money'] = self::countSettelmentMoney($rate, $totalMoney);
            (new VillageShareProfit())->dealVillageTaskSettlement5($task, $villageCompany, $taskSchedulePlan);
        }
    }

    /**
     * @param $taskSchedulePlan
     * 信息平台铺设工作  app提交凭证,后台审批。通过后一次性发送
     */
    public static function dealVillageTask6($taskSchedulePlan)
    {
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $villageCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
        // 结算
        $stageDayOneTotalTaskMoney =  bcmul($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['money'], 2);
        $stageDayTwoTotalTaskMoney =  bcmul($taskTemplateInfo['stage_day_two'], $taskTemplateInfo['money_two'], 2);
        $taskMoney = bcadd($stageDayOneTotalTaskMoney, $stageDayTwoTotalTaskMoney, 2);
        $task['money'] = $taskMoney;
        (new VillageShareProfit())->dealVillageTaskSettlement6($task, $villageCompany, $taskSchedulePlan);
    }

    /**
     * @param $taskSchedulePlan
     * 种养殖基地订单匹配
     * 任务累计天数 < stage1  关闭任务
     * 任务累计天数 = stage1 从商城查询种养殖商户的交易额,判定是否完成任务,完成则结算
     * 任务累计天数 < stage1+stage2 关闭任务,不结算
     * 任务累计天数 = stage1+stage2 从商城查询种养殖商户的交易额,判定是否完成任务,完成则结算
     * 任务累计天数 < stage1 + stage2 + stage3 关闭任务,不结算
     * 任务累计天数 = stage1 + stage2 + stage3 从商城查询种养殖商户的交易额,判定是否完成任务,完成
     * 任务累计天数 - (stage1 + stage2 + stage3) 不能整除30 关闭任务
     * 任务累计天数 - (stage1 + stage2 + stage3) 整除30 从商城查询种养殖商户的交易额,判定是否完成任务,完成
     */
    private static function dealVillageTask7($taskSchedulePlan)
    {
        Log::info(['镇农科公司定时任务结算执行-'.$taskSchedulePlan['template_info']['title']]);
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $dayCount = $taskTemplateInfo['day_count'];
        $stageDayOne = $taskTemplateInfo['stage_day_one'];
        $stageDayTwoCount = bcadd($taskTemplateInfo['stage_day_one'], $taskTemplateInfo['stage_day_two']);
        $stageDayThreeCount = bcadd($stageDayTwoCount, $taskTemplateInfo['stage_day_three']);
        $villageCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();


        // 任务累计天数 < stage1  关闭任务
        if ($dayCount < $stageDayOne) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 任务累计天数 = stage1 从商城查询种养殖商户的交易额,判定是否完成任务,完成则结算
        if ($dayCount == $stageDayOne) {
            $startTime = strtotime(date('Y-m-d',strtotime($taskTemplateInfo['create_time'])))+86400; // 创建任务的第二天00:00:00开始
            $endTime = strtotime('+30 day', $startTime);
            self::finishVillageTask7($startTime, $endTime, 13000, $taskTemplateInfo['stage_day_one'], $taskTemplateInfo['money'], $villageCompany, $taskSchedulePlan);
        }

        // 任务累计天数 < stage1+stage2 关闭任务,不结算
        if ($dayCount < $stageDayTwoCount) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 任务累计天数 = stage1+stage2 从商城查询种养殖商户的交易额,判定是否完成任务,完成则结算
        if ($dayCount == $stageDayTwoCount) {
            $startTime = strtotime('-30 day', $endTime);
            $endTime = strtotime(date('Y-m-d', time()));
            self::finishVillageTask7($startTime, $endTime, 17000, $taskTemplateInfo['stage_day_two'], $taskTemplateInfo['money_two'], $villageCompany, $taskSchedulePlan);
        }

        // 任务累计天数 < stage1 + stage2 + stage3 关闭任务,不结算
        if ($dayCount < $stageDayThreeCount) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 任务累计天数 = stage1 + stage2 + stage3 从商城查询种养殖商户的交易额,判定是否完成任务,完成
        if ($dayCount == $stageDayThreeCount) {
            $startTime = strtotime('-30 day', $endTime);
            $endTime = strtotime(date('Y-m-d', time()));
            self::finishVillageTask7($startTime, $endTime, 17000, $taskTemplateInfo['stage_day_three'], $taskTemplateInfo['new_money_three'], $villageCompany, $taskSchedulePlan);
        }

        // 任务累计天数 - (stage1 + stage2 + stage3) 不能整除30 关闭任务
        if ($dayCount > $stageDayThreeCount && $dayCount % 30 != 0) {
            (new Task())->closeTask($taskSchedulePlan['task_id']);
        }

        // 任务累计天数 - (stage1 + stage2 + stage3) 整除30 从商城查询种养殖商户的交易额,,判定是否完成任务,完成
        if ($dayCount > $stageDayThreeCount && $dayCount % 30 == 0) {
            $startTime = strtotime('-30 day', $endTime);
            $endTime = strtotime(date('Y-m-d', time()));
            self::finishVillageTask7($startTime, $endTime, 17000, 30, $taskTemplateInfo['money_three'], $villageCompany, $taskSchedulePlan);
        }
    }

    /**
     * @param $startTime
     * @param $endTime
     * @param $targetAmount 任务目标金额
     * @param $dayNum 结算周期天数
     * @param $perMoney 每天金额
     * @param $villageCompany
     * @param $taskSchedulePlan
     * @return void
     */
    private static function finishVillageTask7( $startTime, $endTime, $targetAmount, $dayNum, $perMoney, $villageCompany, $taskSchedulePlan)
    {
        $param = [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'village' => $villageCompany['village'],

        ];
        $result = ShopRequestLogic::getPlantingAndBreedingMerchantTradeAmount($param); // todo 商城接口那边需要确定种养殖基地是何种类型的商户

        $tradeAmount = $result['data']['trade_amount'];
        // 交易池
        $transactionPool = $taskSchedulePlan['template_info']['transaction_pool'];
        $totalTradeAmount = bcadd($transactionPool, $tradeAmount, 2);
        if ($totalTradeAmount >= $targetAmount) {
            $task['money'] = bcmul($dayNum, $perMoney, 2);
            $leftTransactionPool = bcsub($totalTradeAmount, $targetAmount, 2);
            (new VillageShareProfit())->dealVillageTaskSettlement7($task, $villageCompany, $taskSchedulePlan, $leftTransactionPool);
        }
    }

    public static function dealVillageTask8($taskSchedulePlan)
    {
        $taskTemplateInfo = $taskSchedulePlan['template_info'];
        $villageCompany = Company::where(['id' => $taskTemplateInfo['company_id']])->find();
        $task = Task::where('id', $taskSchedulePlan['task_id'])->find();
        $task['money'] = $taskTemplateInfo['money_three'];
        (new VillageShareProfit())->dealVillageTaskSettlement8($task, $villageCompany, $taskSchedulePlan);
    }
}