package com.unis.module.coding.service.caxx;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yitter.idgen.YitIdHelper;
import com.unis.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.unis.framework.mybatis.core.query.QueryWrapperX;
import com.unis.framework.security.core.LoginUser;
import com.unis.framework.security.core.util.AreaUtils;
import com.unis.framework.security.core.util.SecurityFrameworkUtils;
import com.unis.module.coding.controller.admin.delivery.vo.DeliveryRespVO;
import com.unis.module.coding.controller.admin.delivery.vo.SparePageReqVO;
import com.unis.module.coding.controller.admin.delivery.vo.SpareRespVO;
import com.unis.module.coding.dal.dataobject.kqxx.KqxxDO;
import com.unis.module.coding.dal.mysql.kqxx.KqxxMapper;
import com.unis.module.system.dal.dataobject.permission.UserRoleDO;
import com.unis.module.system.dal.dataobject.user.AdminUserDO;
import com.unis.module.system.dal.mysql.permission.UserRoleMapper;
import com.unis.module.system.dal.mysql.user.AdminUserMapper;
import com.unis.module.system.enums.permission.RoleIdEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import com.unis.module.coding.controller.admin.caxx.vo.*;
import com.unis.module.coding.dal.dataobject.caxx.CaxxDO;
import com.unis.framework.common.pojo.PageResult;
import com.unis.framework.common.util.object.BeanUtils;

import com.unis.module.coding.dal.mysql.caxx.CaxxMapper;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.unis.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.unis.module.core.enums.ErrorCodeConstants.CAXX_NOT_EXISTS;
import static com.unis.module.infra.enums.ErrorCodeConstants.ERROR;

