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.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.client.UserServiceClient;
import com.diagbot.dto.DisclaimerInformationDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.DisclaimerInformation;
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.DisclaimerInformationServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.DisclaimerInformationAllVO;
import com.diagbot.vo.DisclaimerInformationIdVO;
import com.diagbot.vo.DisclaimerInformationVO;

/**
 * @author wangfeng
 * @Description: TODO
 * @date 2018年11月21日 下午4:25:48
 */
@Component
public class DisclaimerInformationFacade extends DisclaimerInformationServiceImpl {

    @Autowired
    UserServiceClient userServiceClient;

    
    /**
     * 分页查询免责声明
     * @param page
     * @param title
     * @return
     */
    public IPage<DisclaimerInformationDTO> getDisclaimerInformation(Page page, String title) {

        DisclaimerInformationAllVO disAll = new DisclaimerInformationAllVO();
        disAll.setTitle(title);
        IPage<DisclaimerInformationDTO> querDisclaimerInformation = getDisclaimerInformationAll(page, disAll);
        List<DisclaimerInformationDTO> data = querDisclaimerInformation.getRecords();

        List<String> modifierid = new ArrayList<>();
        modifierid = data.stream().map(ac -> ac.getModifier()).collect(Collectors.toList());

        Map<String, String> userNames = new HashMap<>();
        if (ListUtil.isNotEmpty(modifierid)) {
            RespDTO<Map<String, String>> userNamesDTO = userServiceClient.getUserInfoByIds(modifierid);
            if (userNamesDTO == null || !CommonErrorCode.OK.getCode().equals(userNamesDTO.code)) {
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                        "获取所有用户信息失败");
            }
            userNames = userNamesDTO.data;
        }


