<?php
namespace app\common\model;

use think\Db;
use think\Exception;

class HouseLock extends Base
{
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    public $table = 'house_lock';
    protected $validateName = 'HouseLock';



    public function getStartTime($userId){
        $info = $this
            ->where('user_id',$userId)
            ->order('end','desc')
            ->find();
        if(!$info){
            $info = Db::name('house_pay')
                ->where('create_user_id',$userId)
                ->where('status','in',[1,2])
                ->order('pay_time','asc')
                ->find();
            if($info){
                return $info['pay_time'];
            }
        }else{
            return $info['end'];
        }
        return '';
    }
    public function getDataInfo($start,$end,$userId,$orgId){
        // 检查是否有返销的数据
        $ret = Db::name('house_pay')
            ->where('create_user_id',$userId)
            ->where('org_id',$orgId)
            ->where('status',2)
            ->where('del',0)
            ->where('pay_time','between',[$start,$end])
            ->find();
        if($ret){
            $this->error = '存在返销中的数据';
            return false;
        }

        $lists = Db::name('house_pay')
            ->alias('hp')
            ->join('owner o','o.id = hp.owner_id')
            ->join('user u','u.id = hp.create_user_id')
            ->where('hp.create_user_id',$userId)
            ->where('hp.status',1)
            ->where('hp.del',0)
            ->where('hp.pay_time','between',[$start,$end])
            ->field('hp.*,o.name,u.real_name')
            ->select();
        if(!$lists){
            $this->error = '该时间段内没有收费记录';
            return false;
        }
        $mData = [
            'money' => 0,
            'pre_money' => 0,
            'true_money' => 0,
            'pay_money1' => 0,
            'pay_money3' => 0,
            'pay_money4' => 0,
            'pay_money5' => 0,
        ];
        $payIds = [];
        foreach ($lists as $k=>$v){
            $payIds[] = $v['id'];
            $mData['money'] += $v['money'];
            $mData['pre_money'] += $v['pre_money'];
            $mData['true_money'] += $v['true_money'];

            if($v['pay_type'] == 1){ //1=现金  3=支付宝 4=银行托收 5=微信 6=组合付款
                $mData['pay_money1'] += $v['true_money'];
            }else if($v['pay_type'] == 3){
                $mData['pay_money3'] += $v['true_money'];
            }else if($v['pay_type'] == 4){
                $mData['pay_money4'] += $v['true_money'];
            }else if($v['pay_type'] == 5){
                $mData['pay_money5'] += $v['true_money'];
            }else{
                $payData = json_decode($v['pay_data'],true);
                foreach ($payData as $kk=>$vv){
                    if($kk == 1){
                        $mData['pay_money1'] += $vv;
                    }else if($kk == 3){
                        $mData['pay_money3'] += $vv;
                    }else if($kk == 4){
                        $mData['pay_money4'] += $vv;
                    }else if($kk == 5){
                        $mData['pay_money5'] += $vv;
                    }
                }
            }
        }

        $logs = Db::name('house_pay_log_view')
            ->where('pay_id','in',$payIds)
            ->select();

        $feeIds = [];
        $fees = [];
        foreach ($logs as $k=>$v){
            if(!in_array($v['fee_id'],$feeIds)){
                $feeIds[] = $v['fee_id'];
                $fees[] = [
                    'fee_id' => $v['fee_id'],
                    'fee_title' => $v['fee_title'],
                    'money' => 0
                ];
            }
        }
        foreach ($fees as $k=>$v){
            foreach ($logs as $kk=>$vv){
                if($v['fee_id'] == $vv['fee_id']){
                    $fees[$k]['money'] += $vv['money'];
                }
            }
        }

        $data = [
            'list' => $lists,
            'data' => $mData,
            'logs' => $logs,
            'fees' => $fees
        ];
        return $data;
    }

    public function addSave($start,$end,$remark,$userId,$orgId){
        $gStart = $this->getstarttime($userId);
        if($start != $gStart){
            $this->error = '开始时间不正确';
            return false;
        }
        $data = $this->getDataInfo($start,$end,$userId,$orgId);
        if(!$data){
            return false;
        }

        $post = $data['data'];

        $this->startTrans();
        try{
            $sData = [
                'org_id' => $orgId,
                'user_id' => $userId,
                'status' => 0,
                'start' => $start?$start:null,
                'end' => $end?$end:null,
                'money' => $post['money'],
                'pre_money' => $post['pre_money'],
                'true_money' => $post['true_money'],
                'pay_money1' => $post['pay_money1'],
                'pay_money3' => $post['pay_money3'],
                'pay_money4' => $post['pay_money4'],
                'pay_money5' => $post['pay_money5'],
                'create_time' => getTime(),
                'remark' => $remark
            ];

            $lid = $this->insertGetId($sData);
            if (!$lid) {
               exception('操作失败');
            }
            foreach ($data['list'] as $k=>$v){
                $res = Db::name('house_lock_pay')
                    ->insert([
                    'house_lock_id' => $lid,
                    'pay_id' => $v['id']
                ]);
                if (!$res) {
                     exception('操作失败');
                }
            }

            foreach ($data['fees'] as $k=>$v){
                $res = Db::name('house_lock_fee')
                    ->insert([
                    'house_lock_id' => $lid,
                    'fee_id' => $v['fee_id'],
                    'money' => $v['money']
                ]);
                if (!$res) {
                   exception('操作失败');
                }
            }

            $this->commit();
            return true;
        }catch (Exception $e){
            $this->error = $e->getmessage();
            $this->rollback();
            return false;
        }
    }
    public function deal($id,$status,$userId){
        $info = $this->where('id',$id)->find();
        if(!$info){
            $this->error = '记录不存在';
            return false;
        }
        $info = json_decode(json_encode($info),true);
        if($info['status'] != 0){
            $this->error = '无权限操作';
            return false;
        }
        $res = $this->where('id',$id)->update([
            'status' => $status,
            'deal_user_id' => $userId,
            'update_time' => getTime()
        ]);
        if (!$res) {
            $this->error = '操作失败';
            return false;
        }
        return true;
    }
    public function getDataById($id){
        $info = $this->where('id',$id)->find();
        if(!$info){
            $this->error = '记录不存在';
            return false;
        }

        $lists = Db::name('house_lock_pay')
            ->alias('hlp')
            ->join('house_pay hp','hp.id = hlp.pay_id')
            ->join('owner o','o.id = hp.owner_id')
            ->join('user u','u.id = hp.create_user_id')
            ->where('hlp.house_lock_id',$id)
            ->field('hp.*,o.name,u.real_name')
            ->select();
        $lists = $lists?$lists:[];
        $payIds = [];
        foreach ($lists as $k=>$v){
            $payIds[] = $v['id'];
        }

        $logs = Db::name('house_pay_log_view')
            ->where('pay_id','in',$payIds)
            ->select();

        $fees =Db::name('house_lock_fee')
            ->alias('hlf')
            ->join('house_fee hf','hf.id = hlf.fee_id')
            ->where('hlf.house_lock_id',$id)
            ->field('hlf.*,hf.title as fee_title')
            ->select();

        $data = [
            'list' => $lists,
            'data' => json_decode(json_encode($info),true),
            'logs' => $logs?$logs:[],
            'fees' => $fees?$fees:[]
        ];
        return $data;
    }

}