package com.fuint.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuint.common.dto.AccountInfo;
import com.fuint.common.enums.StatusEnum;
import com.fuint.common.param.PageParam;
import com.fuint.common.service.TableInfoService;
import com.fuint.common.util.AuthUserUtil;
import com.fuint.common.util.I18nUtil;
import com.fuint.framework.annoation.OperationServiceLog;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.framework.web.PageResult;
import com.fuint.repository.bean.TableInfoBean;
import com.fuint.repository.mapper.MtStoreMapper;
import com.fuint.repository.mapper.MtTableCategoryMapper;
import com.fuint.repository.mapper.MtTableInfoMapper;
import com.fuint.repository.model.MtStore;
import com.fuint.repository.model.MtTableInfo;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 餐桌信息服务接口
 *
 * Created by pzg
 * CopyRight https://www.fuint.cn
 */
@Service
@AllArgsConstructor
public class TableInfoServiceImpl extends ServiceImpl<MtTableInfoMapper, MtTableInfo> implements TableInfoService {

    private static final Logger logger = LoggerFactory.getLogger(TableInfoServiceImpl.class);

    private  MtTableInfoMapper mtTableInfoMapper;

    private MtTableCategoryMapper tableCategoryMapper;

    private MtStoreMapper storeMapper;

    /**
     * 分页查询数据列表
     *
     * @param paginationRequest
     * @return
     */


    /**
     * 添加餐桌信息
     *
     * @param mtTableInfo 餐桌信息信息
     * @return
     */
    @Override
    @OperationServiceLog(description = "新增餐桌信息")
    public MtTableInfo addTableInfo(MtTableInfo mtTableInfo) throws BusinessCheckException {
        mtTableInfo.setDeleteFlag(0);
        mtTableInfo.setUpdateTime(new Date());
        mtTableInfo.setCreateTime(new Date());
        Integer id = mtTableInfoMapper.insert(mtTableInfo);
        if (id > 0) {
            return mtTableInfo;
        } else {
            throw new BusinessCheckException(I18nUtil.getMessage("saveErr"));
        }
    }

    /**
     * 根据ID获餐桌信息取息
     *
     * @param id 餐桌信息ID
     * @return
     */
    @Override
    public MtTableInfo queryTableInfoById(Long id) {
        return mtTableInfoMapper.selectById(id);
    }

    /**
     * 根据ID删除餐桌信息
     *
     * @param id 餐桌信息ID
     * @param operator 操作人
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "删除餐桌信息")
    public void deleteTableInfo(Long id, String operator) {
        MtTableInfo mtTableInfo = queryTableInfoById(id);
        if (null == mtTableInfo) {
            return;
        }
        mtTableInfo.setDeleteFlag(1);
        mtTableInfo.setUpdateTime(new Date());
        mtTableInfoMapper.updateById(mtTableInfo);
    }

    /**
     * 修改餐桌信息数据
     *
     * @param mtTableInfo
     * @throws BusinessCheckException
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "更新餐桌信息")
    public MtTableInfo updateTableInfo(MtTableInfo mtTableInfo) throws BusinessCheckException {
        mtTableInfoMapper.updateById(mtTableInfo);
        return mtTableInfo;
    }

   /**
    * 根据条件搜索餐桌信息
    *
    * @param  params 查询参数
    * @throws BusinessCheckException
    * @return
    * */
    @Override
    public List<MtTableInfo> queryTableInfoListByParams(Map<String, Object> params) {
        String status =  params.get("status") == null ? StatusEnum.ENABLED.getKey(): params.get("status").toString();
        String storeId =  params.get("storeId") == null ? "" : params.get("storeId").toString();
        String merchantId =  params.get("merchantId") == null ? "" : params.get("merchantId").toString();

        LambdaQueryWrapper<MtTableInfo> lambdaQueryWrapper = Wrappers.lambdaQuery();

        lambdaQueryWrapper.orderByAsc(MtTableInfo::getId);
        List<MtTableInfo> dataList = mtTableInfoMapper.selectList(lambdaQueryWrapper);
        return dataList;
    }

