<?php
/**
 * Created by PhpStorm.
 * User: nizongfeng
 * Date: 2021/11/10
 * Time: 10:20
 */

namespace app\admin\dao;


use app\admin\command\Util;
use app\admin\model\OrderMain;
use app\admin\model\ReceiptOrder;
use think\Exception;

class ReceiptOrderDao
{

    /**
     * 获取详情
     * @param $id
     * @return array
     */
    public function getInfoById($id){
        try{
            $model = new ReceiptOrder();
            $info =  $model->where(["id"=>$id])->find();
            if ($info == null) {
                return Util::returnArrEr("获取收款单信息失败:".$id);
            }
            return Util::returnArrSu("",$info->toArray());
        }catch (Exception $e){
            return Util::returnArrEr("获取收款单信息失败:".$e->getMessage());
        }
    }

    /**
     * 添加记录
     * @param $param
     * @return array
     */
    public function save($param)
    {
        if ($this->checkName($param)) {
            return Util::returnArrEr("名称已经存在");
        }
        try {
            $data = [
                'name' => $param['name'],
                "create_id"=>$param['create_id'],
                "group_id"=>$param['group_id']
            ];
            $receiptOrder = new ReceiptOrder();
            if (empty($param['id'])) {
                $id = $receiptOrder->insertGetId($data);
                return Util::returnArrSu("", $id);
            } else {
                $receiptOrder->save($data, ['id' => $param['id']]);
                return Util::returnArrSu("", $param['id']);
            }
        } catch (Exception $e) {
            return Util::returnArrEr("更新主订单失败:" . $e->getMessage());
        }
    }

    /**
     * 校验名称
     * @param $param
     * @return bool
     */
    public function checkName($param):bool {
        try {
            $model = new ReceiptOrder();
            $infoRe = $model->where(["name" => $param['name'],"group_id"=>$param['group_id']])->find();
            if ($infoRe == null) {
                return false;
            }
            $info = $infoRe->toArray();
            if (isset($param['id'])) {
                if ($param['id'] != $info['id']) {
                    return true;
                }
            }else{
                return true;
            }
            return false;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 修改状态
     * @param $id
     * @param $status
     * @return array
     */
    public function setStatus($id, $status)
    {
        try {
            //设置收购单状态
            $receiptOrder = new ReceiptOrder();
            $receiptOrder->save(['status' => $status], ['id' => $id]);
            return Util::returnArrSu();
        } catch (Exception $e) {
            return Util::returnArrEr("修改状态失败" . $e->getMessage());
        }
    }


    /**
     * 获取列表
     * @param $param
     * @return array
     */
    public function getList($param)
    {

        try {
            $where = ["a.del_flag"=>0,"a.group_id"=>$param['group_id']];
            if (!empty($param['order_id'])) {
                $orderMainModel = new OrderMain();
                $orderMain = $orderMainModel->where(["id"=>$param['order_id']])->find();
                if ($orderMain == null || empty($orderMain['receipt_order_id'])) {
                    $where["a.id"] = 0;
                }else{
                    $where["a.id"] = $orderMain['receipt_order_id'];
                }
            }
            if (!empty($param['name'])) {
                $where['a.name'] = ["like","%".$param['name']."%"];
            }
            if ($param['status']."" != 'all' && $param['status']!=="") {
                $where["a.status"] = $param['status'];
            }
            if (!empty($param["id"])) {
                $where["a.id"] = $param["id"];
            }
            if (!empty($param['create_id'])) {
                $where["a.create_id"] = $param["create_id"];
            }
            $having = "";
            if(!empty($param['startMoney']) && !empty($param['endMoney'])) {
                $having = " total_amount >= {$param['startMoney']} and  total_amount <= {$param['endMoney']}  ";
            }
            if(!empty($param['startMoney']) && empty($param['endMoney'])) {
                $having = " total_amount >= {$param['startMoney']}   ";
            }
            if(empty($param['startMoney']) && !empty($param['endMoney'])) {
                $having = " total_amount <= {$param['endMoney']}  ";
            }
            $offset = ($param['pageNum'] - 1) * $param['pageSize'];
            $receiptOrder = new ReceiptOrder();
            $total = $receiptOrder
                ->alias("a")
                ->join('hbp_order_main b', 'a.id = b.receipt_order_id', 'left')
                ->field("a.*,GROUP_CONCAT(b.id) order_ids,sum(b.total_amount) total_amount")
                ->group("a.id")
                ->where($where)
                ->having($having)
                ->count();

            $list = $receiptOrder
                ->alias("a")
                ->join('hbp_order_main b', 'a.id = b.receipt_order_id', 'left')
                ->field("a.*,GROUP_CONCAT(b.id ORDER BY b.id DESC) order_ids,sum(b.total_amount) total_amount")
                ->group("a.id")
                ->where($where)
                ->having($having)
                ->limit($offset, $param['pageSize'])
                ->order("id","DESC")->select();
            $data = ["total" => $total, "list" => $list->toArray()];
            return Util::returnArrSu("", $data);
        } catch (Exception $e) {
            return Util::returnArrSu("", ["total" => 0, "list" => []]);
        }
    }

    /**
     * 删除
     * @param $id
     * @return array
     */
    public function del($id){
        try {
            //设置收购单状态
            $receiptOrder = new ReceiptOrder();
            $receiptOrder->save(['del_flag' => 1], ['id' => $id]);
            return Util::returnArrSu();
        } catch (Exception $e) {
            return Util::returnArrEr("修改状态失败" . $e->getMessage());
        }
    }
}