package com.mosty.common.core.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.mosty.common.base.constant.enums.DeletedEnum;
import com.mosty.common.base.exception.Asserts;
import com.mosty.common.core.business.entity.*;
import com.mosty.common.core.business.entity.request.SysAppHomeconfigQuery;
import com.mosty.common.core.business.entity.request.SysUserAppHomeconfigPage;
import com.mosty.common.core.business.entity.request.SysUserAppHomeconfigQuery;
import com.mosty.common.core.business.entity.vo.*;
import com.mosty.common.core.business.mapper.*;
import com.mosty.common.core.business.service.SysAppHomeconfigService;
import com.mosty.common.core.business.service.SysUserAppHomeconfigPlateListService;
import com.mosty.common.core.business.service.SysUserAppHomeconfigPlateService;
import com.mosty.common.core.business.service.SysUserAppHomeconfigService;
import com.mosty.common.token.UserInfo;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 用户app首页配置表 服务实现类
 * </p>
 *
 * @author zengbo
 * @since 2022-08-18
 */
@Service
public class SysUserAppHomeconfigServiceImpl extends ServiceImpl<SysUserAppHomeconfigMapper, SysUserAppHomeconfig> implements SysUserAppHomeconfigService {

    private static final Logger log = LoggerFactory.getLogger(SysUserAppHomeconfigServiceImpl.class);

    @Resource
    private SysUserAppHomeconfigMapper sysUserAppHomeconfigMapper;

    @Resource
    private SysUserAppHomeconfigPlateMapper sysUserAppHomeconfigPlateMapper;

    @Resource
    private SysUserAppHomeconfigPlateListMapper sysUserAppHomeconfigPlateListMapper;

    @Resource
    private SysAppHomeconfigService sysAppHomeconfigService;

    @Resource
    private SysUserAppHomeconfigPlateService sysUserAppHomeconfigPlateService;

    @Resource
    private SysUserAppHomeconfigPlateListService sysUserAppHomeconfigPlateListService;


    @Override
    public Long saveInfo(SysUserAppHomeconfig config, String ipAddress) {
        config.setXtCjsj(new Date());
        config.setXtLrip(ipAddress);
        config.setXtLrsj(new Date());
        config.setXtZhxgsj(new Date());
        config.setXtZxbz(DeletedEnum.NATURE.code);
        sysUserAppHomeconfigMapper.insert(config);
        return config.getId();
    }

    @Override
    public void saveInfoBatch(List<SysUserAppHomeconfig> configs, String ipAddress) {
        if (!CollectionUtils.isEmpty(configs)) {
            for (SysUserAppHomeconfig config : configs) {
                config.setXtCjsj(new Date());
                config.setXtLrip(ipAddress);
                config.setXtLrsj(new Date());
                config.setXtZhxgsj(new Date());
                config.setXtZxbz(DeletedEnum.NATURE.code);
                sysUserAppHomeconfigMapper.insert(config);
            }
        }
    }

    @Override
    public void updateInfo(SysUserAppHomeconfig config, String ipAddress) {
        SysUserAppHomeconfig oldConfig = sysUserAppHomeconfigMapper.selectById(config.getId());
        Asserts.check(oldConfig == null, "主键为 %s 的信息不存在", config.getId());
        config.setXtZxbz(DeletedEnum.NATURE.code);
        config.setXtZhxgsj(new Date());
        config.setXtLrip(ipAddress);
        sysUserAppHomeconfigMapper.updateById(config);
    }

    @Override
    public void updateInfoBatch(List<SysUserAppHomeconfig> configs, String ipAddress) {
        if (!CollectionUtils.isEmpty(configs)) {
            String sfzh = configs.get(0).getUserSfzh();
            sysUserAppHomeconfigMapper.deleteBySfzh(sfzh);
            for (SysUserAppHomeconfig config : configs) {
                config.setXtZhxgsj(new Date());
                config.setXtCjsj(new Date());
                config.setXtLrip(ipAddress);
                config.setXtLrsj(new Date());
                config.setXtZhxgsj(new Date());
                config.setXtZxbz(DeletedEnum.NATURE.code);
                sysUserAppHomeconfigMapper.insert(config);
            }
        }
    }

    @Override
    public void delete(List<Long> list, String ipAddress, UserInfo userInfo) {
        if (!CollectionUtils.isEmpty(list)) {
            for (Long id : list) {
                SysUserAppHomeconfig config = sysUserAppHomeconfigMapper.selectById(id);
                if (config != null) {
                    config.setXtZhxgsj(new Date());
                    config.setXtZxbz(DeletedEnum.DELETED.code);
                    config.setXtZhxgsj(new Date());
                    config.setXtZhxgip(ipAddress);
                    if (userInfo != null) {
                        config.setXtZhxgrxm(userInfo.getUserName());
                        config.setXtZhxgrbmid(userInfo.getDeptId() + "");
                        config.setXtZhxgrbm(userInfo.getDeptName());
                    }
                    sysUserAppHomeconfigMapper.updateById(config);
                }
            }
        }
    }

