<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\contract;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\lists\ListsExcelInterface;
use app\common\model\auth\Admin;
use app\common\model\bid\BidBuyBiddingDocument;
use app\common\model\contract\Contract;
use app\common\lists\ListsSearchInterface;
use app\common\model\contract\ContractNegotiation;
use app\common\model\custom\Custom;
use app\common\model\finance\FinanceInvoiceApply;
use app\common\model\finance\FinanceRefundApply;
use app\common\model\finance\FinanceReturnedRecord;
use app\common\model\project\Project;
use think\facade\Db;

/**
 * 项目合同列表
 * Class ContractLists
 * @package app\adminapi\listscontract
 */
class ContractLists extends BaseAdminDataLists implements ListsSearchInterface,ListsExcelInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2023/12/02 17:19
     */
    public function setSearch(): array
    {
        return [
            '=' => ['project_id','contract_type', 'contract_code'],
	        '%like%' => ['contract_code']
        ];
    }


    /**
     * @notes 获取项目合同列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2023/12/02 17:19
     */
    public function lists(): array
    {
		$params = $this->request->get(['project_name','business_director_name','custom_id']);
		$where = [];
		if(isset($params['project_name']) && $params['project_name'] != ''){
			$project_ids = Project::where('name','like','%'.$params['project_name'].'%')->column('id');
			$where[] = ['project_id','in',$project_ids];
		}
	    if(isset($params['business_director_name']) && $params['business_director_name'] != ''){
		    $business_director_ids = Admin::where('name','like','%'.$params['business_director_name'].'%')->column('id');
		    $where[] = ['business_director','in',$business_director_ids];
	    }
	    if(isset($params['custom_id']) && $params['custom_id'] != ''){
		    $project_ids = Project::where('custom_id','=',$params['custom_id'])->column('id');
		    $where[] = ['project_id','in',$project_ids];
	    }
        return Contract::where($this->searchWhere)->where($where)
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['id' => 'desc'])
            ->select()->each(function($data){
		        $project = Project::field('custom_id,name,project_code')->where('id',$data['project_id'])->findOrEmpty();
		        $custom = Custom::field('name')->where('id',$project['custom_id'])->findOrEmpty();
		        $buy_bidding_document = BidBuyBiddingDocument::field('bid_document_no')->where('id',$data['buy_bidding_document_id'])->findOrEmpty();
		        $business_director = Admin::field('name')->where('id',$data['business_director'])->findOrEmpty();
		        $data['custom_name'] = $custom['name'];
		        $data['bid_document_no'] = $buy_bidding_document['bid_document_no'];
		        $data['project_name'] = $project['name'];
		        $data['project_code'] = $project['project_code'];
		        $data['contract_type_text'] = $data->contract_type_text;
		        $data['contract_pricing_method_text'] = $data->contract_pricing_method_text;
		        $data['contract_status_text'] = $data->contract_status_text;
		        $data['business_director_name'] = $business_director['name'];
				//洽商金额
				$data['negotiation_amount'] = ContractNegotiation::where('contract_id',$data['id'])->sum('negotiation_amount');
		        //回款金额
		        $data['returned_amount'] = FinanceReturnedRecord::where('contract_id',$data['id'])->sum('amount');
				//开票金额
		        $data['invoicing_amount'] = FinanceInvoiceApply::where('contract_id',$data['id'])->sum('invoicing_amount');
				//退款金额
		        $data['refund_amount'] = FinanceRefundApply::where('contract_id',$data['id'])->sum('amount');
				//实际合同金额=合同金额+洽商金额-退款金额
		        $data['reality_contract_amount'] = $data['amount'] + $data['negotiation_amount'] - $data['refund_amount'];
				//未回款金额
				$data['not_returned_amount'] = $data['reality_contract_amount'] - $data['returned_amount'];
				//未开票金额
				$data['not_invoicing_amount'] = $data['reality_contract_amount'] - $data['invoicing_amount'];
				//结算差异(带计算)
		        $data['settlement_difference'] = 0;
                return $data;
            })
            ->toArray();
    }


    /**
     * @notes 获取项目合同数量
     * @return int
     * @author likeadmin
     * @date 2023/12/02 17:19
     */
    public function count(): int
    {
	    $params = $this->request->get(['project_name','business_director_name','custom_id']);
	    $where = [];
	    if(isset($params['project_name']) && $params['project_name'] != ''){
		    $project_ids = Project::where('name','like','%'.$params['project_name'].'%')->column('id');
		    $where[] = ['project_id','in',$project_ids];
	    }
	    if(isset($params['business_director_name']) && $params['business_director_name'] != ''){
		    $business_director_ids = Admin::where('name','like','%'.$params['business_director_name'].'%')->column('id');
		    $where[] = ['business_director','in',$business_director_ids];
	    }
	    if(isset($params['custom_id']) && $params['custom_id'] != ''){
		    $project_ids = Project::where('custom_id','=',$params['custom_id'])->column('id');
		    $where[] = ['project_id','in',$project_ids];
	    }
        return Contract::field('id')->where($this->searchWhere)->where($where)->count();
    }
	
	public function setFileName(): string
	{
		return '项目合同列表';
	}
	
	/**
	 * @notes 导出字段
	 * @return string[]
	 * @author 段誉
	 * @date 2022/11/24 16:17
	 */
	public function setExcelFields(): array
	{
		return [
			"id" => "id",
			"contract_code" => "合同编号",
            "custom_name" => "客户名称",
            "project_name" => "项目名称",
            "project_code" => "项目编码",
			"contract_type_text" => "合同类型",
            "contract_pricing_method_text" => "合同计价方式",
			"business_director_name" => "业务负责人",
            "contract_status_text" => "合同状态",
            "expire" => "合同有效期",
            "contract_date" => "签约日期",
			"amount" =>"合同金额",
			"negotiation_amount" =>"洽商金额",
			"reality_contract_amount" =>"实际合同金额",
			"returned_amount" =>"已回款",
			"not_returned_amount" =>"未回款",
			"invoicing_amount" =>"已开票",
			"not_invoicing_amount" =>"未开票",
			"refund_amount" =>"已退款金额",
		];
	}

}