package com.diagbot.facade;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.diagbot.client.UserServiceClient;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.VersionDetailDTO;
import com.diagbot.entity.VersionDetail;
import com.diagbot.entity.VersionInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.StatusEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.VersionDetailServiceImpl;
import com.diagbot.service.impl.VersionInfoServiceImpl;
import com.diagbot.util.DateUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.VersionDetailIdVO;
import com.diagbot.vo.VersionDetailVO;
import com.diagbot.vo.VersionInfoAndDetailIdVO;

/**
 * 版本详情
 *
 * @author wangfeng
 * @Description: TODO
 * @date 2018年11月21日 上午11:38:40
 */
@Component
public class VersionDetailFacade extends VersionDetailServiceImpl {

    @Autowired
    VersionDetailServiceImpl versionDetailServiceImpl;
    @Autowired
    UserServiceClient userServiceClient;
    @Autowired
    VersionInfoServiceImpl versionInfoServiceImpl;

    /**
     * 根据版本id查询版本详情
     *
     * @param id
     * @return
     */
    public List<VersionDetailDTO> getById(Long id) {
        QueryWrapper<VersionDetail> versionDetailQuery = new QueryWrapper<>();

        versionDetailQuery.eq("is_deleted", IsDeleteEnum.N.getKey()).eq("STATUS", StatusEnum.Enable.getKey())
                .eq("version_id", id).orderByAsc("order_no");

        VersionDetail versionDetail = new VersionDetail();
        versionDetail.setVersionId(id);
        List<VersionDetail> datas = list(versionDetailQuery);
        // System.out.println("List<VersionDetail>==="+datas.toString());
        List<VersionDetailDTO> dataNew = new ArrayList<VersionDetailDTO>();
        // 过滤字段
        for (VersionDetail versionData : datas) {
            VersionDetailDTO versionDTO = new VersionDetailDTO();
            versionDTO.setId(versionData.getId());
            //versionDTO.setCreator(versionData.getCreator());
            versionDTO.setDescription(versionData.getDescription());
            versionDTO.setGmtCreate(versionData.getGmtCreate());
            versionDTO.setOrderNo(versionData.getOrderNo());
            versionDTO.setRemark(versionData.getRemark());
            versionDTO.setStatus(versionData.getStatus());
            versionDTO.setTitle(versionData.getTitle());
            versionDTO.setVersionId(versionData.getVersionId());
            dataNew.add(versionDTO);
        }
        return dataNew;

    }

    /**
     * 根据版本ids查询版本详情
     *
     * @param ids
     * @return
     */
    public List<VersionDetailDTO> getByIds(List<Long> ids) {
        QueryWrapper<VersionDetail> versionDetailQuery = new QueryWrapper<>();

        versionDetailQuery.eq("is_deleted", IsDeleteEnum.N.getKey()).eq("STATUS", StatusEnum.Enable.getKey())
                .in("version_id", ids).orderByAsc("order_no");

        List<VersionDetail> datas = list(versionDetailQuery);
        List<VersionDetailDTO> dataNew = new ArrayList<VersionDetailDTO>();
        List<String> modifierid = new ArrayList<>();
        modifierid = datas.stream().map(ac -> ac.getModifier()).collect(Collectors.toList());
        Map<String, String> userNames = new HashMap<>();
        if (modifierid.size() > 0) {
            RespDTO<Map<String, String>> userNamesDTO = userServiceClient.getUserInfoByIds(modifierid);
            if (userNamesDTO == null || !"0".equals(userNamesDTO.code)) {
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                        "获取所有用户信息失败");
            }
            userNames = userNamesDTO.data;
        }
		