    @Override
    public IPage<SysUserAppHomeconfig> selectByPage(SysUserAppHomeconfigPage cofigPage) {
        QueryWrapper<SysUserAppHomeconfig> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(cofigPage.getHomename())) {
            queryWrapper.and(wrapper -> wrapper.like("homename", cofigPage.getHomename()));
        }
        if (cofigPage.getHomeid() != null) {
            queryWrapper.and(wrapper -> wrapper.eq("homeid", cofigPage.getHomeid()));
        }
        if (cofigPage.getUserId() != null) {
            queryWrapper.and(wrapper -> wrapper.eq("user_id", cofigPage.getUserId()));
        }
        if (StringUtils.isNotBlank(cofigPage.getUserSfzh())) {
            queryWrapper.and(wrapper -> wrapper.eq("user_sfzh", cofigPage.getUserSfzh()));
        }
        queryWrapper.and(wrapper -> wrapper.eq("xt_zxbz", DeletedEnum.NATURE.code));
        List<OrderItem> orderBy = Lists.newArrayList(OrderItem.asc("id"));
        cofigPage.setOrders(orderBy);
        return sysUserAppHomeconfigMapper.selectPage(cofigPage, queryWrapper);
    }

    @Override
    public List<SysUserAppHomeconfigVo> queryUserConfig(SysUserAppHomeconfigQuery cofigQuery) {
        List<SysUserAppHomeconfigVo> homeconfigVos = new ArrayList<>();
        List<SysUserAppHomeconfig> configs = getConfigs(cofigQuery);
        List<SysUserAppHomeconfigPlate> plates = getPlates(configs);
        List<SysUserAppHomeconfigPlateList> plateList = getPlateList(plates);
        if (!CollectionUtils.isEmpty(configs)) {
            for (SysUserAppHomeconfig config : configs) {
                SysUserAppHomeconfigVo vo = new SysUserAppHomeconfigVo();
                BeanUtils.copyProperties(config, vo);
                if (!CollectionUtils.isEmpty(plates)) {
                    List<SysUserAppHomeconfigPlate> list =
                            plates.parallelStream().filter(item -> item.getPzId().longValue() == config.getId().longValue()).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(list)) {
                        List<SysUserAppHomeconfigPlateVo> voList = new ArrayList<>();
                        for (SysUserAppHomeconfigPlate plate : list) {
                            SysUserAppHomeconfigPlateVo plateVo = new SysUserAppHomeconfigPlateVo();
                            BeanUtils.copyProperties(plate, plateVo);
                            if (!CollectionUtils.isEmpty(plateList)) {
                                List<SysUserAppHomeconfigPlateList> platesArray = getList(plateList, plate.getId());
                                plateVo.setPlateList(platesArray);
                            }
                            voList.add(plateVo);
                        }
                        vo.setPlates(voList);
                    }
                }
                homeconfigVos.add(vo);
            }
        }
        return homeconfigVos;
    }

    @Override
    public Long saveDefaultConfig(SysUserHomeconfigVo configVo, String ipAddress) {
        QueryWrapper<SysUserAppHomeconfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq("user_id", configVo.getUserId()));
        queryWrapper.and(wrapper -> wrapper.eq("homeid", configVo.getHomeid()));
        queryWrapper.and(wrapper -> wrapper.eq("xt_zxbz", DeletedEnum.NATURE.code));
        List<SysUserAppHomeconfig> configs = sysUserAppHomeconfigMapper.selectList(queryWrapper);
        System.out.println(configs);
        if (configs != null && configs.size() > 0 &&
                configs.get(0).getPzbks() != null && configs.get(0).getPzbks() != 0) {
            System.out.println("configs------->" + configs.size());
            log.info(JSONObject.toJSONString(configs));
            return configs.get(0).getId();
        }
        SysAppHomeconfigQuery query = new SysAppHomeconfigQuery();
        query.setId(configVo.getHomeid());
        SysAppHomeconfigRsVO vo = sysAppHomeconfigService.queryConfig(query);
        //用户首页配置ID
        SysUserAppHomeconfig config = new SysUserAppHomeconfig();
        config.setHomeid(configVo.getHomeid());
        config.setHomename(vo.getHomename());
        config.setUserId(configVo.getUserId());
        config.setUserXm(configVo.getUserXm());
        config.setUserSfzh(configVo.getUserSfzh());
        if (!CollectionUtils.isEmpty(vo.getPlateList())) {
            config.setPzbks(vo.getPlateList().size());
        }
        config.setPzsj(new Date());
        config.setSd(configVo.getSd());
        Long homeConfigId = saveInfo(config, ipAddress);
        if (!CollectionUtils.isEmpty(vo.getPlateList())) {
            //用户默认板块内容
            int i = 0;
            for (SysAppHomeconfigPlateVo plate : vo.getPlateList()) {
                i++;
                SysUserAppHomeconfigPlate userPlate = new SysUserAppHomeconfigPlate();
                userPlate.setPzId(homeConfigId);
                userPlate.setPlateId(plate.getId());
                userPlate.setBklx(plate.getBklx());
                userPlate.setBkmc(plate.getBkmc());
                userPlate.setBksx(i);
                Long userPlateId = sysUserAppHomeconfigPlateService.saveInfo(userPlate, ipAddress);
                if (!CollectionUtils.isEmpty(vo.getPlateList())) {
                    userPlate.setBknrs(vo.getPlateList().size());
                    int j = 0;
                    for (SysAppHomeconfigPlateList plateVo : plate.getPlateList()) {
                        j++;
                        SysUserAppHomeconfigPlateList userList = new SysUserAppHomeconfigPlateList();
                        userList.setPzId(homeConfigId);
                        userList.setPzPlateId(userPlateId);
                        userList.setPlateListId(plateVo.getId());
                        userList.setNrmc(plateVo.getNrmc());
                        userList.setBksx(j);
                        userList.setTzdz(plateVo.getTzdz());
                        userList.setBz(plateVo.getBz());
                        sysUserAppHomeconfigPlateListService.saveInfo(userList, ipAddress);
                    }
                }
            }
        }
        return homeConfigId;
    }

    public List<SysUserAppHomeconfigPlateList> getList(List<SysUserAppHomeconfigPlateList> platesArray, Long id) {
        List<SysUserAppHomeconfigPlateList> array = new ArrayList<>();
        if (CollectionUtils.isEmpty(platesArray)) {
            return array;
        }
        log.info("platesArray:" + platesArray.size() + ",id:" + id);
        for (SysUserAppHomeconfigPlateList plate : platesArray) {
            if (plate.getPzPlateId().longValue() == id.longValue()) {
                array.add(plate);
            }
        }
        return array;
    }

    /**
     * 获取用户配置首页
     *
     * @param cofigQuery
     * @return
     */
    public List<SysUserAppHomeconfig> getConfigs(SysUserAppHomeconfigQuery cofigQuery) {
        QueryWrapper<SysUserAppHomeconfig> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(cofigQuery.getHomename())) {
            queryWrapper.and(wrapper -> wrapper.like("homename", cofigQuery.getHomename()));
        }
        if (cofigQuery.getHomeid() != null) {
            queryWrapper.and(wrapper -> wrapper.eq("homeid", cofigQuery.getHomeid()));
        }
        if (cofigQuery.getUserId() != null) {
            queryWrapper.and(wrapper -> wrapper.eq("user_id", cofigQuery.getUserId()));
        }
        if (StringUtils.isNotBlank(cofigQuery.getUserSfzh())) {
            queryWrapper.and(wrapper -> wrapper.eq("user_sfzh", cofigQuery.getUserSfzh()));
        }
        queryWrapper.and(wrapper -> wrapper.eq("xt_zxbz", DeletedEnum.NATURE.code));
        queryWrapper.orderByAsc("ID");
        return sysUserAppHomeconfigMapper.selectList(queryWrapper);
    }


    /**
     * 获取用户配置板块
     *
     * @param configs
     * @return
     */
    public List<SysUserAppHomeconfigPlate> getPlates(List<SysUserAppHomeconfig> configs) {
        List<SysUserAppHomeconfigPlate> plates = new ArrayList<>();
        if (!CollectionUtils.isEmpty(configs)) {
            List<Long> configIds = configs.stream().map(item -> item.getId()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(configIds)) {
                QueryWrapper<SysUserAppHomeconfigPlate> plateListWrapper = new QueryWrapper<>();
                plateListWrapper.lambda().in(SysUserAppHomeconfigPlate::getPzId, configIds);
                plateListWrapper.lambda().eq(SysUserAppHomeconfigPlate::getXtZxbz, DeletedEnum.NATURE.code);
                plateListWrapper.orderByAsc("bksx");
                plates = sysUserAppHomeconfigPlateMapper.selectList(plateListWrapper);
            }
        }
        return plates;
    }


    /**
     * 获取用户配置板块内容
     *
     * @param plates
     * @return
     */
    public List<SysUserAppHomeconfigPlateList> getPlateList(List<SysUserAppHomeconfigPlate> plates) {
        List<SysUserAppHomeconfigPlateList> plateList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(plates)) {
            List<Long> configIds = plates.stream().map(item -> item.getId()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(configIds)) {
                QueryWrapper<SysUserAppHomeconfigPlateList> plateListWrapper = new QueryWrapper<>();
                plateListWrapper.lambda().in(SysUserAppHomeconfigPlateList::getPzPlateId, configIds);
                plateListWrapper.lambda().eq(SysUserAppHomeconfigPlateList::getXtZxbz, DeletedEnum.NATURE.code);
                plateListWrapper.orderByAsc("bksx");
                plateList = sysUserAppHomeconfigPlateListMapper.selectList(plateListWrapper);
            }
        }
        return plateList;
    }

}
