package com.dxhy.admin.sys.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.admin.sys.config.SysConfig;
import com.dxhy.admin.sys.dao.SysTabulateDao;
import com.dxhy.admin.sys.entity.SysTabulateDeptEntity;
import com.dxhy.admin.sys.entity.SysTabulateEntity;
import com.dxhy.admin.sys.model.TabulateMenuModel;
import com.dxhy.admin.sys.model.TabulateModel;
import com.dxhy.admin.sys.service.SysTabulateDeptService;
import com.dxhy.admin.sys.service.SysTabulateService;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.RedisConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.util.redis.RedisUtils;
import com.dxhy.common.utils.Aops;
import com.dxhy.common.utils.PageUtils;
import com.dxhy.common.utils.Query;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang（焦红阳）
 * @date 2020-09-22
 */
@Service("sysTabulateService")
@Slf4j
public class SysTabulateServiceImpl extends ServiceImpl<SysTabulateDao, SysTabulateEntity>
    implements SysTabulateService {
    @Resource
    private SysTabulateDeptService sysTabulateDeptService;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public int saveTablate(String dataList) {
        SysTabulateDeptEntity tabulateDeptEntity;
        List<SysTabulateDeptEntity> tabulateDeptList = new ArrayList<>();
        try {
            TabulateModel tabulateModel = JSON.parseObject(dataList, TabulateModel.class);
            List<SysTabulateEntity> sysTabulateEntities = tabulateModel.getDomains();
            if (sysTabulateEntities.size() > 0) {
                for (SysTabulateEntity tabulateEntity : sysTabulateEntities) {
                    tabulateEntity.setMenuId(Long.parseLong(tabulateModel.getMenuId()));
                    tabulateEntity.setCreateDate(DateUtil.date());
                    tabulateEntity.setInputFixed(tabulateModel.isIndexType());
                    tabulateEntity.setSelection(tabulateModel.isSelection());
                    int tabulateCount =
                        this.getTablateCount(tabulateEntity.getMenuCode(), String.valueOf(tabulateEntity.getMenuId()),
                            tabulateEntity.getTabulateName(), tabulateEntity.getTabulateCode());
                    if (tabulateCount > 0) {
                        return 2;
                    }
                }
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                Aops.getSelf(this).insertTablate(sysTabulateEntities);

                List<SysTabulateEntity> tablates =
                    getTablate(null, String.valueOf(sysTabulateEntities.get(0).getMenuId()), null, null, false);
                if (tablates.size() > 0) {
                    redisUtils.set(RedisConstant.MENU_TABULATE + sysTabulateEntities.get(0).getMenuId(),
                        JSON.toJSONString(tablates), RedisUtils.NOT_EXPIRE);
                }
                for (SysTabulateEntity tabulateEntity : tablates) {
                    if (tabulateEntity.isDefaultStatus()) {
                        tabulateDeptEntity = new SysTabulateDeptEntity();
                        tabulateDeptEntity.setCompany(SysConfig.ZXQY);
                        tabulateDeptEntity.setMenuId(tabulateEntity.getMenuId());
                        tabulateDeptEntity.setTabulateName(tabulateEntity.getTabulateName());
                        tabulateDeptEntity.setTabulateCode(tabulateEntity.getTabulateCode());
                        tabulateDeptEntity.setTabulateId(tabulateEntity.getId());
                        tabulateDeptEntity.setOrderNum(tabulateEntity.getOrderNum());
                        tabulateDeptEntity.setCreateDate(DateUtil.date());
                        tabulateDeptEntity.setUpdateDate(DateUtil.date());
                        tabulateDeptEntity.setShowStatus(tabulateEntity.isShowStatus());
                        tabulateDeptList.add(tabulateDeptEntity);
                    }

                }
                if (tabulateDeptList.size() > 0) {
                    sysTabulateDeptService.saveTablateDept(tabulateDeptList, "tabulate");
                }
                return 1;
            } else {
                return 4;
            }
        } catch (Exception e) {
            log.error("保存显示列表异常，异常信息：{}", e.toString());
            e.printStackTrace();
            return 3;
        }
    }

    @Override
    public int getTablateCount(String menuCode, String menuId, String tabulateName, String tabulateCode) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return Math.toIntExact(this.count(new QueryWrapper<SysTabulateEntity>().eq("menu_id", menuId)
                .eq(StringUtils.isNotBlank(menuCode), "menu_code", menuCode)
                .eq(StringUtils.isNotBlank(tabulateName), "tabulate_name", tabulateName)
                .eq(StringUtils.isNotBlank(tabulateCode), "tabulate_code", tabulateCode)));
    }

    @Override
    public int updateTablate(SysTabulateEntity sysTabulateEntity) {
        SysTabulateDeptEntity tabulateDeptEntity;
        List<SysTabulateDeptEntity> tabulateDeptList = new ArrayList<>();
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        sysTabulateEntity.setUpdateDate(DateUtil.date());
        try {

            Aops.getSelf(this).updateTablateTr(sysTabulateEntity);

            List<SysTabulateEntity> tablates =
                getTablate(null, String.valueOf(sysTabulateEntity.getMenuId()), null, null, false);

            if (tablates.size() > 0) {
                redisUtils.set(RedisConstant.MENU_TABULATE + sysTabulateEntity.getMenuId(), JSON.toJSONString(tablates),
                    RedisUtils.NOT_EXPIRE);
            }

            for (SysTabulateEntity tabulateEntity : tablates) {
                if (tabulateEntity.isDefaultStatus()) {
                    tabulateDeptEntity = new SysTabulateDeptEntity();
                    tabulateDeptEntity.setCompany(SysConfig.ZXQY);
                    tabulateDeptEntity.setMenuId(tabulateEntity.getMenuId());
                    tabulateDeptEntity.setTabulateName(tabulateEntity.getTabulateName());
                    tabulateDeptEntity.setTabulateCode(tabulateEntity.getTabulateCode());
                    tabulateDeptEntity.setTabulateId(tabulateEntity.getId());
                    tabulateDeptEntity.setOrderNum(tabulateEntity.getOrderNum());
                    tabulateDeptEntity.setCreateDate(DateUtil.date());
                    tabulateDeptEntity.setUpdateDate(DateUtil.date());
                    tabulateDeptEntity.setShowStatus(tabulateEntity.isShowStatus());
                    tabulateDeptList.add(tabulateDeptEntity);
                }
            }
            if (tabulateDeptList.size() > 0) {
                sysTabulateDeptService.saveTablateDept(tabulateDeptList, "tabulate");
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改保存显示列表异常，异常信息：{}", e.toString());
            return 3;
        }
    }

    @Override
    public int deleteTabulate(long tabulateId) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        try {
            Aops.getSelf(this).deleteTabulateTr(tabulateId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除显示列表异常，异常信息：{}", e.toString());
            return 2;
        }

    }

    @Override
    public List<SysTabulateEntity> getTablate(String menuCode, String menuId, String tabulateName, String tabulateCode,
        boolean defaultStatus) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.selectList(new QueryWrapper<SysTabulateEntity>().eq("menu_id", menuId)
            .eq(StringUtils.isNotBlank(menuCode), "menu_code", menuCode)
            .eq(StringUtils.isNotBlank(tabulateName), "tabulate_name", tabulateName)

            .eq(StringUtils.isNotBlank(tabulateCode), "tabulate_code", tabulateCode)
            .eq(defaultStatus, "default_status", defaultStatus).orderByAsc("order_num"));
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        String menuId = (String)params.get("menuId");
        String menuCode = (String)params.get("menuCode");
        String tabulateName = (String)params.get("tabulateName");
        String tabulateCode = (String)params.get("tabulateCode");
        IPage<SysTabulateEntity> page = this.page(new Query<SysTabulateEntity>().getPage(params),
            new QueryWrapper<SysTabulateEntity>().eq("menu_id", menuId)
                .eq(StringUtils.isNotBlank(menuCode), "menu_code", menuCode)
                .eq(StringUtils.isNotBlank(tabulateName), "tabulate_name", tabulateName)
                .eq(StringUtils.isNotBlank(tabulateCode), "tabulate_code", tabulateCode).orderByAsc("order_num"));
        List<SysTabulateEntity> records = page.getRecords();
        if (records.size() > 0) {
            for (SysTabulateEntity entity : records) {
                if ("1".equals(entity.getType())) {
                    entity.setTypeName("列表");
                } else if ("2".equals(entity.getType())) {
                    entity.setTypeName("按钮");
                } else if ("3".equals(entity.getType())) {
                    entity.setTypeName("excel");
                }

                if (entity.isDefaultStatus()) {
                    entity.setDefaultStatusName("是");
                } else {
                    entity.setDefaultStatusName("否");
                }

                if (entity.isInputFixed()) {
                    entity.setInputFiledName("是");
                } else {
                    entity.setInputFiledName("否");
                }

                if (entity.isShowOverflowTooltip()) {
                    entity.setShowOverflowTooltipName("是");
                } else {
                    entity.setShowOverflowTooltipName("否");
                }

                if (entity.isIconFixed()) {
                    entity.setIconFixedName("是");
                } else {
                    entity.setIconFixedName("否");
                }

                if (entity.isShowStatus()) {
                    entity.setShowStatusName("是");
                } else {
                    entity.setShowStatusName("否");
                }
                if (entity.isSortable()) {
                    entity.setSortableName("是");
                } else {
                    entity.setSortableName("否");
                }
            }
        }
        return new PageUtils(page);
    }

    @Override
    public boolean cancel(Map<String, Object> params, String type) {
        String menuId = (String)params.get("menuId");
        try {
            List<SysTabulateEntity> tablateList = this.getTablate("", menuId, "", "", false);
            for (SysTabulateEntity tabulateEntity : tablateList) {
                if ("selection".equals(type)) {
                    tabulateEntity.setSelection(false);
                } else if ("indexType".equals(type)) {
                    tabulateEntity.setIndexType(false);
                }
            }
            DynamicContextHolder.push(DbConstant.BASICS_WRITE);
            this.updateTablateList(tablateList);
            return true;
        } catch (Exception e) {
            log.error("异常，{}", e.getMessage());
            return false;
        }

    }

    @Override
    public void updateTabulateMenuId(List<TabulateMenuModel> menuIdModels) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Aops.getSelf(this).updateTabulateMenuIdTran(menuIdModels);
        // 获取根据菜单id 获取显示列表信息，并重新创建显示列表信息

        Aops.getSelf(this).updateTabulateDeptMenuIdTran(menuIdModels);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateTabulateMenuIdTran(List<TabulateMenuModel> menuIdModels) {
        baseMapper.updateTabulateMenuIdTran(menuIdModels);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateTabulateDeptMenuIdTran(List<TabulateMenuModel> menuIdModels) {
        baseMapper.updateTabulateDeptMenuIdTran(menuIdModels);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteTabulateTr(long tabulateId) {
        this.removeById(tabulateId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateTablateTr(SysTabulateEntity sysTabulateEntity) {
        this.updateById(sysTabulateEntity);

    }

    @Transactional(rollbackFor = Exception.class)
    public void updateTablateList(List<SysTabulateEntity> tablateList) {
        this.updateBatchById(tablateList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertTablate(List<SysTabulateEntity> tabulateEntityList) {
        this.saveBatch(tabulateEntityList);
    }

}