		// 过滤字段
		for (VersionDetail versionData : datas) {
			VersionDetailDTO versionDTO = new VersionDetailDTO();
			versionDTO.setId(versionData.getId());
			//versionDTO.setCreator(versionData.getCreator());
			versionDTO.setModifierid(userNames.get(versionData.getModifier()));
			versionDTO.setDescription(versionData.getDescription());
			versionDTO.setGmtCreate(versionData.getGmtCreate());
			versionDTO.setOrderNo(versionData.getOrderNo());
			versionDTO.setRemark(versionData.getRemark());
			versionDTO.setStatus(versionData.getStatus());
			versionDTO.setTitle(versionData.getTitle());
			versionDTO.setVersionId(versionData.getVersionId());
			dataNew.add(versionDTO);
		}
        return dataNew;

    }

    /**
     * 更新接口
     *
     * @param versionDetailVO
     * @return
     */
    public boolean updateVersionDetail(VersionDetailVO versionDetailVO) {
        // 1.先判断数据是否存在有效
    	checkExist(versionDetailVO.getDetailId());
        // 2.修改版本详情信息
        VersionDetail versionDetail = new VersionDetail();

        versionDetail.setGmtModified(DateUtil.now());// 修改时间
        versionDetail.setModifier(UserUtils.getCurrentPrincipleID());
        versionDetail.setTitle(versionDetailVO.getTitle());
        versionDetail.setOrderNo(versionDetailVO.getOrderNo());
        versionDetail.setStatus(versionDetailVO.getStatus());
        versionDetail.setId(versionDetailVO.getDetailId());
        versionDetail.setDescription(versionDetailVO.getDescription());
        versionDetail.setRemark(versionDetailVO.getRemark());
        boolean res = updateById(versionDetail);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }

        return res;
    }

    /**
     * 删除接口
     *
     * @param versionDetailIdVO
     * @return
     */
    public boolean cancelVersionDetail(VersionDetailIdVO versionDetailIdVO) {
    	 // 1.先判断数据是否存在有效
    	checkExist(versionDetailIdVO.getId());
        UpdateWrapper<VersionDetail> versionDetailNew = new UpdateWrapper<>();
        versionDetailNew.in("id", versionDetailIdVO.getId()).eq("is_deleted", IsDeleteEnum.N.getKey()).set("is_deleted",
                IsDeleteEnum.Y.getKey()).set("modifier", UserUtils.getCurrentPrincipleID()).set("gmt_modified", DateUtil.now());
        return update(new VersionDetail(), versionDetailNew);
    }

    /**
     * 增加明细接口
     *
     * @param versionDetailIdVO
     * @return
     */
    public boolean addVersionDetail(VersionInfoAndDetailIdVO versionInfoAndDetailIdVO) {

    	//1.增加明细前先判断主版本号的id是否有效
        QueryWrapper<VersionInfo> VersionInfoFand = new QueryWrapper<>();
        VersionInfoFand.eq("is_deleted", IsDeleteEnum.N.getKey()).eq("id", versionInfoAndDetailIdVO.getVersionInfoId());
        int sum = versionInfoServiceImpl.count(VersionInfoFand);
        if (sum == 0) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "主版本号数据不存在");
        }
        
        List<VersionDetail> dataNew = new ArrayList<VersionDetail>();
        List<VersionDetailVO> datas = versionInfoAndDetailIdVO.getVersionDetail();
        for (VersionDetailVO data : datas) {
            VersionDetail versionDetail = new VersionDetail();
            versionDetail.setCreator(UserUtils.getCurrentPrincipleID());
            versionDetail.setGmtCreate(DateUtil.now());
            versionDetail.setGmtModified(DateUtil.now());
            versionDetail.setModifier(UserUtils.getCurrentPrincipleID());
            versionDetail.setDescription(data.getDescription());
            versionDetail.setOrderNo(data.getOrderNo());
            versionDetail.setTitle(data.getTitle());
            versionDetail.setVersionId(versionInfoAndDetailIdVO.getVersionInfoId());
            versionDetail.setRemark(data.getRemark());
            versionDetail.setStatus(String.valueOf(StatusEnum.Enable.getKey()));
            dataNew.add(versionDetail);

        }

        boolean res = versionDetailServiceImpl.saveBatch(dataNew);

        return res;
    }
    /**
     * 判断数据是否存在有效
     *
     * @param id
     */
    private void checkExist(Long id) {
    	 // 1.先判断数据是否存在有效
    	 QueryWrapper<VersionDetail> VersionInfoFand = new QueryWrapper<>();
         VersionInfoFand.eq("is_deleted", IsDeleteEnum.N.getKey()).eq("id", id);
         int sum = count(VersionInfoFand);
         if (sum == 0) {
             throw new CommonException(CommonErrorCode.NOT_EXISTS, "该数据不存在");
         }
    }
}