        List<DisclaimerInformationDTO> dataNew = new ArrayList<DisclaimerInformationDTO>();
        for (DisclaimerInformationDTO disclaimerInformationDTO : data) {
            DisclaimerInformationDTO dis = new DisclaimerInformationDTO();
            BeanUtil.copyProperties(disclaimerInformationDTO, dis);
            dis.setModifier(userNames.get(disclaimerInformationDTO.getModifier()));

            dataNew.add(dis);
        }
        return querDisclaimerInformation.setRecords(dataNew);
    }

    /**
     * 增加
     *
     * @return
     */
    public Boolean addDisclaimerInformation(DisclaimerInformationVO disclaimerInformationVO) {
    	//每一处免责声明（免责声明按钮、推送免责声明、诊断免责声明）同时最多可启用1条内容，显示（按操作时间）最新的条记录；新添加免责声明，则自动展示新添加的内容；自动开启，最近一条数据自动停用；
    	UpdateWrapper<DisclaimerInformation>  DisclaimerInformationStatus= new UpdateWrapper<>();
    	DisclaimerInformationStatus.eq("disclaimer_code",disclaimerInformationVO.getDisclaimerCode()).eq("is_deleted", IsDeleteEnum.N.getKey())
        .set("modifier", UserUtils.getCurrentPrincipleID())
        .set("gmt_modified", DateUtil.now()).set("status", StatusEnum.Disable.getKey());
    	
    	update(new DisclaimerInformation(), DisclaimerInformationStatus);
    	
        DisclaimerInformation disclaimerInformation = new DisclaimerInformation();
        disclaimerInformation.setCreator(UserUtils.getCurrentPrincipleID());
        disclaimerInformation.setModifier(UserUtils.getCurrentPrincipleID());
        disclaimerInformation.setDescription(disclaimerInformationVO.getDescription());
        disclaimerInformation.setDisclaimerCode(disclaimerInformationVO.getDisclaimerCode());
        disclaimerInformation.setGmtCreate(DateUtil.now());
        disclaimerInformation.setGmtModified(DateUtil.now());
        disclaimerInformation.setOrderNo(disclaimerInformationVO.getOrderNo());
        disclaimerInformation.setRemark(disclaimerInformationVO.getRemark());
        disclaimerInformation.setStatus(String.valueOf(StatusEnum.Enable.getKey()));
        disclaimerInformation.setTitle(disclaimerInformationVO.getTitle());
        //disclaimerInformation.setVersionId();

        boolean res = save(disclaimerInformation);

        return res;
    }

    /**
     * 修改
     *
     * @return
     */
    public Boolean updateDisclaimerInformation(DisclaimerInformationAllVO disclaimerInformationAllVO) {
        // 1.先判断数据是否存在有效
        checkExist(disclaimerInformationAllVO.getId());
        // 2.修改版本详情信息
        DisclaimerInformation disclaimerInformation = new DisclaimerInformation();

        disclaimerInformation.setGmtModified(DateUtil.now());// 修改时间
        disclaimerInformation.setModifier(UserUtils.getCurrentPrincipleID());
        disclaimerInformation.setDescription(disclaimerInformationAllVO.getDescription());
        disclaimerInformation.setDisclaimerCode(disclaimerInformationAllVO.getDisclaimerCode());
        disclaimerInformation.setGmtCreate(DateUtil.now());
        disclaimerInformation.setId(disclaimerInformationAllVO.getId());
        //disclaimerInformation.setOrderNo(disclaimerInformationAllVO.getOrderNo());
        //disclaimerInformation.setRemark(disclaimerInformationAllVO.getRemark());
        //disclaimerInformation.setStatus(String.valueOf(StatusEnum.Enable.getKey()));
        disclaimerInformation.setTitle(disclaimerInformationAllVO.getTitle());
        disclaimerInformation.setVersionId(0L);

        boolean res = updateById(disclaimerInformation);

        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }

        return res;
    }

    /**
     * 删除
     *
     * @return
     */
    public Boolean cancelDisclaimerInformation(DisclaimerInformationIdVO disclaimerInformationIdVO) {
        // 1.先判断数据是否存在有效
        checkExist(disclaimerInformationIdVO.getId());
        UpdateWrapper<DisclaimerInformation> disclaimerInformationNew = new UpdateWrapper<>();
        disclaimerInformationNew.in("id", disclaimerInformationIdVO.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 DisclaimerInformation(), disclaimerInformationNew);
    }

    /**
     * 启用
     *
     * @return
     */
    public boolean startDisclaimerInformations(DisclaimerInformationIdVO disclaimerInformationIdVO) {
        // 1.先判断数据是否存在有效
        checkExist(disclaimerInformationIdVO.getId());
        //每一处免责声明（免责声明按钮、推送免责声明、诊断免责声明）同时最多可启用1条内容，显示（按操作时间）最新的条记录；新添加免责声明，则自动展示新添加的内容；自动开启，最近一条数据自动停用；
      //  QueryWrapper<DisclaimerInformation> data = new QueryWrapper<DisclaimerInformation>();
       // data.in("id", disclaimerInformationIdVO.getId()).eq("is_deleted", IsDeleteEnum.N.getKey());
        DisclaimerInformation disclaimerInformation = getById(disclaimerInformationIdVO.getId());
        
        UpdateWrapper<DisclaimerInformation>  DisclaimerInformationStatus= new UpdateWrapper<>();
    	DisclaimerInformationStatus.eq("disclaimer_code",disclaimerInformation.getDisclaimerCode()).eq("is_deleted", IsDeleteEnum.N.getKey())
        .set("modifier", UserUtils.getCurrentPrincipleID())
        .set("gmt_modified", DateUtil.now()).set("status", StatusEnum.Disable.getKey());
    	
    	update(new DisclaimerInformation(), DisclaimerInformationStatus);
        
        UpdateWrapper<DisclaimerInformation> disclaimerInformationNew = new UpdateWrapper<>();
        disclaimerInformationNew.in("id", disclaimerInformationIdVO.getId()).eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("status", StatusEnum.Disable.getKey()).set("modifier", UserUtils.getCurrentPrincipleID())
                .set("gmt_modified", DateUtil.now()).set("status", StatusEnum.Enable.getKey());
        return update(new DisclaimerInformation(), disclaimerInformationNew);
    }

    /**
     * 停用
     *
     * @return
     */
    public boolean endDisclaimerInformations(DisclaimerInformationIdVO disclaimerInformationEndVO) {
        // 1.先判断数据是否存在有效
        checkExist(disclaimerInformationEndVO.getId());
        UpdateWrapper<DisclaimerInformation> disclaimerInformationNew = new UpdateWrapper<>();
        disclaimerInformationNew.in("id", disclaimerInformationEndVO.getId()).eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("status", StatusEnum.Enable.getKey()).set("modifier", UserUtils.getCurrentPrincipleID())
                .set("gmt_modified", DateUtil.now()).set("status", StatusEnum.Disable.getKey());
        return update(new DisclaimerInformation(), disclaimerInformationNew);
    }

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

}