/**
 * 仓廒信息; Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class CaxxServiceImpl implements CaxxService {

    @Resource
    private CaxxMapper caxxMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private AdminUserMapper adminUserMapper;
    @Resource
    private KqxxMapper kqxxMapper;

    @Override
    public Long createCaxx(CaxxSaveReqVO createReqVO) {
        // 插入
        CaxxDO caxx = BeanUtils.toBean(createReqVO, CaxxDO.class);
        caxx.setId(YitIdHelper.nextId());
        caxx.setSjly(0);
        caxxMapper.insert(caxx);
        // 返回
        return caxx.getId();
    }

    @Override
    public void updateCaxx(CaxxSaveReqVO updateReqVO) {
        // 校验存在
        validateCaxxExists(updateReqVO.getId());
        // 更新
        CaxxDO updateObj = BeanUtils.toBean(updateReqVO, CaxxDO.class);
        caxxMapper.updateById(updateObj);
    }

    @Override
    public void deleteCaxx(Long id) {
        // 校验存在
        validateCaxxExists(id);
        // 删除
        caxxMapper.deleteById(id);
    }

    private void validateCaxxExists(Long id) {
        if (caxxMapper.selectById(id) == null) {
            throw exception(CAXX_NOT_EXISTS);
        }
    }

    @Override
    public CaxxDO getCaxx(Long id) {
        return caxxMapper.selectById(id);
    }

    @Override
    public PageResult<CaxxDO> getCaxxPage(CaxxPageReqVO pageReqVO) {
        return caxxMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<SpareRespVO> getDeliverySparePage(SparePageReqVO pageReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            throw exception(ERROR, "不存在用户信心信息");
        }
        if (StringUtils.isNotBlank(pageReqVO.getDwmc())) {
            pageReqVO.setDwmc(String.format("%s%s%s", "%", pageReqVO.getDwmc(), "%"));
        }
        if (StringUtils.isNotBlank(pageReqVO.getKqmc())) {
            pageReqVO.setKqmc(String.format("%s%s%s", "%", pageReqVO.getKqmc(), "%"));
        }
        String areaLevel = loginUser.getInfo().get("areaLevel");
        Page<SpareRespVO> page = new Page<SpareRespVO>();
        // 国家交易中心已选
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            page = caxxMapper.getDeliverySparePage(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
        }
        //省级交易中心与银行用户
        if ("1".equals(areaLevel)) {
            String shengCode = loginUser.getInfo().get("shengCode");
            pageReqVO.setShengCode(shengCode);
            //获取当前用户角色
            String roleIds = loginUser.getInfo().get("roleIds");
            if (ObjectUtils.isEmpty(roleIds)) {
                throw exception(ERROR, "当前用户不存在角色信息");
            }
            if (roleIds.contains("[") && roleIds.contains("]")) {
                String roleIdsReal = roleIds.substring(1, roleIds.length() - 1);
                String[] items = roleIdsReal.split(",");
                List<String> roleIdList = Arrays.asList(items);
                if (roleIdList.contains(RoleIdEnum.BANK_ADMIN.getRoleId())) {
                    String bankType = loginUser.getInfo().get("bankType");
                    if (StringUtils.isBlank(bankType)) {
                        throw exception(ERROR, "当前银行用户不存在银行信息");
                    }
                    pageReqVO.setYhmc(bankType);
                    page = caxxMapper.selectWrapperPageForBank(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
                } else {
                    page = caxxMapper.selectWrapperPageForSheng(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
                    List<SpareRespVO> records = page.getRecords();
                    if (!ObjectUtils.isEmpty(records)) {
                        records.stream().forEach(s -> {
                            String fileIds = s.getFileIds();
                            if (fileIds != null && !"".equals(fileIds)) {
                                String[] fileIdArray = fileIds.split(",");
                                int length = fileIdArray.length;
                                s.setFileNumber(length);
                            } else {
                                s.setFileNumber(0);
                            }
                        });
                    }
                }
            }
        }
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    @Override
    public PageResult<SpareRespVO> getIdentifySparePage(SparePageReqVO pageReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            throw exception(ERROR, "不存在用户信息");
        }
        String areaLevel = loginUser.getInfo().get("areaLevel");
        if (StringUtils.isNotBlank(pageReqVO.getDwmc())) {
            pageReqVO.setDwmc(String.format("%s%s%s", "%", pageReqVO.getDwmc(), "%"));
        }
        if (StringUtils.isNotBlank(pageReqVO.getKqmc())) {
            pageReqVO.setKqmc(String.format("%s%s%s", "%", pageReqVO.getKqmc(), "%"));
        }
        Page<SpareRespVO> page = new Page<SpareRespVO>();
        // 国家交易中心已选
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            page = caxxMapper.getIdentifySparePage(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
        }
        //省级交易中心与银行用户
        if ("1".equals(areaLevel)) {
            String shengCode = loginUser.getInfo().get("shengCode");
            pageReqVO.setShengCode(shengCode);
            String roleIds = loginUser.getInfo().get("roleIds");
            if (ObjectUtils.isEmpty(roleIds)) {
                throw exception(ERROR, "当前用户不存在角色信息");
            }
            if (roleIds.contains("[") && roleIds.contains("]")) {
                String roleIdsReal = roleIds.substring(1, roleIds.length() - 1);
                String[] items = roleIdsReal.split(",");
                List<String> roleIdList = Arrays.asList(items);
                if (roleIdList.contains(RoleIdEnum.BANK_ADMIN.getRoleId())) {
                    String bankType = loginUser.getInfo().get("bankType");
                    if (StringUtils.isBlank(bankType)) {
                        throw exception(ERROR, "当前银行用户不存在银行信息");
                    }
                    pageReqVO.setYhmc(bankType);
                    page = caxxMapper.getIdentifyPageForBank(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
                } else {
                    page = caxxMapper.getIdentifyPageForSheng(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
                }
            }
        }
        if (!ObjectUtils.isEmpty(page)) {
            List<SpareRespVO> records = page.getRecords();
            if (!ObjectUtils.isEmpty(records)) {
                records.stream().forEach(s -> s.setYhmc(pageReqVO.getYhmc()));
            }
        }
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    @Override
    public PageResult<SpareRespVO> getSelectSparePage(SparePageReqVO pageReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            throw exception(ERROR, "不存在用户信息");
        }
        String areaLevel = loginUser.getInfo().get("areaLevel");
        if (StringUtils.isNotBlank(pageReqVO.getDwmc())) {
            pageReqVO.setDwmc(String.format("%s%s%s", "%", pageReqVO.getDwmc(), "%"));
        }
        if (StringUtils.isNotBlank(pageReqVO.getKqmc())) {
            pageReqVO.setKqmc(String.format("%s%s%s", "%", pageReqVO.getKqmc(), "%"));
        }
        Page<SpareRespVO> page = new Page<SpareRespVO>();
        // 国家交易中心已选
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            page = caxxMapper.getSelectSparePage(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
        }
        //省级交易中心与银行用户
        if ("1".equals(areaLevel)) {
            String shengCode = loginUser.getInfo().get("shengCode");
            pageReqVO.setShengCode(shengCode);
            String roleIds = loginUser.getInfo().get("roleIds");
            if (ObjectUtils.isEmpty(roleIds)) {
                throw exception(ERROR, "当前用户不存在角色信息");
            }
            if (roleIds.contains("[") && roleIds.contains("]")) {
                String roleIdsReal = roleIds.substring(1, roleIds.length() - 1);
                String[] items = roleIdsReal.split(",");
                List<String> roleIdList = Arrays.asList(items);
                if (roleIdList.contains(RoleIdEnum.BANK_ADMIN.getRoleId())) {
                    String bankType = loginUser.getInfo().get("bankType");
                    if (StringUtils.isBlank(bankType)) {
                        throw exception(ERROR, "当前银行用户不存在银行信息");
                    }
                    pageReqVO.setYhmc(bankType);
                    page = caxxMapper.getSelectPageForBank(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
                } else {
                    page = caxxMapper.getSelectPageForSheng(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
                }
            }
        }
        if (!ObjectUtils.isEmpty(page)) {
            List<SpareRespVO> records = page.getRecords();
            if (!ObjectUtils.isEmpty(records)) {
                records.stream().forEach(s -> s.setYhmc(pageReqVO.getYhmc()));
            }
        }
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    @Override
    public List<CaxxDO> getCaxxByKqBm() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        String kqbm = loginUser.getInfo().get("kqbm");
        if (ObjectUtils.isEmpty(loginUser)) {
            throw exception(ERROR, "不存在用户信息");
        }
        if (ObjectUtils.isEmpty(kqbm)) {
            throw exception(ERROR, "当前用户不存在库区编码");
        }
        List<KqxxDO> kqbm1 = kqxxMapper.selectList(new QueryWrapper<KqxxDO>().eq("KQBM", kqbm));
        if (CollectionUtils.isEmpty(kqbm1)) {
            throw exception(ERROR, "当前库区编码下无库区信息");
        }
        return caxxMapper.selectList(new QueryWrapper<CaxxDO>().eq("KQID", kqbm1.get(0).getId()));
    }

    public LambdaQueryWrapper<CaxxDO> buildQueryWrapper(CaxxPageReqVO reqVO) {
        LambdaQueryWrapper<CaxxDO> queryWrapper = new LambdaQueryWrapper<>();

        // 这里添加具体的询条件逻辑
        if (reqVO.getKqid() != null) {
            queryWrapper.eq(CaxxDO::getKqid, reqVO.getKqid());
        }
        // 其他条件...

        queryWrapper.orderByDesc(CaxxDO::getId);

        return queryWrapper;
    }

}