package org.jeecg.modules.system.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.pay.config.WechatConstants;
import org.jeecg.modules.system.app.dto.AppSiteDTO;
import org.jeecg.modules.system.app.dto.AppSitePageDTO;
import org.jeecg.modules.system.app.dto.EditSitePayInfoDTO;
import org.jeecg.modules.system.app.entity.AppSite;
import org.jeecg.modules.system.app.entity.AppSitePlace;
import org.jeecg.modules.system.app.mapper.AppSiteMapper;
import org.jeecg.modules.system.app.mapper.AppSitePlaceMapper;
import org.jeecg.modules.system.app.mapper.AppSitePriceRulesMapper;
import org.jeecg.modules.system.app.service.IAppSiteService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static org.jeecg.common.constant.CommonConstant.SC_INTERNAL_SERVER_ERROR_500;

/**
 * @Description: 场地表
 * @Author: jeecg-boot
 * @Date: 2025-07-03
 * @Version: V1.0
 */
@Service
public class AppSiteServiceImpl extends ServiceImpl<AppSiteMapper, AppSite> implements IAppSiteService {
    @Resource
    private AppSitePriceRulesMapper priceRulesMapper;
    @Resource
    private SysDepartMapper sysDepartMapper;
    @Resource
    private AppSitePlaceMapper appSitePlaceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSite(AppSiteDTO siteCuDTO) {
        if (null == siteCuDTO.getType()) throw new JeecgBootException("商户类型不能为空", SC_INTERNAL_SERVER_ERROR_500);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        AppSite site = new AppSite();
//        SysDepart departById = sysDepartMapper.getDepartById(siteCuDTO.getTenantId());
        //根据当前登录的orgcode去查询所属部门id
        SysDepart departById = sysDepartMapper.findByOrgCode(sysUser.getOrgCode());
        if (null == departById) throw new JeecgBootException("商户部门不存在", SC_INTERNAL_SERVER_ERROR_500);
        if (!(departById.getOrgCategory().equals("21")||departById.getOrgCategory().equals("20"))) throw new JeecgBootException("商户部门类型错误", SC_INTERNAL_SERVER_ERROR_500);
        BeanUtils.copyProperties(siteCuDTO, site);
        if (null == departById.getOrgCode())
            throw new JeecgBootException("商户部门编码不能为空", SC_INTERNAL_SERVER_ERROR_500);
        if (null == departById.getTenantId())
            throw new JeecgBootException("商户部门id不能为空", SC_INTERNAL_SERVER_ERROR_500);

        site.setOrgCode(departById.getOrgCode());
        site.setTenantId(departById.getId());
        int saveSiteResult = baseMapper.insert(site);
        // 如果插入失败，抛出自定义异常提示“场地信息保存失败”
        if (saveSiteResult < 1) {
            throw new JeecgBootException("商户信息保存失败", SC_INTERNAL_SERVER_ERROR_500);
        }
        // 所有操作成功完成后返回 true
        return Boolean.TRUE;
    }

