package com.mvc.service.alarm;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.dao.TAlarmSubscriptionDetailMapper;
import com.mvc.dao.TAlarmSubscriptionMapper;
import com.mvc.entity.TAlarmSubscription;
import com.mvc.entity.TAlarmSubscriptionDetail;
import com.mvc.entity.TAlarmSubscriptionDetailExample;
import com.mvc.entity.TAlarmSubscriptionExample;
import com.mvc.model.ResPageModel;
import com.mvc.model.alarm.TAlarmSubscriptionModel;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 报警订阅管理
 */
@Service
@Transactional
public class TAlarmSubscriptionService {
    @Resource
    private TAlarmSubscriptionMapper tAlarmSubscriptionMapper;

    @Resource
    private TAlarmSubscriptionDetailMapper alarmSubscriptionDetailMapper;

    /**
     * 查询报警订阅列表
     *
     * @param queryModel
     * @return
     */
    public ResPageModel findAllTAlarmSubscription(TAlarmSubscriptionModel queryModel) {
        TAlarmSubscriptionExample example = new TAlarmSubscriptionExample();
        TAlarmSubscriptionExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getRulesName())) {
            criteria.andRulesNameLike(StringUtil.getLikeFormat(queryModel.getRulesName()));
        }
        if (StringUtils.isNotEmpty(queryModel.getEmailAddress())) {
            criteria.andEmailAddressLike(StringUtil.getLikeFormat(queryModel.getEmailAddress()));
        }
        if (StringUtils.isNotEmpty(queryModel.getPhoneNumber())) {
            criteria.andPhoneNumberLike(StringUtil.getLikeFormat(queryModel.getPhoneNumber()));
        }
        if (StringUtils.isNotEmpty(queryModel.getCreateMan())) {
            criteria.andCreateManLike(StringUtil.getLikeFormat(queryModel.getCreateMan()));
        }
        if (StringUtils.isNotEmpty(queryModel.getQueryUserType()) && !queryModel.getQueryUserType().equals("0")) {
            criteria.andUnitCodeEqualTo(queryModel.getUnitCode());
        }
        if (queryModel.getUseFlag() != null) {
            criteria.andUseFlagEqualTo(queryModel.getUseFlag());
        }

        example.setOrderByClause(" CREATE_TIME desc");
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPageNum(), queryModel.getPageSize());
        List<TAlarmSubscriptionModel> resList = findAlarmSubscriptionsByExample(example, true);

        ResPageModel pageModel = new ResPageModel(resList, pageObject);
        return pageModel;
    }

    /**
     * 根据Example查询报警订阅列表
     *
     * @param example
     * @param isFindDetails
     * @return
     */
    public List<TAlarmSubscriptionModel> findAlarmSubscriptionsByExample(TAlarmSubscriptionExample example, boolean isFindDetails) {
        List<TAlarmSubscription> TAlarmSubscriptions = tAlarmSubscriptionMapper.selectByExample(example);
        List<TAlarmSubscriptionModel> resList = new ArrayList<>();
        for (TAlarmSubscription TAlarmSubscription : TAlarmSubscriptions) {
            TAlarmSubscriptionModel model = new TAlarmSubscriptionModel();
            BeanUtils.copyProperties(TAlarmSubscription, model);
            if (isFindDetails) {
                model.setDetails(findTAlarmSubscriptionDetailsById(model.getId()));
            }
            model.setDurationHours(TAlarmSubscription.getDurationHours() / 24);//前台是天数,数据库是小时
            resList.add(model);
        }
        return resList;
    }

    /**
     * 保存报警订阅
     *
     * @param model
     * @return
     */
    public TAlarmSubscriptionModel saveTAlarmSubscription(TAlarmSubscriptionModel model) {
        model.setCreateTime(new Date());
        model.setDurationHours(model.getDurationHours() * 24);//前台是天数，数据库是小时
        TAlarmSubscription alarmNotice = new TAlarmSubscription();
        BeanUtils.copyProperties(model, alarmNotice);
        int insert = tAlarmSubscriptionMapper.insert(alarmNotice);
        model.setId(alarmNotice.getId());
        if (insert > 0) {
            saveDetails(alarmNotice.getId(), model.getDetails());
        }
        return model;
    }

    /**
     * 保存明细列表
     *
     * @param details
     */
    private void saveDetails(int parentId, List<TAlarmSubscriptionDetail> details) {
        if (details == null || details.size() == 0) return;
        for (TAlarmSubscriptionDetail detail : details) {
            detail.setParentId(parentId);
            alarmSubscriptionDetailMapper.insert(detail);
        }
    }

    /**
     * 更新报警订阅
     *
     * @param model
     * @return
     */
    public TAlarmSubscriptionModel updateTAlarmSubscription(TAlarmSubscriptionModel model) {
        TAlarmSubscription alarmNotice = tAlarmSubscriptionMapper.selectByPrimaryKey(model.getId());
        model.setDurationHours(model.getDurationHours() * 24);//前台是天数，数据库是小时
        BeanUtils.copyProperties(model, alarmNotice);
        int i = tAlarmSubscriptionMapper.updateByPrimaryKey(alarmNotice);
        if (i > 0) {
            //更新时,统一删除掉明细,再重新添加
            deleteDetailByParentId(model.getId());
            saveDetails(alarmNotice.getId(), model.getDetails());
        }
        return model;
    }

    /**
     * 删除报警订阅
     *
     * @param id
     * @return
     */
    public int deleteTAlarmSubscription(int id) {
        int i = tAlarmSubscriptionMapper.deleteByPrimaryKey(id);
        if (i > 0) {
            deleteDetailByParentId(id);
        }
        return i;
    }

    /**
     * 根据父ID删除明细
     *
     * @param parentId
     * @return
     */
    private int deleteDetailByParentId(int parentId) {
        TAlarmSubscriptionDetailExample example = new TAlarmSubscriptionDetailExample();
        example.createCriteria().andParentIdEqualTo(parentId);
        return alarmSubscriptionDetailMapper.deleteByExample(example);
    }

    /**
     * 根据父ID获取明细列表
     *
     * @param parentId
     * @return
     */
    private List<TAlarmSubscriptionDetail> findTAlarmSubscriptionDetailsById(int parentId) {
        TAlarmSubscriptionDetailExample example = new TAlarmSubscriptionDetailExample();
        example.createCriteria().andParentIdEqualTo(parentId);
        return alarmSubscriptionDetailMapper.selectByExample(example);
    }

    /**
     * 根据ID获取对象
     *
     * @param id
     * @return
     */
    public TAlarmSubscriptionModel findTAlarmSubscriptionModelById(int id) {
        TAlarmSubscription alarmNotice = tAlarmSubscriptionMapper.selectByPrimaryKey(id);
        if (alarmNotice != null) {
            TAlarmSubscriptionModel model = new TAlarmSubscriptionModel();
            BeanUtils.copyProperties(alarmNotice, model);
        }
        return null;
    }

    /**
     * 查询所有明细
     *
     * @return
     */
    public List<TAlarmSubscriptionDetail> findAllTAlarmSubscriptionDetail() {
        return alarmSubscriptionDetailMapper.selectByExample(null);
    }

    /**
     * 校验报警订阅信息
     *
     * @param model
     * @return
     */
    public String checkAlarmSubscription(TAlarmSubscriptionModel model) {
        if (StringUtils.isEmpty(model.getPhoneNumber()) && StringUtils.isEmpty(model.getEmailAddress())) {
            return "手机号码和邮箱地址不能同时为空";
        }

        if (StringUtils.isNotEmpty(model.getPhoneNumber())) {
            if (!StringUtil.isValidPhoneNumber(model.getPhoneNumber())) {
                return "手机号码格式不正确";
            } else {
                String[] array = model.getPhoneNumber().split(";");
                if (array.length > 3) {
                    return "最多只能输入3个手机号码";
                }
            }
        }

        if (StringUtils.isNotEmpty(model.getEmailAddress())) {
            if (!StringUtil.isValidEmail(model.getEmailAddress())) {
                return "邮箱地址格式不正确";
            } else {
                String[] array = model.getEmailAddress().split(";");
                if (array.length > 3) {
                    return "最多只能输入3个邮箱地址";
                }
            }
        }

        if (model.getDurationHours() == null || model.getDurationHours() == 0) {
            return "持续天数不能为空或0";
        }

        return null;
    }
}
