package com.fuint.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuint.common.dto.AccountInfo;
import com.fuint.common.dto.ext.TableCategoryDto;
import com.fuint.common.enums.StatusEnum;
import com.fuint.common.param.PageParam;
import com.fuint.common.service.TableCategoryService;
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.pagination.PaginationRequest;
import com.fuint.framework.pagination.PaginationResponse;
import com.fuint.framework.web.PageResult;
import com.fuint.repository.bean.TableCategoryBean;
import com.fuint.repository.mapper.MtTableCategoryMapper;
import com.fuint.repository.mapper.MtTableInfoMapper;
import com.fuint.repository.model.MtTableCategory;
import com.fuint.repository.model.MtTableInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
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.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 餐桌分类表服务接口
 *
 * Created by pzg
 * CopyRight https://www.fuint.cn
 */
@Service
@AllArgsConstructor
public class TableCategoryServiceImpl extends ServiceImpl<MtTableCategoryMapper, MtTableCategory> implements TableCategoryService {

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

    private MtTableCategoryMapper mtTableCategoryMapper;

    private MtTableInfoMapper tableInfoMapper;


    @Override
    public PaginationResponse<MtTableCategory> queryTableCategoryListByPagination(PaginationRequest paginationRequest) {
        Page<MtTableCategory> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        LambdaQueryWrapper<MtTableCategory> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ne(MtTableCategory::getDeleteFlag, 1);

        lambdaQueryWrapper.orderByAsc(MtTableCategory::getId);
        List<MtTableCategory> dataList = mtTableCategoryMapper.selectList(lambdaQueryWrapper);

        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(dataList, pageRequest, pageHelper.getTotal());
        PaginationResponse<MtTableCategory> paginationResponse = new PaginationResponse(pageImpl, MtTableCategory.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(dataList);

        return paginationResponse;
    }

    /**
     * 添加餐桌分类表
     *
     * @param mtTableCategory 餐桌分类表信息
     * @return
     */
    @Override
    @OperationServiceLog(description = "新增餐桌分类表")
    public MtTableCategory addTableCategory(MtTableCategory mtTableCategory) throws BusinessCheckException {
        mtTableCategory.setDeleteFlag(0);
        mtTableCategory.setUpdateTime(new Date());
        mtTableCategory.setCreateTime(new Date());
        int id = mtTableCategoryMapper.insert(mtTableCategory);
        if (id > 0) {
            return mtTableCategory;
        } else {
            throw new BusinessCheckException("新增餐桌分类表数据失败");
        }
    }

    /**
     * 根据ID获餐桌分类表取息
     *
     * @param id 餐桌分类表ID
     * @return
     */
    @Override
    public MtTableCategory queryTableCategoryById(Long id) {
        return mtTableCategoryMapper.selectById(id);
    }

    /**
     * 根据ID删除餐桌分类表
     *
     * @param id 餐桌分类表ID
     * @param operator 操作人
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "删除餐桌分类表")
    public void deleteTableCategory(Long id, String operator) {
        MtTableCategory mtTableCategory = queryTableCategoryById(id);
        if (null == mtTableCategory) {
            return;
        }
        mtTableCategory.setDeleteFlag(1);
        mtTableCategory.setUpdateTime(new Date());
        mtTableCategoryMapper.updateById(mtTableCategory);
    }

    /**
     * 修改餐桌分类表数据
     *
     * @param mtTableCategory
     * @throws BusinessCheckException
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "更新餐桌分类表")
    public MtTableCategory updateTableCategory(MtTableCategory mtTableCategory) throws BusinessCheckException {
        mtTableCategory = queryTableCategoryById(mtTableCategory.getId());
        if (mtTableCategory == null) {
            throw new BusinessCheckException(I18nUtil.getMessage("diningTableCategoryStatusAbnormal"));
        }
        mtTableCategory.setUpdateTime(new Date());
        mtTableCategoryMapper.updateById(mtTableCategory);
        return mtTableCategory;
    }

   /**
    * 根据条件搜索餐桌分类表
    *
    * @param  params 查询参数
    * @throws BusinessCheckException
    * @return
    * */
    @Override
    public List<MtTableCategory> queryTableCategoryListByParams(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<MtTableCategory> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(storeId)) {
            lambdaQueryWrapper.and(wq -> wq
                    .eq(MtTableCategory::getStoreId, 0)
                    .or()
                    .eq(MtTableCategory::getStoreId, storeId));
        }

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

    /**
     * 校验分类是否存在且有效
     * @param categoryId 分类ID
     * @return 是否存在有效分类
     */
    @Override
    public boolean existCategory(Long categoryId) {
        if (categoryId == null || categoryId < 1) {
            return false;
        }
        // 构造查询条件（包含删除状态校验）
        LambdaQueryWrapper<MtTableCategory> query = new LambdaQueryWrapper<>();
        query.eq(MtTableCategory::getId, categoryId)
                .eq(MtTableCategory::getDeleteFlag, 0); // 0-未删除
        return mtTableCategoryMapper.selectCount(query) > 0;
    }


	@Override
	public void saveHandler(TableCategoryDto tableCategoryDto) throws BusinessCheckException {
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MtTableCategory>()
                .eq(MtTableCategory::getCategoryName, tableCategoryDto.getCategoryName()));
        if (count>0){
            throw new BusinessCheckException(I18nUtil.getMessage("existCat"));
        }
        AccountInfo accountInfo = AuthUserUtil.get();
        if (accountInfo.getStoreId()==null || accountInfo.getStoreId()<=0){
            throw new BusinessCheckException(I18nUtil.getMessage("superAdminNotAllowedUseMerchantAccount"));
        }
        //创建分类并插入
        MtTableCategory mtTableCategory = new MtTableCategory();
        BeanUtils.copyProperties(tableCategoryDto,mtTableCategory);
        mtTableCategory.setDeleteFlag(0);
        mtTableCategory.setProject("0");
        mtTableCategory.setStoreId(accountInfo.getStoreId());
        mtTableCategory.setCreateUserId(accountInfo.getId().toString());
        mtTableCategory.setUpdateUserId(accountInfo.getId().toString());
        this.baseMapper.insert(mtTableCategory);
    }