    //比较两个list
    //取出存在menuOneList中，但不存在resourceList中的数据，差异数据放入differentList
    private List<String> listCompare(List<String> menuOneList, List<String> resourceList) {
        Map<String, Integer> map = new HashMap<String, Integer>(resourceList.size());
        List<String> differentList = new ArrayList<>();
        for (String resource : resourceList) {
            map.put(resource, 1);
        }
        for (String resource1 : menuOneList) {
            if (map.get(resource1) == null) {
                differentList.add(resource1);
            }
        }
        return differentList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editSite(AppSiteDTO siteCuDTO) {
        String id = siteCuDTO.getId();
        if (StrUtil.isNotBlank(id)) {
            AppSite oldSite = baseMapper.selectById(id);
            //比较运动类目，做新增删除修改
            if (ObjectUtil.isNotNull(oldSite.getCategoryId()) && !siteCuDTO.getCategoryId().equals(oldSite.getCategoryId())) {
                List<String> oldList = Arrays.stream(oldSite.getCategoryId().split(",")).collect(Collectors.toList());
                List<String> newList = Arrays.stream(siteCuDTO.getCategoryId().split(",")).collect(Collectors.toList());
                List<String> diffList = listCompare(oldList, newList);
                if (ObjectUtils.isNotEmpty(diffList)) {
                    for (String categoryId : diffList) {
                        //删除包场已修改的类目场地信息
                        appSitePlaceMapper.delete(Wrappers.<AppSitePlace>lambdaQuery().eq(AppSitePlace::getSiteId,
                                id).eq(AppSitePlace::getCategoryId, categoryId));
                    }
                }
            }
        }
        AppSite site = new AppSite();
        BeanUtils.copyProperties(siteCuDTO, site);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (null == site.getType()) throw new JeecgBootException("场地类型不能为空", SC_INTERNAL_SERVER_ERROR_500);
        AppSite dbSite = baseMapper.selectById(site.getId());
        if (null == dbSite) throw new JeecgBootException("未找到对应数据", SC_INTERNAL_SERVER_ERROR_500);
        if (null == dbSite.getOrgCode())
            throw new JeecgBootException("商户部门编码不能为空", SC_INTERNAL_SERVER_ERROR_500);
        if (null == dbSite.getTenantId())
            throw new JeecgBootException("商户部门id不能为空", SC_INTERNAL_SERVER_ERROR_500);
        site.setOrgCode(dbSite.getOrgCode());
        site.setTenantId(dbSite.getTenantId());
        int updateSiteResult = baseMapper.updateById(site);
        if (updateSiteResult < 1) {
            throw new JeecgBootException("商户信息保存失败", SC_INTERNAL_SERVER_ERROR_500);
        }
        return Boolean.TRUE;
    }

    @Override
    public AppSiteDTO querySiteById(String id) {
        AppSite dbSite = baseMapper.selectById(id);
        if (null == dbSite) throw new JeecgBootException("未找到对应数据", SC_INTERNAL_SERVER_ERROR_500);
        AppSiteDTO appSiteDTO = new AppSiteDTO();
        BeanUtils.copyProperties(dbSite, appSiteDTO);
        return appSiteDTO;
    }

    @Override
    public AppSiteDTO querySiteByOrgCode(String orgCode) {
        AppSite site = baseMapper.selectOne(Wrappers.<AppSite>lambdaQuery().eq(AppSite::getOrgCode, orgCode));
        AppSiteDTO siteVO = new AppSiteDTO();
        if (site!=null){
            BeanUtils.copyProperties(site, siteVO);
        }

        return siteVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteSiteById(String id) {
        AppSite dbSite = baseMapper.selectById(id);
        if (null == dbSite) throw new JeecgBootException("未找到对应数据", SC_INTERNAL_SERVER_ERROR_500);
//        checkPermission(dbSite,sysUser);
        int deleteSiteResult = baseMapper.deleteById(id);
        if (deleteSiteResult < 1) {
            throw new JeecgBootException("商户信息删除失败", SC_INTERNAL_SERVER_ERROR_500);
        }
        return Boolean.TRUE;
    }

    @Override
    public IPage<AppSiteDTO> querySitePage(AppSitePageDTO dto) {
        Page<AppSite> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        LambdaQueryWrapper<AppSite> wrapper = Wrappers.<AppSite>lambdaQuery()
                .like(StringUtils.isNotBlank(dto.getName()), AppSite::getName, dto.getName());
        IPage<AppSite> resultPage = baseMapper.selectPage(page, wrapper);

        return resultPage.convert(record -> {
            AppSiteDTO cuDTO = new AppSiteDTO();
            BeanUtils.copyProperties(record, cuDTO);
            return cuDTO;
        });
    }

    @Override
    public AppSiteDTO queryByTenantId(String tenantId) {
        AppSite site = baseMapper.selectOne(Wrappers.<AppSite>lambdaQuery().eq(AppSite::getTenantId, tenantId));
        if (ObjectUtils.isNotEmpty(site)) throw new JeecgBootException("未找到对应数据", SC_INTERNAL_SERVER_ERROR_500);
        AppSiteDTO appSiteDTO = new AppSiteDTO();
        BeanUtils.copyProperties(site, appSiteDTO);
        return appSiteDTO;
    }

    @Override
    public Boolean editSitePayInfo(EditSitePayInfoDTO editSitePayInfoDTO) {
        SysDepart sysDepart = sysDepartMapper.selectById(editSitePayInfoDTO.getSiteId());
        if(null == sysDepart) throw new JeecgBootException("商户部门不存在", SC_INTERNAL_SERVER_ERROR_500);
        // 转换括号
        String mchName = editSitePayInfoDTO.getMchName();
        if (mchName != null) {
            mchName = mchName.replace("(", "（").replace(")", "）");
        }
        sysDepart.setMchId(editSitePayInfoDTO.getMchId());
        sysDepart.setMchName(mchName);
        sysDepart.setOrgIdCardNum(editSitePayInfoDTO.getOrgIdCardNum());
        sysDepart.setAppid(WechatConstants.WECHAT_SUB_APPID);
        return sysDepartMapper.updateById(sysDepart) > 0;
    }

    @Override
    public EditSitePayInfoDTO querySitePayInfoById(String id) {
        EditSitePayInfoDTO editSitePayInfoDTO = new EditSitePayInfoDTO();
        SysDepart sysDepart = sysDepartMapper.selectById(id);
        // 转换括号
        String mchName = editSitePayInfoDTO.getMchName();
        if (mchName != null) {
            mchName = mchName.replace("(", "（").replace(")", "）");
        }
        editSitePayInfoDTO.setSiteId(sysDepart.getId())
                .setMchId(sysDepart.getMchId())
                .setMchName(mchName)
                .setOrgIdCardNum(sysDepart.getOrgIdCardNum());
        return editSitePayInfoDTO;
    }

    /**
     * 权限校验
     *
     * @param site
     * @param sysUser
     */
    private void checkPermission(AppSite site, LoginUser sysUser) {
        if (!sysUser.getOrgCode().equals(site.getOrgCode()))
            throw new JeecgBootException("无权限操作", SC_INTERNAL_SERVER_ERROR_500);
    }
}
