<?php

namespace app\api\controller;

use app\common\logic\task\TaskLogic;
use app\common\model\Approve;
use app\common\model\Company;
use app\common\model\company\CompanyProperty;
use app\common\model\contract\Contract;
use app\common\model\dict\DictData;
use app\common\model\flow\Flow;
use app\common\model\informationg\UserInformationg;
use app\common\model\task\Task;
use app\common\model\task_template\TaskTemplate;
use app\common\model\user\User;
use app\common\model\vehicle\VehicleRent;
use think\Exception;
use think\facade\Db;


class TaskController extends BaseApiController
{

    public function lists()
    {
        $param = Request()->param();
        [$page, $limit] = $this->getPage();
        $time = strtotime(date('Y-m-d'));
        $userCompanyInfo = Company::where('id', $this->userInfo['company_id'])->find();
        $where = [];
        if ($this->userInfo['admin_id'] != 0) {
            $where[] = ['company_id', '=', $this->userInfo['company_id']];
        }
        if ($userCompanyInfo['company_type'] == 18) {
            $is_captain = User::where('id', $this->userId)->value('is_captain');
            if ($is_captain == 1) {
                $where[] = ['type', 'in', [31,33]];
            }
//            else {
//                $where[] = ['type', '=', 33];
//                $where[] = ['director_uid', '=', $this->userId];
//            }
            $where[] = ['company_id', '=', $this->userInfo['company_id']];
        }

        if ($userCompanyInfo['company_type'] == 41) {
            $where[] = ['director_uid', '=', $this->userId];
//            $where[] = ['company_id', '=', $this->userInfo['company_id']];
        }
        if ($userCompanyInfo['company_type'] == 17) {
            $where[] = ['director_uid', '=', $this->userId];
//            $where[] = ['company_id', '=', $this->userInfo['company_id']];
        }
        if (isset($param['date_time']) && $param['date_time'] != '') {
            $time = strtotime($param['date_time']);
            $param['start_time']=date('Y-m-d H:i:s',$time);
            $end = $time + 86399;
            $param['end_time']=date('Y-m-d H:i:s',$end);
            $where[] = ['start_time', 'between', [$time, $end]];
        } else {
            if(!isset($param['status'])){
                $time = strtotime(date('Y-m-d'));
                $param['start_time']=date('Y-m-d H:i:s',$time);
                $end = $time + 86399;
                $param['end_time']=date('Y-m-d H:i:s',$end);
                $where[] = ['start_time', 'between', [$time, $end]];
            }
        }
        if (isset($param['status']) && $param['status'] > 0) {
            $where[] = ['status', '=', $param['status']];
        }
        $serviceGroupTaskTypeList = DictData::where(['type_value' => 'task_type', 'status' => 1])->column('value', 'id');
        $villageTaskTypeList = DictData::where(['type_value' => 'village_task_type', 'status' => 1])->column('value', 'id');
        $townTaskTypeList = DictData::where(['type_value' => 'town_task_type', 'status' => 1])->column('value', 'id');
        $townMarketingManagerTaskTypeList = DictData::where(['type_value' => 'town_task_type_marketing_director', 'status' => 1])->column('value', 'id');

        $res = Task::where($where)
            ->field(['id', 'title', 'money', 'template_id', 'director_uid', 'company_id',  'start_time', 'end_time', 'director_uid', 'type', 'status', 'content', 'extend'])
            ->page($page, 25)
            ->order(['id' => 'desc', 'status' => 'asc'])
            ->select()->toArray();
        foreach ($res as $k => $item) {
            if (isset($serviceGroupTaskTypeList[$item['type']])) {
                $res[$k]['task_type_value'] = $serviceGroupTaskTypeList[$item['type']];
            }
            if (isset($villageTaskTypeList[$item['type']])) {
                $res[$k]['task_type_value'] = $villageTaskTypeList[$item['type']];
            }
            if (isset($townTaskTypeList[$item['type']])) {
                $res[$k]['task_type_value'] = $townTaskTypeList[$item['type']];
            }
            if (isset($townMarketingManagerTaskTypeList[$item['type']])) {
                $res[$k]['task_type_value'] = $townMarketingManagerTaskTypeList[$item['type']];
            }

            if ($item['type'] == 33) {
                $company = Company::where('id', $item['company_id'])->field('id,deposit,company_money,user_id,day_count,company_type,province,city,area,street,village,brigade,responsible_area')->find(); // 可能要判断预存金是否满足
                $find = App(RemoteController::class)->shang_date_total_price($company,$param,$item['template_id']);
                if ($find != false) {
                    if($time<time()){
                        $transaction_pool=TaskTemplate::where('id',$item['template_id'])->value('transaction_pool');
                        $res[$k]['extend']['transaction'] = $find;
                        if($transaction_pool==0){
                            $res[$k]['extend']['transaction']['arr']['transaction_pool']=$find['arr']['total_price'];
                        }else{
                            $res[$k]['extend']['transaction']['arr']['transaction_pool']=bcadd($res[$k]['extend']['transaction']['arr']['total_price'],$transaction_pool,2);
                        }
                    }
                    // Task::where('id',$item['id'])->update(['extend'=>json_encode(['transaction'=>$find],true)]);
                } else {
                    $res[$k]['extend']['transaction'] = '';
                }
            }
            if (isset($townTaskTypeList[$item['type']])) {
                if ($townTaskTypeList[$item['type']] == 'town_task_type_1') {
                    // 协助总负责人开展工作任务
                    $groupServiceCompanyCount = 0;     // 已安排任务的小组服务公司总数
                    $notDoneTaskGroupServiceCompanyCount = 0; // 未完成每日任务的小组服务公司总数

                    $townCompany = Company::where(['id' => $item['company_id']])->find();
                    $groupServiceCompanyList = Company::where(['street' => $townCompany['street'], 'company_type' => 18])->select()->toArray();
                    foreach ($groupServiceCompanyList as $groupServiceCompany) {
                        // 小组服务公司是否有对应的每日任务安排
                        $templateList = TaskTemplate::where(['company_id' => $groupServiceCompany['id']])->whereIn('type', [31, 32, 33])->select()->toArray();

                        if(count($templateList) === 3) {
                            $groupServiceCompanyCount += 1;
                            foreach ($templateList as $template) {
                                $task = Task::where(['template_id' => $template['id'], 'status' => 3])->find();
                                if (empty($task)) {
                                    $notDoneTaskGroupServiceCompanyCount += 1;
                                    break;
                                }
                            }
                        }
                    }
                    $res[$k]['extend'] = ['total' => $groupServiceCompanyCount, 'not_done_count' => $notDoneTaskGroupServiceCompanyCount];
                }
                if ($townTaskTypeList[$item['type']] == 'town_task_type_2') {
                    // 拓展小组服务团队工作任务
                    $contractCount = 15; // 小组服务合同总数
                    $doneContractCount = 0; // 已完成小组服务合同数
                    $townCompany = Company::where(['id' => $item['company_id']])->find();
                    $doneContractCount = Contract::where(['party_a' => $townCompany['id'], 'status' => 1, 'contract_type' => 25])->count();
                    $res[$k]['extend'] = ['total' => $contractCount, 'done_count' => $doneContractCount];
                }
            }

            if (isset($townMarketingManagerTaskTypeList[$item['type']])) {
                // 数字农贸宣传、加工业务建设和招商任务 返回给前端当前任务模板进行到哪个阶段
                // 每个阶段不同,前台展示不同的资料上传页面,上传走审批接口
                if ($townMarketingManagerTaskTypeList[$item['type']] == 'town_task_type_marketing_director_10') {
                    $templateInfo = TaskTemplate::where(['id' => $item['template_id']])->find();
                    $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);
                    // 第一阶段
                    if ($dayCount < $stageDayOne) {
                        $res[$k]['stage'] = 1;
                    }
                    // 第二阶段
                    if ($dayCount > $stageDayOne && $dayCount <= $stageDayTwoCount) {
                        $res[$k]['stage'] = 2;
                    }
                    // 第三阶段
                    if ($dayCount > $stageDayTwoCount && $dayCount <= $stageDayThreeCount) {
                        $res[$k]['stage'] = 3;
                    }
                    // 第四阶段
                    if ($dayCount > $stageDayThreeCount) {
                        $res[$k]['stage'] = 4;
                    }
                }
            }

        }