    @Override
    public void updateStatus(TableCategoryDto tableCategoryDto) throws BusinessCheckException {
        MtTableCategory tableCategory = this.baseMapper.selectById(tableCategoryDto.getId());
        if (Objects.isNull(tableCategory)){
            throw new BusinessCheckException(I18nUtil.getMessage("paramErr"));
        }
       if (tableCategory.getCategoryName().equals(tableCategoryDto.getCategoryName())){
           Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MtTableCategory>()
                   .eq(MtTableCategory::getCategoryName, tableCategoryDto.getCategoryName()));
           if (count>0){
               throw new BusinessCheckException(I18nUtil.getMessage("existCat"));
           }
       }
        MtTableCategory mtTableCategory = new MtTableCategory();
        BeanUtils.copyProperties(tableCategoryDto,mtTableCategory);
        this.baseMapper.updateById(mtTableCategory);
    }

    @Override
    public PageResult<TableCategoryBean> selectTableCategoryList(String categoryName, PageParam pageParam) throws ExecutionException, InterruptedException {
        Long storeId = AuthUserUtil.get().getStoreId();
        //查询总页数
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> this.baseMapper
                .selectByStoreIdAndCategoryCount(storeId, categoryName));
        //查询数据
        List<TableCategoryBean>  mtTableCategoryIPage = this.baseMapper
                .selectByStoreIdAndCategoryName(storeId,categoryName,(pageParam.getPage()-1)*pageParam.getPageSize(),pageParam.getPageSize());
        return PageResult.<TableCategoryBean>builder().data(mtTableCategoryIPage).total(future.get()!=null?future.get():0).build();
    }

    @Override
    public void deleteHandler(Long id) throws BusinessCheckException {
        //判断是否有餐桌引用
        Integer count = tableInfoMapper.selectCount(new LambdaQueryWrapper<MtTableInfo>()
                .eq(MtTableInfo::getCategoryId, id));
        if (count>0){
            throw new BusinessCheckException(I18nUtil.getMessage("unrmvTblRef"));
        }
        this.baseMapper.deleteById(id);
    }
}
