package com.ym.mec.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.PlatformServeDao;
import com.ym.mec.biz.dal.dao.PlatformServeDetailDao;
import com.ym.mec.biz.dal.dto.PlatformServeDto;
import com.ym.mec.biz.dal.entity.PlatformServe;
import com.ym.mec.biz.dal.entity.PlatformServeDetail;
import com.ym.mec.biz.dal.entity.TenantProductInfo;
import com.ym.mec.biz.dal.vo.PlatformServeInfoVo;
import com.ym.mec.biz.dal.vo.PlatformServeModeVo;
import com.ym.mec.biz.dal.vo.PlatformServePageVo;
import com.ym.mec.biz.service.PlatformServeService;
import com.ym.mec.biz.service.TenantProductInfoService;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.PageUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author hgw
 * Created by 2021-12-02
 */
@Service
public class PlatformServeServiceImpl extends ServiceImpl<PlatformServeDao, PlatformServe> implements PlatformServeService {

    @Autowired
    private PlatformServeDetailDao platformServeDetailDao;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private TenantProductInfoService tenantProductInfoService;

    /**
     * 增加
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addServe(PlatformServeDto obj) {
        PlatformServeServiceInfo serveInfo = getServeInfo(obj);
        serveInfo.getPlatformServe().setDeleted(0);
        serveInfo.getPlatformServe().setCreatedBy(serveInfo.getUserId());
        serveInfo.getPlatformServe().setCreatedTime(new Date());

        baseMapper.insert(serveInfo.getPlatformServe());

        addDetail(serveInfo.getDetailList(), serveInfo.getPlatformServe().getId());
    }

    /**
     * 修改
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateServe(PlatformServeDto obj) {
        PlatformServeServiceInfo serveInfo = getServeInfo(obj);
        serveInfo.getPlatformServe().setId(obj.getId());
        serveInfo.getPlatformServe().setUpdatedBy(serveInfo.getUserId());
        serveInfo.getPlatformServe().setUpdatedTime(new Date());
        baseMapper.updateByPrimaryKeySelective(serveInfo.getPlatformServe());

        platformServeDetailDao.deleteByServeId(obj.getId());

        addDetail(serveInfo.getDetailList(), obj.getId());
    }

    /**
     * 删除服务
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteServe(Integer id) {
        Optional.ofNullable(id).orElseThrow(() -> new BizException("服务Id不能为空！"));
        Integer userId = Optional.ofNullable(sysUserFeignService.queryUserInfo())
                .map(SysUser::getId)
                .orElseThrow(() -> new BizException("用户信息获取失败"));

        TenantProductInfo productInfo = tenantProductInfoService.getOne(new QueryWrapper<TenantProductInfo>()
                .eq("serve_id_", id));
        if (Objects.nonNull(productInfo)) {
            throw new BizException("该服务已关联机构无法删除！");
        }

        PlatformServe platformServe = new PlatformServe();
        platformServe.setId(id);
        platformServe.setDeleted(1);
        platformServe.setUpdatedBy(userId);
        platformServe.setUpdatedTime(new Date());
        baseMapper.updateByPrimaryKeySelective(platformServe);
    }

    /**
     * 分页查询
     *
     * @param search 关键字
     * @param page   页数
     * @param rows   查询数
     */
    @Override
    public PageInfo<PlatformServePageVo> queryPage(String search, Integer page, Integer rows) {
        Page<PlatformServePageVo> pageInfo = PageUtil.getPage(page, rows);
        pageInfo.setAsc("a.id_");
        IPage<PlatformServePageVo> pageData = baseMapper.queryPage(pageInfo, search,null);
        return PageUtil.pageInfo(pageData);
    }

    /**
     * 根据服务id查询关联的产品名称(名称用逗号分割)
     *
     * @param id
     */
    @Override
    public PlatformServePageVo queryProductNameById(Integer id) {
        return baseMapper.queryPage(null, id);
    }

    /**
     * 查询单个服务的详情
     *
     * @param id 服务id
     */
    @Override
    public PlatformServeInfoVo queryInfo(Integer id) {
        return baseMapper.queryInfo(id);
    }

    /**
     * 根据服务ID 查询付费模式和学员上限设置
     *
     * @param id 服务id
     */
    @Override
    public List<PlatformServeModeVo> queryModeDetail(Integer id) {
        return platformServeDetailDao.queryDetailById(id);
    }

    private PlatformServeServiceInfo getServeInfo(PlatformServeDto obj) {
        List<PlatformServeDetail> detailList = Optional.ofNullable(obj)
                .filter(o -> CollectionUtils.isNotEmpty(obj.getDetailList()))
                .map(PlatformServeDto::getDetailList)
                .orElseThrow(() -> new BizException("请填入服务详情"));

        Integer userId = Optional.ofNullable(sysUserFeignService.queryUserInfo())
                .map(SysUser::getId)
                .orElseThrow(() -> new BizException("用户信息获取失败"));
        PlatformServe platformServe = new PlatformServe();
        platformServe.setName(obj.getName());
        platformServe.setProductId(obj.getProductId());

        PlatformServeServiceInfo platformServeInfo = new PlatformServeServiceInfo();
        platformServeInfo.setDetailList(detailList);
        platformServeInfo.setUserId(userId);
        platformServeInfo.setPlatformServe(platformServe);
        return platformServeInfo;
    }

    static class PlatformServeServiceInfo implements Serializable {
        private List<PlatformServeDetail> detailList;

        private Integer userId;

        private PlatformServe platformServe;

        public List<PlatformServeDetail> getDetailList() {
            return detailList;
        }

        public void setDetailList(List<PlatformServeDetail> detailList) {
            this.detailList = detailList;
        }

        public Integer getUserId() {
            return userId;
        }

        public void setUserId(Integer userId) {
            this.userId = userId;
        }

        public PlatformServe getPlatformServe() {
            return platformServe;
        }

        public void setPlatformServe(PlatformServe platformServe) {
            this.platformServe = platformServe;
        }
    }

    private void addDetail(List<PlatformServeDetail> detailList, Integer id) {
        detailList.forEach(detail -> {
            detail.setServeId(id);
            platformServeDetailDao.insert(detail);
        });
    }

}