        return $this->success('ok', $res);
    }

    //交易详情
    public function order_detail()
    {
        $parmas = $this->request->param();
        $task=Task::where('id',$parmas['id'])->field('company_id,start_time,end_time,extend,type,template_id')->find();
        if(!$task){
            return $this->fail('任务不存在');
        }
        $task=$task->toArray();
        $transaction_pool=TaskTemplate::where('id',$task['template_id'])->value('transaction_pool');

        $company = Company::where('id', $task['company_id'])->field('id,deposit,company_money,user_id,day_count,company_type,province,city,area,street,village,brigade,responsible_area')->find(); // 可能要判断预存金是否满足
        // $list = App(RemoteController::class)->shang_date_list($company, 1, $parmas);
        $parmas['start_time']=date('Y-m-d',$task['start_time']);
        $parmas['end_time']=$task['end_time'].' 23:59:59';
        $list = App(RemoteController::class)->shang_date_list($company, $parmas);
        $shang_date_total_price = App(RemoteController::class)->shang_date_total_price($company,$parmas,$task['template_id']);
        if ($task != false) {
            $find['list'] = $list;
            if($transaction_pool==0){
                $task['extend']['transaction']['arr']['transaction_pool']=$shang_date_total_price['arr']['total_price'];
            }else{
                $task['extend']['transaction']['arr']['transaction_pool']=bcadd($shang_date_total_price['arr']['total_price'],$transaction_pool,2);
            }
            if($task['start_time']<strtotime(date('Y-m-d'))){
                $task['extend']['transaction']['arr']['is_show']=false;
            }else{
                $task['extend']['transaction']['arr']['is_show']=true;
            }
            $find['extend']=$task['extend'];
            return $this->success('ok', $find);
        }
        return $this->success('ok');
    }

    /**
     * 入股
     */
    public function shareholder(){
        $parmas = $this->request->param();
        $task = TaskLogic::detail($parmas);
        $extend = $task['extend'];
        if (isset($extend['is_commit']) && $extend['is_commit'] == 1) {
            $approve = Approve::where(['task_id' =>$task['id']])->order('id', 'desc')->find();
            $task['approve_status'] = $approve['check_status']; //审核状态
            $task['deny_notes'] = $approve['remark']; // 拒绝原因
        }
        return $this->success('ok', $task);
    }
    /**
     * 三轮车详情
     */
    public function tricycle_detail()
    {
        $parmas = $this->request->param();
        $task = TaskLogic::detail($parmas);
        return $this->success('ok', $task);
    }

    /**
     * 三轮车坐标
     */
    public function add_tricycle_coordinate()
    {
        $parmas = $this->request->param();
        $task = Task::where('id', $parmas['id'])->find()->toArray();
        $VehicleRent = VehicleRent::where('rent_company_id', $this->userInfo['company_id'])->find();
        if(empty($VehicleRent)){
            self::setError('该公司没有三轮车,请先租赁三轮车');
            return false;
        }
//        $object_id=CompanyProperty::where('company_id',$this->userInfo['company_id'])->value('object_id');
//        if(!$object_id){
//            return $this->fail('该公司没有三轮车,请先租赁三轮车');
//        }
        $start_time = date('Y-m-d');
        $time=strtotime($start_time)+86399;
        $end_time=date('Y-m-d H:i:s',$time);
        $datas=[
            'car_id'=>$VehicleRent['car_id'],
            'start_time'=>$start_time.' 00:00:00',
            'end_time'=>$end_time
        ];
        $data['status'] = 2;
        if (isset($parmas['terminus'])) {
            if( $parmas['terminus']['lnglat'][0]==null || $parmas['terminus']['lnglat'][0]<=0){
                return $this->fail('定位不存在');
            }
            $res = App(RemoteController::class)->calculateDistance($task['extend']['terminus']['lnglat'][0],$task['extend']['terminus']['lnglat'][1], $parmas['terminus']['lnglat'][0],  $parmas['terminus']['lnglat'][1]);
            if($res>200){
                return $this->fail('定位坐标大于200米,请重新打卡。'.$res.'米');
            }
            $res_two = App(RemoteController::class)->coordinate($datas, $parmas['terminus']['lnglat'][0],  $parmas['terminus']['lnglat'][1]);
            if($res===false){
                return $this->fail('GPS无轨迹');
            }
            $task['extend']['update']['terminus'] = $parmas['terminus'];
        }
        if (isset($parmas['transfer'])) {
            if( $parmas['transfer']['lnglat'][0]==null || $parmas['transfer']['lnglat'][0]<=0){
                return $this->fail('定位不存在');
            }
            $res = App(RemoteController::class)->calculateDistance($task['extend']['transfer']['lnglat'][0],$task['extend']['transfer']['lnglat'][1], $parmas['transfer']['lnglat'][0],  $parmas['transfer']['lnglat'][1]);
            if($res>200){
                return $this->fail('定位坐标大于200米,请重新打卡。'.$res.'米');
            }
            $res_two = App(RemoteController::class)->coordinate($datas, $parmas['transfer']['lnglat'][0],  $parmas['transfer']['lnglat'][1]);
            if($res===false){
                return $this->fail('GPS无轨迹');
            }
            $task['extend']['update']['transfer'] = $parmas['transfer'];
        }
        if (isset($task['extend']['update']['terminus']) && isset($task['extend']['update']['transfer'])) {
            $data['status'] = 3;
        }
        if($res_two<1000){
            $data['extend'] = json_encode($task['extend']);
            Task::where('id', $parmas['id'])->update($data);
            return $this->success('更新成功');
        }
        return $this->fail('定位坐标大于200米,请重新打卡。'.$res.'米');
    }

    public function informationg_list()
    {
        $parmas = Request()->param();
        $find = Task::where('id', $parmas['id'])->find();
        if ($find['type'] == 31) {
            if (isset($find['extend']['informationg']['ids'])) {
                $ids = $find['extend']['informationg']['ids'];
                $list = UserInformationg::where('id', 'in', $ids)
                    ->field(
                        'id,name,phone,sex,age,update_time,
                area_id,area_id area_name,street_id,street_id street_name,village_id,village_id village_name,brigade_id,brigade_id brigade_name,address'
                    )->select()->toArray();
            } else {
                $list = [];
            }
        } else {
            $list = [];
        }
        return $this->success('ok', $list);
    }

    /**
     * 其他任务详情
     */
    public function other_task_detail(){
        $parmas = $this->request->param();
        $task = TaskLogic::detail($parmas);
        $extend = $task['extend'];
        if (isset($extend['other']) && $extend['other']['is_commit'] == 1) {
            $approve = Approve::where(['task_id' =>$task['id']])->find();
            $task['approve_status'] = $approve['check_status']; //审核状态
            $task['deny_notes'] = $approve['remark']; // 拒绝原因
        }
        return $this->success('ok', $task);
    }

    /**
     * 其他任务 -提交
     */
    public function commit_other_task()
    {
        try {
            $parmas = $this->request->param(); //id note annex vedio_annex
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            if (empty($parmas['annex']) && empty($parmas['video_annex'])) {
                $this->fail('没有上传凭证,无法提交审核');
            }

            $extend = ['other' => ['is_commit' => 1, 'note' => $parmas['note'], 'annex'=>$parmas['annex'], 'video_annex' => $parmas['video_annex']]];
            Db::startTrans();
            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time'=>time(), 'director_uid'=>$this->userId]); // director_uid 指派人

            // 片区经理
            $areaManagerId = User::where(['id' => $this->userId])->with('company')->value('area_manager');

            // 没有则创建审批任务
            $approveModel = Approve::where(['task_id' => $task['id']])->findOrEmpty();
            if ($approveModel->isEmpty()) {
                $approveModel->type = Approve::APPROVE_TYPE_1;
                $approveModel->flow_id = 1;
                $approveModel->name = $task['title'];
                $approveModel->admin_id = 0; // 后台发起人id 暂时为0
                $approveModel->user_id = $this->userId; // 前台发起人用户id
                $approveModel->task_id = $task['id']; // 前台发起人用户id
                $approveModel->department_id = '0';
                $approveModel->check_admin_ids = $areaManagerId; // 当前审批人ID 片区经理的admin_id
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->other_type = 6;
                $approveModel->create_time = time();
                $approveModel->update_time = time();
                $re = $approveModel->save();
            } else {
                // 有则更新状态
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->save();
            }

            Db::commit();
            return $this->success('ok', []);
        } catch (Exception $e) {
            Db::rollback();
            return $this->fail($e->getMessage());
        }

    }

    /**
     * 镇农科公司任务详情
     */
    public function service_task_detail()
    {
        $param = $this->request->param();
        $task = TaskLogic::detail($param);
        $task['template_info'] = TaskTemplate::where(['id' => $task['template_id']])->find();
        return $this->success('成功', $task);
    }

    /**
     * 镇农科公司任务-督促小组服务团队学习任务 -提交
     */
    public function commit_town_task_type4()
    {
        try {
            $parmas = $this->request->param(); //id study_photo sign_in_table study_content
            $extend = ['town_task_type_4' => ['study_photo'=>$parmas['study_photo'], 'sign_in_table'=>$parmas['sign_in_table'], 'study_content'=> $parmas['study_content']]];
            if (count($parmas['study_photo']) >= 5 && !empty($parmas['sign_in_table']) && strlen($parmas['study_content'])>=50) {
                Task::where('id', $parmas['id'])->save(['extend' => json_encode($extend), 'status' => 3]);
            } else {
                Task::where('id', $parmas['id'])->save(['extend' => json_encode($extend)]);
            }
            return $this->success('成功', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 镇农科公司任务-数字农贸宣传、加工业务建设和招商任务
     * 第一阶段 上传 宣传和加工两个业务 的手续办理完成证明
     * 第二阶段 上传 竣工验收单
     * 第三阶段 上传 两个业务体系招商入驻证明
     * 第四阶段 上传完成净利润的证明
     *
     * 将上传文件保存,走任务审批流程
     */
    public function commit_town_task_type_marketing_director_10()
    {
        try {
            $parmas = $this->request->param(); //id stage  stage_1第一阶段完成证明 stage_2 stage_3 stage_4
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            $extend = [];
            $stage = $parmas['stage']; // 当前做的是任务第几阶段
            if ($stage == 1) {
                $extend['stage1'] = $parmas['stage1'];
                $parmas['stage1']['is_commit'] = 1;
            }
            if ($stage == 2) {
                $extend['stage2'] = $parmas['stage2'];
                $extend['stage2']['is_commit'] = 1;
            }
            if ($stage == 3) {
                $extend['stage3'] = $parmas['stage3'];
                $extend['stage3']['is_commit'] = 1;
            }
            if ($stage == 4) {
                $extend['stage4'] = $parmas['stage4'];
                $extend['stage4']['is_commit'] = 1;
            }
            $extend['stage'] = $stage;
            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time'=>time(), 'director_uid'=>$this->userId]); // director_uid 指派人

            // 片区经理
            $areaManagerId = User::where(['id' => $this->userId])->with('company')->value('area_manager');


            // 创建审批任务
            $approveModel = new Approve();
            $approveModel->type = Approve::APPROVE_TYPE_4;
            $approveModel->flow_id = 1;
            $approveModel->name = $task['title'];
            $approveModel->admin_id = 0; // 后台发起人id 暂时为0
            $approveModel->user_id = $this->userId; // 前台发起人用户id
            $approveModel->task_id = $task['id']; // 任务id
            $approveModel->department_id = '0';
            $approveModel->check_admin_ids = $areaManagerId; // 当前审批人ID 片区经理的admin_id
            $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
            $approveModel->other_type = 6;
            $approveModel->extend = json_encode($extend);
            $approveModel->create_time = time();
            $approveModel->update_time = time();
            $re = $approveModel->save();
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function town_task_type_marketing_director_10_detail()
    {
        $parmas = $this->request->param();
        $task = TaskLogic::detail($parmas);
        $approve = Approve::where(['task_id' =>$task['id']])->order('id', 'desc')->find();
        if ($approve) {
            $task['approve_status'] = $approve['check_status']; //审核状态
            $task['deny_notes'] = $approve['remark']; // 拒绝原因
            $task['approve_extend'] = $approve['extend']; // 审批扩展信息
        }
        return $this->success('ok', $task);
    }

    public function commit_village_task_type_6()
    {
        try {
            $parmas = $this->request->param(); //id annex video_annex
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            if (empty($parmas['annex']) && empty($parmas['video_annex'])) {
                $this->fail('没有上传凭证,无法提交审核');
            }

            $extend = [
                'other'=> [
                    'is_commit' => 1,
                    'note' => $parmas['note'],
                    'annex' => $parmas['annex'],
                    'video_annex' => $parmas['video_annex'],
                ]
            ];
            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time'=>time(), 'director_uid'=>$this->userId]); // director_uid 指派人

            // 片区经理
            $areaManagerId = User::where(['id' => $this->userId])->with('company')->value('area_manager');


            // 没有则创建审批任务
            $approveModel = Approve::where(['task_id' => $task['id']])->findOrEmpty();
            if ($approveModel->isEmpty()) {
                $approveModel->type = Approve::APPROVE_TYPE_5;
                $approveModel->flow_id = 1;
                $approveModel->name = $task['title'];
                $approveModel->admin_id = 0; // 后台发起人id 暂时为0
                $approveModel->user_id = $this->userId; // 前台发起人用户id
                $approveModel->task_id = $task['id']; // 任务id
                $approveModel->department_id = '0';
                $approveModel->check_admin_ids = $areaManagerId; // 当前审批人ID 片区经理的admin_id
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->other_type = 6;
                $approveModel->extend = json_encode($extend);
                $approveModel->create_time = time();
                $approveModel->update_time = time();
                $re = $approveModel->save();
            } else {
                // 有则更新状态
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->save();
            }
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function commit_village_task_type_8()
    {
        try {
            $parmas = $this->request->param(); // id annex video_annex
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            if (empty($parmas['annex']) && empty($parmas['video_annex'])) {
                $this->fail('没有上传凭证,无法提交审核');
            }

            $extend = [
                'other'=> [
                    'is_commit' => 1,
                    'note' => $parmas['note'],
                    'annex' => $parmas['annex'],
                    'video_annex' => $parmas['video_annex'],
                ]
            ];
            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time'=>time(), 'director_uid'=>$this->userId]); // director_uid 指派人

            // 片区经理
            $areaManagerId = User::where(['id' => $this->userId])->with('company')->value('area_manager');


            // 没有则创建审批任务
            $approveModel = Approve::where(['task_id' => $task['id']])->findOrEmpty();
            if ($approveModel->isEmpty()) {
                $approveModel->type = Approve::APPROVE_TYPE_6;
                $approveModel->flow_id = 1;
                $approveModel->name = $task['title'];
                $approveModel->admin_id = 0; // 后台发起人id 暂时为0
                $approveModel->user_id = $this->userId; // 前台发起人用户id
                $approveModel->task_id = $task['id']; // 任务id
                $approveModel->department_id = '0';
                $approveModel->check_admin_ids = $areaManagerId; // 当前审批人ID 片区经理的admin_id
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->other_type = 6;
                $approveModel->extend = json_encode($extend);
                $approveModel->create_time = time();
                $approveModel->update_time = time();
                $re = $approveModel->save();
            } else {
                // 有则更新状态
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->save();
            }
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     *  提前完成,截止提交时间,前面的钱一次性结算,往后至任务结束每天发放
     */
    public function commit_town_master_task_type_2()
    {
        try {
            $parmas = $this->request->param(); // id annex video_annex
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            if (empty($parmas['annex']) && empty($parmas['video_annex'])) {
                $this->fail('没有上传凭证,无法提交审核');
            }

            $extend = [
                'other'=> [
                    'is_commit' => 1,
                    'note' => $parmas['note'],
                    'annex' => $parmas['annex'],
                    'video_annex' => $parmas['video_annex'],
                ]
            ];
            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time'=>time(), 'director_uid'=>$this->userId]); // director_uid 指派人

            // 片区经理
            $areaManagerId = User::where(['id' => $this->userId])->with('company')->value('area_manager');


            // 查询是否 已有审批通过的
            $approveModel = Approve::where(['business_id' => $task['template_id'], 'check_status' => 2])->findOrEmpty();
            if ($approveModel->isEmpty()) {
                $approveModel->type = Approve::APPROVE_TYPE_7;
                $approveModel->flow_id = 1;
                $approveModel->name = $task['title'];
                $approveModel->admin_id = 0; // 后台发起人id 暂时为0
                $approveModel->user_id = $this->userId; // 前台发起人用户id
                $approveModel->task_id = $task['id']; // 任务id
                $approveModel->business_id = $task['template_id']; // 关联模板id,结算时用于判断这个任务是否提前完成
                $approveModel->department_id = '0';
                $approveModel->check_admin_ids = $areaManagerId; // 当前审批人ID 片区经理的admin_id
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->other_type = 6;
                $approveModel->create_time = time();
                $approveModel->update_time = time();
                $re = $approveModel->save();
            } else {
                // 有则更新状态
                return $this->fail('该任务已完成,请勿重复提交');
            }
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 提交 镇农科负责人-信息收集
     * 将信息收集存入task_template表中
     */
    publiC function commit_town_master_task_type_3()
    {
        $param = $this->request->param();
        $task = Task::where(['id'=>$param['id']])->find();
        $taskTemplate = TaskTemplate::where(['id'=>$task['template_id']])->find();
        $extend = $taskTemplate['extend'];
        $extend['purchase_sales_info'][] = $param['purchase_sales_info'];
        $taskTemplate->save(['extend'=>json_encode($extend)]);
        return $this->success('成功', []);
    }

    /**
     * 提交 镇农科负责人-政策补贴申请
     * 上传凭证,后台审批,填写实际完成金额
     */
    publiC function commit_town_master_task_type_7()
    {
        try {
            $parmas = $this->request->param(); // id annex video_annex
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            if (empty($parmas['annex']) && empty($parmas['video_annex'])) {
                $this->fail('没有上传凭证,无法提交审核');
            }

            $extend = [
                'other'=> [
                    'is_commit' => 1,
                    'note' => $parmas['note'],
                    'annex' => $parmas['annex'],
                    'video_annex' => $parmas['video_annex'],
                ]
            ];
            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time'=>time(), 'director_uid'=>$this->userId]); // director_uid 指派人

            // 片区经理
            $areaManagerId = User::where(['id' => $this->userId])->with('company')->value('area_manager');


            // 没有则创建审批任务
            $approveModel = Approve::where(['task_id' => $task['id']])->findOrEmpty();
            if ($approveModel->isEmpty()) {
                $approveModel->type = Approve::APPROVE_TYPE_6;
                $approveModel->flow_id = 1;
                $approveModel->name = $task['title'];
                $approveModel->admin_id = 0; // 后台发起人id 暂时为0
                $approveModel->user_id = $this->userId; // 前台发起人用户id
                $approveModel->task_id = $task['id']; // 任务id
                $approveModel->department_id = '0';
                $approveModel->check_admin_ids = $areaManagerId; // 当前审批人ID 片区经理的admin_id
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->other_type = 6;
                $approveModel->extend = json_encode($extend);
                $approveModel->create_time = time();
                $approveModel->update_time = time();
                $re = $approveModel->save();
            } else {
                // 有则更新状态
                $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
                $approveModel->save();
            }
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    // 小组服务团队-入股任务提交

    public function commit_service_group_task()
    {
        try {
            $parmas = $this->request->param(); // id  annex amount
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            $extend = $task['extend'];
            $extend['is_commit'] = 1;
            $extend['annex'] = $parmas['annex'];
            $extend['file_type'] = $parmas['file_type'];
            $extend['amount'] = $parmas['amount'];

            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time' => time(), 'director_uid' => $this->userId]); // director_uid 指派人

            // 创建审批任务
            $approveModel = new Approve();
            $approveModel->type = Approve::APPROVE_TYPE_10;
            $approveModel->flow_id = 1;
            $approveModel->name = $task['title'];
            $approveModel->admin_id = 0; // 后台发起人id 暂时为0
            $approveModel->user_id = $this->userId; // 前台发起人用户id
            $approveModel->task_id = $task['id']; // 任务id
            $approveModel->department_id = $this->userInfo['company_id']; // 公司id
            $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
            $approveModel->other_type = 6;
            $approveModel->amount = $parmas['amount']; // 入股金额
            $approveModel->extend = json_encode($extend);
            $approveModel->create_time = time();
            $approveModel->update_time = time();
            $re = $approveModel->save();
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    // 村联络员-督促小组服务团队入股任务提交
    public function commit_village_task_4()
    {
        try {
            $parmas = $this->request->param(); // id  annex amount
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            $extend = $task['extend'];
            $extend['is_commit'] = 1;
            $extend['annex'] = $parmas['annex'];
            $extend['file_type'] = $parmas['file_type'];
            $extend['amount'] = $parmas['amount'];

            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time' => time(), 'director_uid' => $this->userId]); // director_uid 指派人

            // 创建审批任务
            $approveModel = new Approve();
            $approveModel->type = Approve::APPROVE_TYPE_11;
            $approveModel->flow_id = 1;
            $approveModel->name = $task['title'];
            $approveModel->admin_id = 0; // 后台发起人id 暂时为0
            $approveModel->user_id = $this->userId; // 前台发起人用户id
            $approveModel->task_id = $task['id']; // 任务id
            $approveModel->department_id = $this->userInfo['company_id']; // 公司id
            $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
            $approveModel->other_type = 6;
            $approveModel->amount = $parmas['amount']; // 入股金额
            $approveModel->extend = json_encode($extend);
            $approveModel->create_time = time();
            $approveModel->update_time = time();
            $re = $approveModel->save();
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    // 村联络员-入股甲方公司任务提交
    public function commit_village_task_5()
    {
        try {
            $parmas = $this->request->param(); // id  annex amount
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            $extend = $task['extend'];
            $extend['is_commit'] = 1;
            $extend['annex'] = $parmas['annex'];
            $extend['file_type'] = $parmas['file_type'];
            $extend['amount'] = $parmas['amount'];

            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time' => time(), 'director_uid' => $this->userId]); // director_uid 指派人

            // 创建审批任务
            $approveModel = new Approve();
            $approveModel->type = Approve::APPROVE_TYPE_12;
            $approveModel->flow_id = 1;
            $approveModel->name = $task['title'];
            $approveModel->admin_id = 0; // 后台发起人id 暂时为0
            $approveModel->user_id = $this->userId; // 前台发起人用户id
            $approveModel->task_id = $task['id']; // 任务id
            $approveModel->department_id = $this->userInfo['company_id']; // 公司id
            $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
            $approveModel->other_type = 6;
            $approveModel->amount = $parmas['amount']; // 入股金额
            $approveModel->extend = json_encode($extend);
            $approveModel->create_time = time();
            $approveModel->update_time = time();
            $re = $approveModel->save();
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    // 镇农科服务部长-督促小组服务团队入股村管理公司
    public function commit_town_service_manager_task_6()
    {
        try {
            $parmas = $this->request->param(); // id  annex amount
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            $extend = $task['extend'];
            $extend['is_commit'] = 1;
            $extend['annex'] = $parmas['annex'];
            $extend['file_type'] = $parmas['file_type'];
            $extend['amount'] = $parmas['amount'];

            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time' => time(), 'director_uid' => $this->userId]); // director_uid 指派人

            // 创建审批任务
            $approveModel = new Approve();
            $approveModel->type = Approve::APPROVE_TYPE_13;
            $approveModel->flow_id = 1;
            $approveModel->name = $task['title'];
            $approveModel->admin_id = 0; // 后台发起人id 暂时为0
            $approveModel->user_id = $this->userId; // 前台发起人用户id
            $approveModel->task_id = $task['id']; // 任务id
            $approveModel->department_id = $this->userInfo['company_id']; // 公司id
            $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
            $approveModel->other_type = 6;
            $approveModel->amount = $parmas['amount']; // 入股金额
            $approveModel->extend = json_encode($extend);
            $approveModel->create_time = time();
            $approveModel->update_time = time();
            $re = $approveModel->save();
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    // 镇农科负责人-促成村联络员入股甲方
    public function commit_town_master_task_6()
    {
        try {
            $parmas = $this->request->param(); // id  annex amount
            $task = TaskLogic::detail($parmas);
            if (empty($task)) {
                $this->fail('任务不存在');
            }
            $extend = $task['extend'];
            $extend['is_commit'] = 1;
            $extend['annex'] = $parmas['annex'];
            $extend['file_type'] = $parmas['file_type'];
            $extend['amount'] = $parmas['amount'];

            Task::where(['id' => $parmas['id']])->update(['extend' => json_encode($extend), 'update_time' => time(), 'director_uid' => $this->userId]); // director_uid 指派人

            // 创建审批任务
            $approveModel = new Approve();
            $approveModel->type = Approve::APPROVE_TYPE_14;
            $approveModel->flow_id = 1;
            $approveModel->name = $task['title'];
            $approveModel->admin_id = 0; // 后台发起人id 暂时为0
            $approveModel->user_id = $this->userId; // 前台发起人用户id
            $approveModel->task_id = $task['id']; // 任务id
            $approveModel->department_id = $this->userInfo['company_id']; // 公司id
            $approveModel->check_status = 1; // 状态 0待审核,1审核中,2审核通过,3审核不通过,4撤销审核
            $approveModel->other_type = 6;
            $approveModel->amount = $parmas['amount']; // 入股金额
            $approveModel->extend = json_encode($extend);
            $approveModel->create_time = time();
            $approveModel->update_time = time();
            $re = $approveModel->save();
            return $this->success('ok', []);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

}