<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\ApiController;
use app\api\middleware\Auth;
use app\finance\model\Invoice as InvoiceList;
use app\finance\model\InvoiceIncome;
use app\finance\validate\InvoiceCheck;
use think\exception\ValidateException;
use think\facade\Db;

class FinanceInvoice extends ApiController
{

	protected $middleware = [
    	Auth::class => ['except' => []]
    ];

	//我申请的发票
    public function index()
    {
		$this->checkAuth();
        $param = get_params();
        $this->uid = JWT_UID;
		$where = [];
		if (!empty($param['check_status'])) {
			$where[] = ['i.check_status','=',$param['check_status']];
		}
		//按时间检索
		if (!empty($param['diff_time'])) {
			$diff_time =explode('~', $param['diff_time']);
			$where[] = ['i.create_time', 'between', [strtotime(urldecode($diff_time[0])),strtotime(urldecode($diff_time[1]))]];
		}		
		$where[] = ['i.admin_id','=',$this->uid];
		$where[] = ['i.delete_time','=',0];
		$model = new InvoiceList();
		$list = $model->get_list($param, $where);
		$this->apiSuccess('获取成功', $list);
    }
	
	//待审批的发票
    public function list()
    {
		$this->checkAuth();
        $param = get_params();
        $this->uid = JWT_UID;
		$status = isset($param['status'])?$param['status']:0;
		$user_id = $this->uid;
		//查询条件
		$map1 = [];
		$map2 = [];
		$map1[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',i.check_admin_ids)")];
		$map1[] = ['i.delete_time','=',0];
		$map2[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',i.flow_admin_ids)")];
		$map2[] = ['i.delete_time','=',0];
		$model = new InvoiceList();
		if($status == 0){
			$list = $model->get_list($param,[$map1,$map2],'or');
		}			
		if($status == 1){
			$list = $model->get_list($param,$map1);
		}
		if($status == 2){
			$list = $model->get_list($param,$map2);
		}	
		$this->apiSuccess('获取成功', $list);
    }
	
	public function copy()
    {
		$this->checkAuth();
        $param = get_params();
        $user_id = JWT_UID;
		//查询条件
		$map = [];
		//按时间检索
		if (!empty($param['diff_time'])) {
			$diff_time =explode('~', $param['diff_time']);
			$map[] = ['i.create_time', 'between', [strtotime(urldecode($diff_time[0])),strtotime(urldecode($diff_time[1]))]];
		}
		$map[] = ['i.delete_time','=',0];
		$map[] = ['i.check_status', '=', 2];			
		$map[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',i.copy_uids)")];
		$model = new InvoiceList();
		$list = $model->get_list($param,$map);	
		$this->apiSuccess('获取成功', $list);
    }
	
	//发票开具
	public function checkedlist()
    {
        $this->checkAuth();
        $param = get_params();
		$this->uid = JWT_UID;
		$auth = isAuthInvoice($this->uid);
		if($auth == 0){
			$this->apiError('你没有权限,请联系管理员或者HR', [], 2);
		}
		$param = get_params();
		$where = [];
		if (!empty($param['check_status'])) {
			$where[] = ['i.check_status','=',$param['check_status']];
		}
		else{
			$where[] = ['i.check_status','in',[2,5,10]];
		}
		//按时间检索
		if (!empty($param['diff_time'])) {
			$diff_time =explode('~', $param['diff_time']);
			$where[] = ['i.create_time', 'between', [strtotime(urldecode($diff_time[0])),strtotime(urldecode($diff_time[1]))]];
		}			
		$where[] = ['i.delete_time','=',0];
		$model = new InvoiceList();
		$list = $model->get_list($param,$where);
		$this->apiSuccess('获取成功', $list);
    }

	//获取开票流程
	public function get_invoice_flow()
	{
		$this->uid = JWT_UID;
		$loginAdmin = Db::name('Admin')->where(['id' => $this->uid])->find();
        $this->did = $loginAdmin['did'];
		$department = $this->did;
		$flows = get_type_department_flows(7,$department);
		$this->apiSuccess('获取成功', $flows);
	}

    //添加&编辑
    public function add()
    {
		$this->checkAuth();
        $this->uid = JWT_UID;
        $param = get_params();
		$admin_id = $this->uid;     
		$loginAdmin = Db::name('Admin')->where(['id' => $this->uid])->find();
        $this->did = $loginAdmin['did'];
		if (empty($param['flow_id'])) {
            $this->apiError("审批流程id不能为空");
        }
		if (empty($param['type'])) {
            $this->apiError("抬头类型不能为空");
        }
		if (empty($param['invoice_title'])) {
            $this->apiError("开票抬头不能为空");
        }
		$param['check_status'] = 1;
		$param['check_step_sort'] = 0;
		$flow_list = Db::name('Flow')->where('id',$param['flow_id'])->value('flow_list');
		$flow = unserialize($flow_list);
		if ($param['type'] == 1) {
			if (empty($param['invoice_tax'])) {
				$this->apiError("纳税人识别号不能为空");
			}
			if (empty($param['invoice_bank'])) {
				$this->apiError("开户银行不能为空");
			}
			if (empty($param['invoice_account'])) {
				$this->apiError("银行账号不能为空");
			}
			if (empty($param['invoice_banking'])) {
				$this->apiError("银行营业网点不能为空");
			}
			if (empty($param['invoice_address'])) {
				$this->apiError("银行地址不能为空");
			}
		}
		if (!isset($param['check_admin_ids'])) {
			foreach($flow as $item) {
				// 当前部门负责人
				if ($item['flow_type'] == 1) {
					$manager = get_department_manager($this->uid);
					if (empty($manager)) {
						$this->apiError('当前部门负责人不存在');
					}
				}
				// 上级部门负责人
				if ($item['flow_type'] == 2) {
					$manager = get_department_manager($this->uid, 1);
					if (empty($manager)) {
						$this->apiError('上级部门负责人不存在');
					}
				}
				// 当前部门分管领导
				if ($item['flow_type'] == 5) {
					$leader = get_department_leader($this->uid);
					if (empty($leader)) {
						$this->apiError('当前部门分管领导不存在');
					}
				}
				// 上级部门分管领导	
				if ($item['flow_type'] == 6) {
					$leader = get_department_leader($this->uid, 1);
					if (empty($leader)) {
						$this->apiError('上级部门分管领导不存在');
					}
				}
			}
		}
		if (!empty($param['id']) && $param['id'] > 0) {
			try {
				validate(InvoiceCheck::class)->scene('edit')->check($param);
			} catch (ValidateException $e) {
				$this->apiError($e->getError());
			}
			$param['update_time'] = time();
			
			//删除原来的审核流程和审核记录
			Db::name('FlowStep')->where(['action_id'=>$param['id'],'type'=>3,'delete_time'=>0])->update(['delete_time'=>time()]);
			Db::name('FlowRecord')->where(['action_id'=>$param['id'],'type'=>3,'delete_time'=>0])->update(['delete_time'=>time()]);		
			if (!isset($param['check_admin_ids'])) {
				if($flow[0]['flow_type'] == 1){
					// 部门负责人
					$manager = get_department_manager($this->uid);
					$param['check_admin_ids'] = $manager;						
				}
				else if($flow[0]['flow_type'] == 2){
					// 上级部门负责人
					$manager = get_department_manager($this->uid, 1);
					$param['check_admin_ids'] = $manager;
				}
				else if($flow[0]['flow_type'] == 5){
					// 部门分管领导
					$leader = get_department_leader($this->uid);
					$param['check_admin_ids'] = $leader;
				}
				else if($flow[0]['flow_type'] == 6){
					// 上级部门分管领导	
					$leader = get_department_leader($this->uid, 1);
					$param['check_admin_ids'] = $leader;
				}
				else{
					$param['check_admin_ids'] = $flow[0]['flow_uids'];
				}
				foreach ($flow as $key => &$value){
					$value['action_id'] = $param['id'];
					$value['sort'] = $key;
					$value['type'] = 3;
					$value['create_time'] = time();
				}
				//增加审核流程
				Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
			}
			else{
				$flow_step = array(
					'action_id' => $param['id'],
					'type' => 3,
					'flow_uids' => $param['check_admin_ids'],
					'create_time' => time()
				);
				//增加审核流程
				Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
			}
			
			$res = InvoiceList::where('id', $param['id'])->strict(false)->field(true)->update($param);
			if ($res !== false) {
				//添加提交申请记录
				$checkData=array(
					'action_id' => $param['id'],
					'check_user_id' => $this->uid,
					'content' => '重新提交申请',
					'type' => 3,
					'check_time' => time(),
					'create_time' => time()
				);	
				$record_id = Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
				add_log('edit', $param['id'], $param);
				//发送消息通知
				$msg=[
					'from_uid'=>$this->uid,
					'title'=>'发票',
					'action_id'=>$param['id']
				];
				$users = $param['check_admin_ids'];
				sendMessage($users,41,$msg);
				$this->apiSuccess('操作成功');   
			} else {
				$this->apiError('操作失败');
			}
		} else {
			try {
				validate(InvoiceCheck::class)->scene('add')->check($param);
			} catch (ValidateException $e) {
				$this->apiError($e->getError());
			}
			$param['admin_id'] = $this->uid;
			$param['did'] = $this->did;
			$param['create_time'] = time();
			
			if (!isset($param['check_admin_ids'])) {
				if($flow[0]['flow_type'] == 1){
					// 部门负责人
					$manager = get_department_manager($this->uid);
					$param['check_admin_ids'] = $manager;						
				}
				else if($flow[0]['flow_type'] == 2){
					// 上级部门负责人
					$manager = get_department_manager($this->uid, 1);
					$param['check_admin_ids'] = $manager;
				}
				else if($flow[0]['flow_type'] == 5){
					// 部门分管领导
					$leader = get_department_leader($this->uid);
					$param['check_admin_ids'] = $leader;
				}
				else if($flow[0]['flow_type'] == 6){
					// 上级部门分管领导	
					$leader = get_department_leader($this->uid, 1);
					$param['check_admin_ids'] = $leader;
				}
				else{
					$param['check_admin_ids'] = $flow[0]['flow_uids'];
				}
				$exid = InvoiceList::strict(false)->field(true)->insertGetId($param);
				foreach ($flow as $key => &$value){
					$value['action_id'] = $exid;
					$value['sort'] = $key;
					$value['type'] = 3;
					$value['create_time'] = time();
				}
				//增加审核流程
				Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
			}
			else{
				$exid = InvoiceList::strict(false)->field(true)->insertGetId($param);
				$flow_step = array(
					'action_id' => $exid,
					'type' => 3,
					'flow_uids' => $param['check_admin_ids'],
					'create_time' => time()
				);
				//增加审核流程
				Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
			}				
			
			if ($exid) {
				//添加提交申请记录
				$checkData=array(
					'action_id' => $exid,
					'check_user_id' => $this->uid,
					'content' => '提交申请',
					'type' => 3,
					'check_time' => time(),
					'create_time' => time()
				);	
				$record_id = Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
				add_log('apply', $exid, $param);
				//发送消息通知
				$msg=[
					'from_uid'=>$this->uid,
					'title'=>'发票',
					'action_id'=>$exid
				];
				$users = $param['check_admin_ids'];
				sendMessage($users,41,$msg);
				$this->apiSuccess('操作成功');   
			} else {
				$this->apiError('操作失败');
			}
		}
    }

    //查看
    public function view()
    {
		$this->checkAuth();
        $this->uid = JWT_UID;
        $id = empty(get_params('id')) ? 0 : get_params('id');
		$model = new InvoiceList();
		$detail = $model->detail($id);
		if(empty($detail)){
			$this->apiError('申请开票不存在');
		}
		$flows = Db::name('FlowStep')->where(['action_id'=>$detail['id'],'type'=>3,'sort'=>$detail['check_step_sort'],'delete_time'=>0])->find();
		$detail['check_user'] = '-';
		$detail['copy_user'] = '-';
		$check_user_ids = [];
		if($detail['check_status'] == 1){
			if($flows['flow_type']==1){
				$detail['check_user'] = '部门负责人';				
				$check_user_ids[]=get_department_manager($detail['admin_id']);
			}
			else if($flows['flow_type']==2){
				$detail['check_user'] = '上级部门负责人';
				$check_user_ids[]=get_department_manager($detail['admin_id'],1);
			}
			else if($flows['flow_type']==5){
				$detail['check_user'] = '部门分管领导';				
				$check_user_ids[]=get_department_leader($detail['admin_id']);
			}
			else if($flows['flow_type']==6){
				$detail['check_user'] = '上级部门分管领导';
				$check_user_ids[]=get_department_leader($detail['admin_id'],1);
			}
			else{
				$check_user_ids = explode(',',$flows['flow_uids']);
				$check_user = Db::name('Admin')->where('id','in',$flows['flow_uids'])->column('name');
				$detail['check_user'] = implode(',',$check_user);			
			}
		}
		
		if($detail['copy_uids'] !=''){
			$copy_user = Db::name('Admin')->where('id','in',$detail['copy_uids'])->column('name');
			$detail['copy_user'] = implode(',',$copy_user);
		}
		if($detail['file_ids'] !=''){
			$fileArray = Db::name('File')->where('id','in',$detail['file_ids'])->select();
			$detail['fileArray'] = $fileArray;
		}
		
		if($detail['other_file_ids'] !=''){
			$fileArrayOther = Db::name('File')->where('id','in',$detail['other_file_ids'])->select();
			$detail['fileArrayOther'] = $fileArrayOther;
		}

		$is_check_admin = 0;
		$is_create_admin = 0;
		if($detail['admin_id'] == $this->uid){
			$is_create_admin = 1;
		}
		if(in_array($this->uid,$check_user_ids)){
			$is_check_admin = 1;
			//当前审核节点详情
			if($flows['flow_type'] == 4){
				$check_count = Db::name('FlowRecord')->where(['action_id'=>$detail['id'],'type'=>3,'step_id'=>$flows['id'],'check_user_id'=>$this->uid])->count();
				if($check_count>0){
					$is_check_admin = 0;
				}
			}
		}
		
		$check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
			->alias('f')
			->join('Admin a', 'a.id = f.check_user_id', 'left')
			->where(['f.action_id'=>$detail['id'],'f.type'=>3])
			->order('check_time desc')
			->select()->toArray();
		foreach ($check_record as $kk => &$vv) {		
			$vv['check_time_str'] = date('Y-m-d H:i:s', $vv['check_time']);
			$vv['check_time'] = date('Y-m-d H:i:s', $vv['check_time']);
			$vv['status_str'] = '提交';
			if($vv['status'] == 1){
				$vv['status_str'] = '审核通过';
			}
			else if($vv['status'] == 2){
				$vv['status_str'] = '审核拒绝';
			}
			if($vv['status'] == 3){
				$vv['status_str'] = '撤销';
			}
		}
		// is_create_admin 是否为创建人 is_check_admin 是否为审核人
		$this->apiSuccess('获取成功', compact('is_create_admin', 'is_check_admin', 'check_record', 'detail', 'flows')); 
    }

    //删除
    public function delete()
    {
		$this->checkAuth();
        $this->uid = JWT_UID;
        $id = get_params("id");
		$detail = (new InvoiceList())->detail($id);
		if(empty($detail)){
			$this->apiError('申请开票不存在');
		}
        $status = InvoiceList::where(['id' => $id])->value('check_status');
        if ($status == 2) {
			$this->apiError('已审核的发票不能删除');
        }
        if ($status == 3) {
			$this->apiError('已开具的发票不能删除');
        }
        $data['delete_time'] = time();
        $data['id'] = $id;
        if (InvoiceList::update($data) !== false) {
            add_log('delete', $id);
            $this->apiSuccess('删除成功');
        } else {
			$this->apiError('删除失败');
        }
    }

	//开具发票
	public function open()
	{
		$param = get_params();
		$this->uid = JWT_UID;
		$auth = isAuthInvoice($this->uid);
		if($auth == 0){
			$this->apiError("你没有开票权限,请联系管理员或者HR", [], 2);
		}
		if (empty($param['id'])) {
            $this->apiError("id不能为空");
        }
		if (empty($param['code'])) {
            $this->apiError("发票号码不能为空");
        }
		if (empty($param['open_time'])) {
            $this->apiError("开票日期不能为空");
        }
		$status = InvoiceList::where(['id' => $param['id']])->value('check_status');
		if ($status == 2) {
			$param['check_status'] = 5;
			$param['open_admin_id'] = $this->uid;
		}
		if(isset($param['open_time'])){
			$param['open_time'] = strtotime(urldecode($param['open_time']));
		}
		$res = InvoiceList::where('id', $param['id'])->strict(false)->field('code,check_status,open_time,open_admin_id,delivery,other_file_ids')->update($param);
		if ($res !== false) {
			add_log('open', $param['id'],$param,'发票');
			$this->apiSuccess('操作成功');
		} else {
			$this->apiError("操作失败");
		}
	}
	 
	//作废发票
	public function tovoid()
	{
		$param = get_params();
		$this->uid = JWT_UID;
		$auth = isAuthInvoice($this->uid);
		if($auth == 0){
			$this->apiError("你没有开票权限,请联系管理员或者HR", [], 2);
		}
		if (empty($param['id'])) {
            $this->apiError("id不能为空");
        }
		$param['check_status'] = 10;
		if ($param['check_status'] == 10) {
			$count = InvoiceIncome::where(['inid'=>$param['id'],'status'=>1])->count();
			if($count>0){
				$this->apiError("发票已经新增有到账记录,请先反到账后再作废发票");
			}
			else{
				$param['update_time'] = time();
			}
		}
		$res = InvoiceList::where('id', $param['id'])->strict(false)->field('check_status')->update($param);
		if ($res !== false) {
			add_log('tovoid', $param['id'],$param,'发票');
			$this->apiSuccess('操作成功');
		} else {
			$this->apiError("操作失败");
		}
	}
 
	//反作废发票
	public function novoid()
	{
		$param = get_params();
		$this->uid = JWT_UID;
		$auth = isAuthInvoice($this->uid);
		if($auth == 0){
			$this->apiError("你没有开票权限,请联系管理员或者HR", [], 2);
		}
		if (empty($param['id'])) {
            $this->apiError("id不能为空");
        }
		$param['check_status'] = 5;
		$param['update_time'] = time();
		add_log('tovoid', $param['id'],$param,'发票');
		$res = InvoiceList::where('id', $param['id'])->strict(false)->field('check_status')->update($param);
		if ($res !== false) {
			add_log('novoid', $param['id'],$param,'发票');
			$this->apiSuccess('操作成功');
		} else {
			$this->apiError("操作失败");
		}
	}
 
}