package com.community.huiju.service.impl;

import com.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.huiju.dao.SysDictionaryMapper;
import com.community.huiju.dao.ToBannerMapper;
import com.community.huiju.dao.ToCommunitiesMapper;
import com.community.huiju.dao.ToUserMapper;
import com.community.huiju.model.SysDictionary;
import com.community.huiju.model.ToBanner;
import com.community.huiju.model.ToCommunities;
import com.community.huiju.model.ToUser;
import com.community.huiju.service.IToBannerService;
import com.community.huiju.vo.ToBannerVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * banner 业务
 * @author weiximei
 */
@Service("iToBannerService")
public class ToBannerServiceImpl implements IToBannerService {

    @Autowired
    private ToBannerMapper toBannerMapper;

    @Autowired
    private ToUserMapper toUserMapper;

    @Autowired
    private ToCommunitiesMapper toCommunitiesMapper;

    @Autowired
    private SysDictionaryMapper sysDictionaryMapper;

    /**
     * 校验 url 合法性
     */
    private Pattern patternUrl = Pattern.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addBanner(ToBanner banner,Integer currentUserId) {

        ResponseBean response = new ResponseBean();
        if (Constant.BANNER_TYPE_ARTICLE.equals(banner.getBannerType())) {
            if (StringUtils.isBlank(banner.getBannerTitle())) {
                response.addError("Banner内容标题不能为空");
                return response;
            }
            if (StringUtils.isBlank(banner.getBannerContent())) {
                response.addError("Banner内容不能为空");
                return response;
            }
        }else {
            if (StringUtils.isBlank(banner.getExternalLink())) {
                response.addError("跳转链接不能为空");
                return response;
            }
            if (!patternUrl.matcher(banner.getExternalLink()).matches()) {
                response.addError("请输入合法的跳转链接!");
                return response;
            }
        }

        Date effTime = banner.getEffTime();
        Date currentDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatCurrentDate = simpleDateFormat.format(currentDate);
        try {
            currentDate = simpleDateFormat.parse(formatCurrentDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (effTime.getTime() < currentDate.getTime()) {
            response.addError("生效时间不能小于当前时间!");
            return response;
        }

        Date expTime = banner.getExpTime();
        if (expTime.getTime() <= effTime.getTime()) {
            response.addError("失效时间不能小于或等于生效时间!");
            return response;
        }

        ToUser toUser = toUserMapper.selectByPrimaryKey(currentUserId);

        banner.setCreateDate(new Date());
        banner.setCreateUser(toUser.getId());
        banner.setUpdateDate(new Date());
        banner.setUpdateUser(toUser.getId());

        int result = toBannerMapper.insertSelective(banner);
        if (result > 0) {
            response.addSuccess("添加成功!");
        }

        return response;
    }


    @Override
    public ResponseBean getById(Integer bannerId) {

        ResponseBean response = new ResponseBean();
        ToBanner toBanner = toBannerMapper.selectByPrimaryKey(bannerId);

        response.addSuccess(toBanner);

        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modifyBanner(ToBanner banner,Integer currentUserId) {
        ResponseBean response = new ResponseBean();

        ToBanner selectBanner = toBannerMapper.selectByPrimaryKey(banner.getId());

        if (Constant.BANNER_TYPE_ARTICLE.equals(banner.getBannerType())) {
            if (StringUtils.isBlank(banner.getBannerTitle())) {
                response.addError("Banner内容标题不能为空");
                return response;
            }
            if (StringUtils.isBlank(banner.getBannerContent())) {
                response.addError("Banner内容不能为空");
                return response;
            }
        }else {
            if (StringUtils.isBlank(banner.getExternalLink())) {
                response.addError("跳转URL不能为空");
                return response;
            }
            if (!patternUrl.matcher(banner.getExternalLink()).matches()) {
                response.addError("请输入合法的跳转链接!");
                return response;
            }
        }

        Date effTime = banner.getEffTime();
        Date currentDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatCurrentDate = simpleDateFormat.format(currentDate);
        try {
            currentDate = simpleDateFormat.parse(formatCurrentDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (effTime.getTime() < currentDate.getTime()) {
            response.addError("生效时间不能小于当前时间!");
            return response;
        }

        Date expTime = banner.getExpTime();
        if (expTime.getTime() <= effTime.getTime()) {
            response.addError("失效时间不能小于或等于生效时间!");
            return response;
        }

        ToUser toUser = toUserMapper.selectByPrimaryKey(currentUserId);

        BeanUtils.copyProperties(banner,selectBanner);

        selectBanner.setUpdateDate(new Date());
        selectBanner.setUpdateUser(toUser.getId());

        int result = toBannerMapper.updateByPrimaryKeySelective(banner);
        if (result > 0) {
            response.addSuccess("修改成功!");
            return response;
        }

        return response;
    }

    @Override
    public ResponseBean getBanner(ToBanner banner,Integer pageNum, Integer pageSize) {
        
        ResponseBean response = new ResponseBean();

        Page<ToBanner> page = PageHelper.startPage(pageNum,pageSize);
        List<ToBanner> bannerList = toBannerMapper.selectBanner(banner);

        List<ToBannerVO> bannerVOList = bannerList.stream().map(e->{
            ToBannerVO toBannerVO = new ToBannerVO();
            BeanUtils.copyProperties(e,toBannerVO);

            ToCommunities toCommunities = toCommunitiesMapper.selectByPrimaryKey(e.getCommunityId());
            toBannerVO.setCommunityName(toCommunities.getCommunityName());

            // TODO banner位置名称
            //SysDictionary sysDictionary = sysDictionaryMapper.selectByPrimaryKey(e.getBannerPosition());
            //toBannerVO.setBannerPositionName(sysDictionary.getName());
            toBannerVO.setBannerPositionName(e.getBannerPosition() == 1?"首页banner": e.getBannerPosition() == 2 ? "服务banner" : "广告banner");

            ToUser toUser = toUserMapper.selectByPrimaryKey(e.getUpdateUser());
            if (null != toUser) {
                toBannerVO.setUpdateUserName(toUser.getUserName());
            }

            return toBannerVO;

        }).collect(Collectors.toList());

        Map<String,Object> map = Maps.newHashMap();
        map.put("item",bannerVOList);
        map.put("total",page.getTotal());
        response.addSuccess(map);

        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean deleteBanner(Integer bannerId) {

        ResponseBean response = new ResponseBean();
        ToBanner toBanner = toBannerMapper.selectByPrimaryKey(bannerId);
        if (toBanner == null) {
            response.addError("banner不存在!");
            return response;
        }

        int result = toBannerMapper.deleteByPrimaryKey(bannerId);
        if (result > 0) {
            response.addSuccess("操作成功!");
        } else {
            response.addError("操作失败!");
        }

        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean deleteBanner(List<Integer> listBannerId) {
        ResponseBean responseBean = new ResponseBean();
        if (listBannerId.isEmpty() || listBannerId.size() == 0) {
            responseBean.addError("请选择需要删除的数据!");
            return responseBean;
        }
        int rows = toBannerMapper.deleteBanchBanner(listBannerId);
        if (rows > 0) {
            responseBean.addSuccess("操作成功!");
            return responseBean;
        }
        responseBean.addError("操作失败!");
        return responseBean;
    }
}
