<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-04-16
 *
 * 
 */

namespace app\common\dao\system\merchant;


use app\common\dao\BaseDao;
use app\common\enum\merchant\MerchantEnum;
use app\common\model\system\merchant\Merchant;
use app\common\model\user\User;
use app\entity\CommonEntity;
use app\entity\data\merchant\MerchantEntity;
use think\db\BaseQuery;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class MerchantDao extends BaseDao
{

    /**
     * @return string
     * @author xaboy
     * @day 2020-04-16
     */
    protected function getModel(): string
    {
        return Merchant::class;
    }

    /**
     * @param array $where
     * @return BaseQuery
     * @author xaboy
     * @day 2020-04-16
     */
    public function search(array $where, $is_del = 0)
    {
        $query = Merchant::getDB()->when($is_del !== null, function ($query) use ($is_del) {
            $query->where('is_del', $is_del);
        })->when(isset($where['date']) && $where['date'] !== '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        });
        if (isset($where['keyword']) && $where['keyword'])
            $query->whereLike('mer_name|mer_keyword|mer_phone', "%{$where['keyword']}%");
        if (isset($where['status']) && $where['status'])
            $query->where('status', $where['status']);
        if (isset($where['mer_state']) && $where['mer_state'])
            $query->where('mer_state', $where['mer_state']);
        if (isset($where['category_id']) && $where['category_id'])
            $query->where('category_id', $where['category_id']);
        if (isset($where['city_id']) && $where['city_id'])
            $query->where('city_id', $where['city_id']);
        $order = $where['order'] ?? '';
        $query->when($order, function ($query) use ($order) {
            if (in_array($order, ['rate', 'sales']) && $order == 'rate')
                $query->order('is_best DESC, product_score DESC,service_score DESC,postage_score DESC,sort DESC');
            else
                $query->order('is_best DESC, sales DESC,sort DESC');
        }, function ($query) use ($order) {
            $query->order('is_best DESC, sort DESC,sales DESC');
        })->when(isset($where['account']) && $where['account'] !== '', function ($query) use ($where) {
            $uid = User::where('account|nickname|phone', 'like', "%{$where['account']}%")
                ->column('uid');
            $query->where('uid', 'in', $uid);
        });
        return $query;
    }


    /**
     * @param array $where
     * @param int $is_del
     * @return BaseQuery
     */
    public function searchLeft(array $where, $is_del = 0)
    {

        $query = Merchant::getDB()->when($is_del !== null, function ($query) use ($is_del) {
            $query->where('merchant.is_del', $is_del);
        })->when(isset($where['date']) && $where['date'] !== '', function ($query) use ($where) {
            getModelTime($query, $where['date'], 'merchant.create_time');
        });
        if (isset($where['keyword']) && $where['keyword'])
            $query->whereLike('merchant.mer_name|merchant.mer_keyword|merchant.mer_phone', "%{$where['keyword']}%");
        if (isset($where['status']) && $where['status'])
            $query->where('merchant.status', $where['status']);
        if (isset($where['mer_state']) && $where['mer_state'])
            $query->where('merchant.mer_state', $where['mer_state']);
        if (isset($where['category_id']) && $where['category_id'])
            $query->where('merchant.category_id', $where['category_id']);
        if (isset($where['city_id']) && $where['city_id'])
            $query->where('merchant.city_id', $where['city_id']);
        $order = $where['order'] ?? '';
        $query->when($order, function ($query) use ($order) {
            if (in_array($order, ['rate', 'sales']) && $order == 'rate')
                $query->order('merchant.is_best DESC, merchant.product_score DESC,merchant.service_score DESC,merchant.postage_score DESC,merchant.sort DESC');
            else
                $query->order('merchant.is_best DESC, merchant.sales DESC,merchant.sort DESC');
        }, function ($query) use ($order) {
            $query->order('merchant.is_best DESC, merchant.sort DESC,merchant.sales DESC');
        })->when(isset($where['account']) && $where['account'] !== '', function ($query) use ($where) {
            $uid = User::where('account|nickname|phone', 'like', "%{$where['account']}%")
                ->column('uid');
            $query->where('merchant.uid', 'in', $uid);
        });
        $query->where('merchantIntention.status', 1);
        return $query;
    }

    /**
     * @param array $where
     * @return BaseQuery
     * @author cabbage
     * @day 2020-10-31
     */
    public function search_mer(array $where, $is_del = 0)
    {
        $query = Merchant::getDB()->when($is_del !== null, function ($query) use ($is_del) {
            $query->where('is_del', $is_del);
        })->when(isset($where['date']) && $where['date'] !== '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        });
        if (isset($where['keyword']) && $where['keyword'])
            $query->whereLike('mer_name|mer_keyword|mer_phone', "%{$where['keyword']}%");
        if (isset($where['status']) && $where['status'])
            $query->where('status', $where['status']);
        if (isset($where['mer_state']) && $where['mer_state'])
            $query->where('mer_state', $where['mer_state']);
        if (isset($where['category_id']) && $where['category_id'])
            $query->where('category_id', $where['category_id']);
        if (isset($where['sxy_submerchant_id'])){
            $query->whereNotNull('sxy_submerchant_id');
        }

        return $query;
    }

    /**
     * @param int $id
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-04-17
     */
    public function get( $id)
    {
        return Merchant::getInstance()->where('is_del', 0)->find($id);
    }

    /**
     * @param $id
     * @author Qinii
     */
    public function apiGetOne($id)
    {
        return Merchant::getInstance()->where(['is_del'=>0,'status' => 1,'mer_state' => 1])->find($id);
    }
    /**
     * @param $id
     * @author Qinii
     */
    public function addrenqi($id)
    {
        return Merchant::getInstance()->where('mer_id',$id)->inc('renqizhi',1)->update();
    }
    /**
     * @param int $merId
     * @author Qinii
     */
    public function incCareCount(int $merId)
    {
        ($this->getModel()::getDB())->where($this->getPk(),$merId)->inc('care_count',1)->update();
    }

    /**
     * @param int $merId
     * @author Qinii
     */
    public function decCareCount(int $merId)
    {
        ($this->getModel()::getDB())->where($this->getPk(),$merId)->where('care_count','>',0)->dec('care_count',1)->update();
    }

    public function dateMerchantNum($date)
    {
        return Merchant::getDB()->where('is_del', 0)->when($date, function ($query, $date) {
            getModelTime($query, $date);
        })->count();
    }

    /**
     * TODO 获取复制商品次数
     * @param int $merId
     * @return mixed
     * @author Qinii
     * @day 2020-08-06
     */
    public function getCopyNum(int $merId)
    {
       return  Merchant::getDB()->where('mer_id',$merId)->value('copy_product_num');
    }

    /**
     * TODO 变更复制次数
     * @param int $merId
     * @param int $num 正负数
     * @return mixed
     * @author Qinii
     * @day 2020-08-06
     */
    public function changeCopyNum(int $merId,int $num)
    {
        return $this->getModel()::where('mer_id',$merId)->inc('copy_product_num',$num)->update();
    }

    public function getConsumptionScoreMer(){
        return $this->getModel()::where('consumption_score',1)->field('mer_id,uid') -> select();
    }


    /**
     * 根据 商户ID 获取 未删除的 商户信息
     * @param int $merId
     * @return \app\entity\CommonEntity
     */
    public function getMerchantEntityByMerchantId(int $merId): \app\entity\CommonEntity
    {
        $data = [];
        try {
            /** @var Merchant $model */
            $model = $this->getModel();
            $dataRes = $model::getDB()
                ->where('mer_id', '=', $merId)
                ->where('is_del', '=', MerchantEnum::IS_DEL['No']['code'])
                ->find();
            if (!empty($dataRes)) {
                $data = $dataRes->toArray();
            }
        } catch (\Exception $e) {

        }
        return MerchantEntity::newInstance($data);
    }

    /**
     * @param array $idList
     * @return CommonEntity[]
     */
    public function getMerchantEntityListByMerchantIdList(array $idList): array
    {
        $entityList = [];
        try {
            /** @var Merchant $model */
            $model = $this->getModel();
            $dataRes = $model::getDB()
                ->whereIn('mer_id', $idList)
                ->where('is_del', '=', MerchantEnum::IS_DEL['No']['code'])
                ->select()
                ->toArray();
            if (!empty($dataRes)) {
                $entityList = array_map(function ($data) {
                    return MerchantEntity::newInstance($data);
                }, $dataRes);
            }
        } catch (\Exception $e) {

        }
        return $entityList;
    }
}