    @Override
    public List<MtTableInfo> selectTableListByStoreId(Long storeId, String categoryName) throws BusinessCheckException {
        //通过店铺id获取店铺下的餐桌分类
        /*MtTableCategory mtTableCategory = tableCategoryMapper.selectOne(new LambdaQueryWrapper<MtTableCategory>()
                .select(MtTableCategory::getId,MtTableCategory::getStoreId)
                .eq(MtTableCategory::getId, categoryName));
        if (Objects.isNull(mtTableCategory) || !storeId.equals(mtTableCategory.getStoreId())) {
            return new ArrayList<>();
        }*/
        //返回结果
//        if (StringUtils.isEmpty(categoryName)){
//            throw new BusinessCheckException(I18nUtil.getMessage("NonEmptyCategoryName"));
//        }

        return this.list(new LambdaQueryWrapper<MtTableInfo>()
                .select(MtTableInfo::getId, MtTableInfo::getTableNumber)
                .eq(MtTableInfo::getTableStatus,0)
                 .eq(MtTableInfo::getStoreId,storeId)
                .eq(StringUtils.isNotEmpty(categoryName),MtTableInfo::getCategoryName, categoryName)
                .eq(MtTableInfo::getDeleteFlag, 0));

    }
    @Override
    public boolean existCategory(Long categoryId) {
        return mtTableInfoMapper.selectCount(
                new LambdaQueryWrapper<MtTableInfo>()
                        .eq(MtTableInfo::getId, categoryId)
        ) > 0;
    }

    @Override
    public List<MtTableInfo> findByCategoryId(Long categoryId) {
        List<MtTableInfo> tableInfos = mtTableInfoMapper.findByCategoryId(categoryId);
        return tableInfos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveTable(MtTableInfo entity) throws BusinessCheckException {
        // 校验桌号唯一性
        Long storeId = AuthUserUtil.get().getStoreId();
        if (storeId==null || storeId<0){
            throw new BusinessCheckException("平台号无权限修改");
        }
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MtTableInfo>()
                .eq(MtTableInfo::getTableNumber, entity.getTableNumber())
                .eq(MtTableInfo::getStoreId,storeId)
                .eq(MtTableInfo::getDeleteFlag, 0));
        if (count>0) {
            throw new BusinessCheckException("桌号已存在");
        }

        // 自动填充时间（兼容数据库自动填充）
        if (entity.getCreateTime() == null) {
            entity.setCreateTime(new Date());
        }
        entity.setUpdateTime(new Date());

        return mtTableInfoMapper.insert(entity) > 0;
    }

    /**
     * 修改餐桌信息接口
     * @param entity
     * @return
     */
    @Override
    public boolean updateTable(MtTableInfo entity) throws BusinessCheckException{
        return updateById(entity);
    }

    @Override
    public PageResult<TableInfoBean> selectTableList(String tableName, Integer tableStatus, PageParam param) throws BusinessCheckException {
        AccountInfo accountInfo = AuthUserUtil.get();
        //检查是否登入
        if (accountInfo == null){
            throw new BusinessCheckException(I18nUtil.getMessage("notAuthenticated"));
        }
       /* if (accountInfo.getStoreId() == null || accountInfo.getStoreId() <=0){
            throw new BusinessCheckException(I18nUtil.getMessage("superAdminNotAllowedUseMerchantAccount"));
        }*/
        //分页查询
        IPage<MtTableInfo> mtTableInfoIPage = this.baseMapper.selectPage(new Page<>(param.getPage(), param.getPageSize()), new LambdaQueryWrapper<MtTableInfo>()
                 .eq((accountInfo.getStoreId()!=null && accountInfo.getStoreId()>0),MtTableInfo::getStoreId,accountInfo.getStoreId())
                 .eq(tableStatus!=null,MtTableInfo::getTableStatus,tableStatus)
                .likeRight(StringUtils.isNotEmpty(tableName), MtTableInfo::getTableNumber, tableName));
        //补全字段
        List<TableInfoBean> beanList = mtTableInfoIPage.getRecords().stream().map(mtTableInfo -> {
            TableInfoBean tableInfoBean = new TableInfoBean();
            Long storeId = mtTableInfo.getStoreId();
            //mtTableInfo copy到TableInfoBean
            BeanUtils.copyProperties(mtTableInfo, tableInfoBean);
            //获取店铺信息
            MtStore mtStore = storeMapper.selectById(storeId);
            if (mtStore!=null){
                tableInfoBean.setStoreName(mtStore.getName());
            }

            return tableInfoBean;
        }).collect(Collectors.toList());
        //返回
        return PageResult.<TableInfoBean>builder().data(beanList).total(Math.toIntExact(mtTableInfoIPage.getTotal())).build();
    }

}
