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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.pojo.PageResult;
import com.unis.framework.common.util.kqbm.KQBMUtils;
import com.unis.framework.common.util.object.BeanUtils;
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.*;
import com.unis.module.coding.controller.admin.dwxx.vo.DwxxPageReqVO;
import com.unis.module.coding.controller.admin.dwxx.vo.DwxxSaveReqVO;
import com.unis.module.coding.dal.dataobject.bank.BankDO;
import com.unis.module.coding.dal.dataobject.caxx.CaxxDO;
import com.unis.module.coding.dal.dataobject.codingcaxx.CodingCaxxDO;
import com.unis.module.coding.dal.dataobject.codingdwxx.CodingDwxxDO;
import com.unis.module.coding.dal.dataobject.codingkqxx.CodingKqxxDO;
import com.unis.module.coding.dal.dataobject.cwxx.CwxxDO;
import com.unis.module.coding.dal.dataobject.cwxxyear.CwxxYearDO;
import com.unis.module.coding.dal.dataobject.dwxx.DwxxDO;
import com.unis.module.coding.dal.dataobject.fmxx.FmxxDO;
import com.unis.module.coding.dal.dataobject.kqxx.KqxxDO;
import com.unis.module.coding.dal.dataobject.province.ProvinceDO;
import com.unis.module.coding.dal.dataobject.users.UsersDO;
import com.unis.module.coding.dal.mysql.bank.BankMapper;
import com.unis.module.coding.dal.mysql.caxx.CaxxMapper;
import com.unis.module.coding.dal.mysql.codingcaxx.CodingCaxxMapper;
import com.unis.module.coding.dal.mysql.codingdwxx.CodingDwxxMapper;
import com.unis.module.coding.dal.mysql.codingkqxx.CodingKqxxMapper;
import com.unis.module.coding.dal.mysql.cwxx.CwxxMapper;
import com.unis.module.coding.dal.mysql.cwxxyear.CwxxYearMapper;
import com.unis.module.coding.dal.mysql.dwxx.DwxxMapper;
import com.unis.module.coding.dal.mysql.fmxx.FmxxMapper;
import com.unis.module.coding.dal.mysql.kqxx.KqxxMapper;
import com.unis.module.coding.dal.mysql.province.ProvinceMapper;
import com.unis.module.coding.dal.mysql.users.UsersMapper;
import com.unis.module.core.enums.CityConstants;
import com.unis.module.core.enums.XZQHLEVEL;
import com.unis.module.core.enums.YXZT;
import com.unis.module.system.dal.dataobject.arealevel.AreaLevelDO;
import com.unis.module.system.dal.dataobject.dict.DictDataDO;
import com.unis.module.system.dal.mysql.arealevel.AreaLevelMapper;
import com.unis.module.system.dal.mysql.dict.DictDataMapper;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

/**
 * 单位信息 Service 实现类
 *
 * @author 超级管理员
 */
@Slf4j
@Service
@Validated
public class DwxxServiceImpl implements DwxxService {

    @Resource
    private DwxxMapper dwxxMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private AdminUserMapper adminUserMapper;
    @Resource
    private CodingKqxxMapper codingKqxxMapper;
    @Resource
    private CodingCaxxMapper codingCaxxMapper;
    @Resource
    private CodingDwxxMapper codingDwxxMapper;
    @Resource
    private KqxxMapper kqxxMapper;
    @Resource
    private CaxxMapper caxxMapper;
    @Resource
    private AreaLevelMapper areaLevelMapper;
    @Resource
    private ProvinceMapper provinceMapper;
    @Resource
    private BankMapper bankMapper;
    @Resource
    private CwxxMapper cwxxMapper;
    @Resource
    private CwxxYearMapper cwxxYearMapper;
    @Resource
    private FmxxMapper fmxxMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private DictDataMapper dictDataMapper;

    @Override
    public Long createDwxx(DwxxSaveReqVO createReqVO) {

        // 插入
        DwxxDO dwxx = BeanUtils.toBean(createReqVO, DwxxDO.class);
        dwxx.setId(YitIdHelper.nextId());
        /**
         * {
         * 	"id": 633249312886853,
         * 	"info": {
         * 		"nickname": "北京局管理员用户",
         * 		"deptId": "1171201049703"
         *        },
         * 	"userType": 2
         * }
         */
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (ObjectUtils.isNotEmpty(loginUser)) {
            String deptId = loginUser.getInfo().get("deptId");
            log.info("创建者的dept_id({})", deptId);
            dwxx.setDwDeptId(deptId);
        } else {
            throw exception(DWXX_LOGIN_USER_EXISTS);
        }

        dwxxMapper.insert(dwxx);
        // 返回
        return dwxx.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDwxx(DwxxSaveReqVO updateReqVO) {
        // 校验存在
        validateDwxxExists(updateReqVO.getId());
        // 更新
        DwxxDO updateObj = BeanUtils.toBean(updateReqVO, DwxxDO.class);
        dwxxMapper.updateById(updateObj);
    }

    @Override
    public void deleteDwxx(Long id) {
        // 校验存在
        validateDwxxExists(id);
        // 删除
        dwxxMapper.deleteById(id);
    }

    private void validateDwxxExists(Long id) {
        if (dwxxMapper.selectById(id) == null) {
            throw exception(DWXX_NOT_EXISTS);
        }
    }

    @Override
    public DwxxDO getDwxx(Long id) {
        return dwxxMapper.selectById(id);
    }

    @Override
    public PageResult<DwxxDO> getDwxxPage(DwxxPageReqVO pageReqVO) {
        return dwxxMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<DeliveryRespVO> getDeliveryPage(DeliveryPageReqVO 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(), "%"));
        }
        String areaLevel = loginUser.getInfo().get("areaLevel");
        Page<DeliveryRespVO> page = new Page<DeliveryRespVO>();
        // 国家交易中心已选
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            if (pageReqVO.getAreaCode() != null) {
                // 数据权限
                pageReqVO.setAreaCode(AreaUtils.getAreaCode(pageReqVO.getAreaLevel(), pageReqVO.getAreaCode(), pageReqVO.getParentCode()));
            }
            page = dwxxMapper.selectWrapperPage(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);

        }
        //省级交易中心与银行用户
        if ("1".equals(areaLevel)) {
            String shengCode = loginUser.getInfo().get("shengCode");
            pageReqVO.setAreaSheng(shengCode);
            if (!ObjectUtils.isEmpty(pageReqVO.getAreaLevel()) && pageReqVO.getAreaCode() != null) {
                if (XZQHLEVEL.SHI.getCode().equals(pageReqVO.getAreaLevel())) {
                    pageReqVO.setAreaShi(pageReqVO.getAreaCode());
                }
                if (XZQHLEVEL.XIAN.getCode().equals(pageReqVO.getAreaLevel())) {
                    pageReqVO.setAreaXian(pageReqVO.getAreaCode());
                }
            }
            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 = dwxxMapper.selectWrapperPageForBank(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
                } else {
                    page = dwxxMapper.selectWrapperPageForSheng(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
                }
            }
        }
        if (!ObjectUtils.isEmpty(page)) {
            List<DeliveryRespVO> records = page.getRecords();
            if (!ObjectUtils.isEmpty(records)) {
                records.stream().forEach(s -> {
                     s.setCflx(pageReqVO.getCflx());
                     s.setCfzt(pageReqVO.getCfzt());
                     s.setCfEnd(pageReqVO.getCfEnd());
                     s.setCfStart(pageReqVO.getCfStart());
                    if (Arrays.asList(CityConstants.CITY).contains(s.getSheng()) && ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel))) {
                        s.setShi(s.getXian());
                        s.setXian(null);
                    }
                });
            }
        }
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    @Override
    public List<StoreRespVO> getStorePage(StorePageReqVO pageReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            throw exception(ERROR, "不存在用户信息");
        }
        String areaLevel = loginUser.getInfo().get("areaLevel");
        // 国家交易中心已选
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            if (YXZT.NOT_SELECTED.getCode().equals(pageReqVO.getYxcf())) {
                List<StoreRespVO> storeListForNation = dwxxMapper.getStoreListForNation(pageReqVO);
                List<CaxxDO> caxxDOS = caxxMapper.selectListByKqId(pageReqVO.getKqId());
                if (!ObjectUtils.isEmpty(storeListForNation)) {
                    if (!ObjectUtils.isEmpty(caxxDOS)) {
                        List<Long> idsExist = caxxDOS.stream().map(CaxxDO::getId).collect(Collectors.toList());
                        if (!ObjectUtils.isEmpty(idsExist)) {
                            storeListForNation.removeIf(caxxDO -> idsExist.contains(caxxDO.getId()));
                        }
                    }
                    return storeListForNation;
                }
            } else if (YXZT.SELECTED.getCode().equals(pageReqVO.getYxcf()) || YXZT.OPTION.getCode().equals(pageReqVO.getYxcf())) {
                List<CaxxDO> caxxDOS = caxxMapper.selectListByKqId(pageReqVO.getKqId());
                if (!ObjectUtils.isEmpty(caxxDOS)) {
                    caxxDOS.stream().forEach(s->{
                        if (s.getSjcr()!=null) {
                            BigDecimal truncatedNumber = s.getSjcr().setScale(0, RoundingMode.DOWN);
                            s.setSjcr(truncatedNumber);
                        }
                    });
                    List<StoreRespVO> selectedStoreSForNation = BeanUtils.toBean(caxxDOS, StoreRespVO.class);
                    return selectedStoreSForNation;
                }
            } else if (YXZT.IDENTIFY.getCode().equals(pageReqVO.getYxcf())) {
                List<StoreRespVO> storeRespVOS = caxxMapper.selectListForIdentify(pageReqVO.getKqId(), pageReqVO.getYhmc());
                return storeRespVOS;
            } else if (YXZT.SELECT.getCode().equals(pageReqVO.getYxcf())) {
                List<StoreRespVO> storeRespVOS = caxxMapper.selectListForSelect(pageReqVO.getKqId(), pageReqVO.getYhmc());
                return storeRespVOS;
            } else {
                //国家查看省已选仓房列表
                List<StoreRespVO> storeListForProvince = provinceMapper.getStoreListForProvinceOnly(pageReqVO.getKqId(), 0);
                return storeListForProvince;
            }
        }
        if ("1".equals(areaLevel)) {
            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, "当前银行用户不存在银行信息");
                    }
                    if (YXZT.NOT_SELECTED.getCode().equals(pageReqVO.getYxcf())) {
                        pageReqVO.setType(1);
                        List<StoreRespVO> storeListForBank = provinceMapper.getStoreListForProvince(pageReqVO);
                        List<StoreRespVO> storeListSelelct = bankMapper.getStoreListForBank(pageReqVO.getKqId(),bankType);
                        if (!ObjectUtils.isEmpty(storeListForBank)) {
                            if (!ObjectUtils.isEmpty(storeListSelelct)) {
                                List<Long> idsExist = storeListSelelct.stream().map(StoreRespVO::getId).collect(Collectors.toList());
                                if (!ObjectUtils.isEmpty(idsExist)) {
                                    storeListForBank.removeIf(a -> idsExist.contains(a.getId()));
                                }
                            }
                            return storeListForBank;
                        }
                    } else if (YXZT.SELECTED.getCode().equals(pageReqVO.getYxcf()) || YXZT.OPTION.getCode().equals(pageReqVO.getYxcf())) {
                        List<StoreRespVO> storeListForBank = bankMapper.getStoreListForBank(pageReqVO.getKqId(),bankType);
                        return storeListForBank;
                    } else if (YXZT.IDENTIFY.getCode().equals(pageReqVO.getYxcf())) {
                        List<StoreRespVO> storeRespVOS = caxxMapper.selectListForIdentify(pageReqVO.getKqId(), bankType);
                        return storeRespVOS;
                    } else if (YXZT.SELECT.getCode().equals(pageReqVO.getYxcf())) {
                        List<StoreRespVO> storeRespVOS = caxxMapper.selectListForSelect(pageReqVO.getKqId(), bankType);
                        return storeRespVOS;
                    }
                } else {// 省已选
                    if (YXZT.NOT_SELECTED.getCode().equals(pageReqVO.getYxcf())) {
                        List<CaxxDO> caxxDOS = caxxMapper.selectList(pageReqVO);
                        List<StoreRespVO> storeListSelect = provinceMapper.getStoreListForProvinceOnly(pageReqVO.getKqId(), 0);
                        List<StoreRespVO> storeListForProvice = new ArrayList<>();
                        if (!ObjectUtils.isEmpty(caxxDOS)) {
                            if (!ObjectUtils.isEmpty(storeListSelect)) {
                                List<Long> idsExist = storeListSelect.stream().map(StoreRespVO::getId).collect(Collectors.toList());
                                if (!ObjectUtils.isEmpty(idsExist)) {
                                    caxxDOS.removeIf(a -> idsExist.contains(a.getId()));
                                }
                            }
                            if (!ObjectUtils.isEmpty(caxxDOS)) {
                                caxxDOS.stream().forEach(s->{
                                    if (s.getSjcr()!=null) {
                                        BigDecimal truncatedNumber = s.getSjcr().setScale(0, RoundingMode.DOWN);
                                        s.setSjcr(truncatedNumber);
                                    }
                                });
                                storeListForProvice = BeanUtils.toBean(caxxDOS, StoreRespVO.class);
                            }
                            return storeListForProvice;
                        }
                    } else if (YXZT.SELECTED.getCode().equals(pageReqVO.getYxcf()) || YXZT.OPTION.getCode().equals(pageReqVO.getYxcf())) {
                        List<StoreRespVO> storeListForProvince = provinceMapper.getStoreListForProvinceOnly(pageReqVO.getKqId(), 0);
                        return storeListForProvince;
                    } else if (YXZT.IDENTIFY.getCode().equals(pageReqVO.getYxcf())) {
                        List<StoreRespVO> storeRespVOS = caxxMapper.selectListForIdentify(pageReqVO.getKqId(), pageReqVO.getYhmc());
                        return storeRespVOS;
                    } else if (YXZT.SELECT.getCode().equals(pageReqVO.getYxcf())) {
                        List<StoreRespVO> storeRespVOS = caxxMapper.selectListForSelect(pageReqVO.getKqId(), pageReqVO.getYhmc());
                        return storeRespVOS;
                    }

                }
            }
        }
        return null;
    }

    @Override
    @Transactional
    public void updateSelectedCaxx(CaxxUpdateReqVO updateReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            throw exception(ERROR, "不存在用户信息");
        }
        String areaLevel = loginUser.getInfo().get("areaLevel");
        // 国家交易中心已选
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            //信息存入新表
            createCaAndKuAndDWForSheng(updateReqVO);
        }
        if ("1".equals(areaLevel)) {
            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, "当前银行用户不存在银行信息");
                    }
                    DictDataDO dictBank = dictDataMapper.selectByDictTypeAndValue("bank_type", bankType);
                    if (ObjectUtils.isEmpty(dictBank)) {
                        throw exception(ERROR, "当前银行用户不存在字典信息");
                    }
                    List<BankDO> bankDOS = new ArrayList<>();
                    for (Long caId : updateReqVO.getIds()) {
                        BankDO bankDO = new BankDO();
                        bankDO.setCaId(caId);
                        bankDO.setKqId(updateReqVO.getKqId());
                        bankDO.setId(YitIdHelper.nextId());
                        bankDO.setDeleted(false);
                        bankDO.setRdyhId(bankType);
                        bankDO.setHyState(0);
                        bankDO.setHyryName(dictBank.getLabel());
                        bankDOS.add(bankDO);
                    }
                    if (!ObjectUtils.isEmpty(bankDOS)) {
                        bankMapper.insertBatch(bankDOS);
                    }
                } else {// 省已选
                    List<ProvinceDO> provinceDOS = new ArrayList<>();
                    for (Long caId : updateReqVO.getIds()) {
                        ProvinceDO province = new ProvinceDO();
                        province.setCaId(caId);
                        province.setKqId(updateReqVO.getKqId());
                        province.setId(YitIdHelper.nextId());
                        province.setDeleted(false);
                        provinceDOS.add(province);
                    }
                    if (!ObjectUtils.isEmpty(provinceDOS)) {
                        provinceMapper.insertBatch(provinceDOS);
                    }
                }
            }
        }
    }

    @Override
    @Transactional
    public void revertCaxx(CaxxUpdateReqVO updateReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            throw exception(ERROR, "不存在用户信息");
        }
        String areaLevel = loginUser.getInfo().get("areaLevel");
        // 国家交易中心
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            //校验是否该仓房是否存在省已经选用或者银行已经选用
            List<ProvinceDO> provinceDOS = provinceMapper.selectListBycaIds(updateReqVO.getIds());
            if (!ObjectUtils.isEmpty(provinceDOS)) {
                throw exception(ERROR, "存在仓房已经被省选用");
            }
            List<BankDO> bankDOS = bankMapper.selectListBycaIds(updateReqVO.getIds());
            if (!ObjectUtils.isEmpty(bankDOS)) {
                throw exception(ERROR, "存在仓房已经被银行选用");
            }
            List<UsersDO> usersDOS = usersMapper.selectListBycaIds(updateReqVO.getIds());
            if (!ObjectUtils.isEmpty(usersDOS)) {
                throw exception(ERROR, "存在仓房已经存粮人被选用");
            }
            caxxMapper.deleteByIds(updateReqVO.getIds());
            List<CaxxDO> caxxDOS = caxxMapper.selectListByKqId(updateReqVO.getKqId());
            if (ObjectUtils.isEmpty(caxxDOS)) {
                kqxxMapper.deleteByKqId(updateReqVO.getKqId());
                CwxxDO cwxxDO = cwxxMapper.selectByKqId(updateReqVO.getKqId());
                if (!ObjectUtil.isEmpty(cwxxDO)) {
                    Long cwxxDOId = cwxxDO.getId();
                    cwxxMapper.deleteById(cwxxDOId);
                    cwxxYearMapper.deleteListByCwxxId(cwxxDOId);
                }
                //校验是否存在使用该库区单位的其他库区,不存在其他库区则删除该单位信息
                List<KqxxDO> kqxxDOS = kqxxMapper.selectListByDwId(updateReqVO.getDeptId());
                if (ObjectUtils.isEmpty(kqxxDOS)) {
                    dwxxMapper.deleteByDwId(updateReqVO.getDeptId());
                }
            }
        }
        if ("1".equals(areaLevel)) {
            //获取当前用户角色
            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, "当前银行用户不存在银行信息");
                    }
                    // 银行已选
                    List<UsersDO> usersDOS = usersMapper.selectListBycaIds(updateReqVO.getIds());
                    if (!ObjectUtils.isEmpty(usersDOS)) {
                        throw exception(ERROR, "存在仓房已经存粮人被选用");
                    }
                    bankMapper.deleteListByKqIdAndCaIdsAndBank(updateReqVO.getKqId(), updateReqVO.getIds(), bankType);
                } else {
                    // 省已选,先校验是否存在银行已经选的
                    List<BankDO> bankDOS = bankMapper.selectListBycaIds(updateReqVO.getIds());
                    if (!ObjectUtils.isEmpty(bankDOS)) {
                        throw exception(ERROR, "存在仓房已经被银行选用");
                    }
                    List<UsersDO> usersDOS = usersMapper.selectListBycaIds(updateReqVO.getIds());
                    if (!ObjectUtils.isEmpty(usersDOS)) {
                        throw exception(ERROR, "存在仓房已经存粮人被选用");
                    }
                    provinceMapper.deleteListByKqIdAndCaIds(updateReqVO.getKqId(), updateReqVO.getIds());
                    KqxxDO kqxxDO = kqxxMapper.selectById(updateReqVO.getKqId());
                    if (ObjectUtils.isEmpty(kqxxDO)) {
                        throw exception(ERROR, "库区信息不存在");
                    }
                    Integer sjly = kqxxDO.getSjly();
                    if (sjly != null && sjly == 0) {
                        //新建的库区，如果省退回全部的仓房则删除库区的全部信息
                        List<ProvinceDO> provinceDOS = provinceMapper.selectListByKqId(updateReqVO.getKqId());
                        if (ObjectUtils.isEmpty(provinceDOS)) {
                            kqxxMapper.deleteByKqId(updateReqVO.getKqId());
                            caxxMapper.deleteListByKqId(updateReqVO.getKqId());
                            CwxxDO cwxxDO = cwxxMapper.selectByKqId(updateReqVO.getKqId());
                            if (!ObjectUtil.isEmpty(cwxxDO)) {
                                Long cwxxDOId = cwxxDO.getId();
                                cwxxMapper.deleteById(cwxxDOId);
                                cwxxYearMapper.deleteListByCwxxId(cwxxDOId);
                            }
                            //校验是否存在使用该库区单位的其他库区,不存在其他库区则删除该单位信息
                            List<KqxxDO> kqxxDOS = kqxxMapper.selectListByDwId(updateReqVO.getDeptId());
                            if (ObjectUtils.isEmpty(kqxxDOS)) {
                                dwxxMapper.deleteByDwId(updateReqVO.getDeptId());
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    @Transactional
    public void revertKqxx(CaxxUpdateReqVO updateReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            throw exception(ERROR, "不存在用户信息");
        }
        List<Long> kqIds = updateReqVO.getKqIds();
        if (ObjectUtil.isEmpty(kqIds)) {
            throw exception(ERROR, "未选择库区");
        }
        String areaLevel = loginUser.getInfo().get("areaLevel");
        // 国家交易中心
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            if (!ObjectUtil.isEmpty(kqIds)) {
                for (Long kqId : kqIds) {
                    KqxxDO kqxxDO = kqxxMapper.selectById(kqId);
                    if (ObjectUtils.isEmpty(kqxxDO)) {
                        throw exception(ERROR, "库区信息不存在");
                    }
                    //校验是否该库区是否存在省已经选用或者银行已经选用
                    List<ProvinceDO> provinceDOS = provinceMapper.selectListByKqId(kqId);
                    if (!ObjectUtils.isEmpty(provinceDOS)) {
                        throw exception(ERROR, "存在库区已经被省选用,不允许删除!");
                    }
                    List<BankDO> bankDOS = bankMapper.selectListByKqId(kqId);
                    if (!ObjectUtils.isEmpty(bankDOS)) {
                        throw exception(ERROR, "存在库区已经被银行选用,不允许删除!");
                    }
                    List<UsersDO> usersDOS = usersMapper.selectListByKqId(kqId);
                    if (!ObjectUtils.isEmpty(usersDOS)) {
                        throw exception(ERROR, "存在仓房已经存粮人被选用");
                    }
                    Long dwId = kqxxDO.getDwid();
                    caxxMapper.deleteListByKqId(kqId);
                    kqxxMapper.deleteByKqId(kqId);
                    CwxxDO cwxxDO = cwxxMapper.selectByKqId(kqId);
                    if (!ObjectUtil.isEmpty(cwxxDO)) {
                        Long cwxxDOId = cwxxDO.getId();
                        cwxxMapper.deleteById(cwxxDOId);
                        cwxxYearMapper.deleteListByCwxxId(cwxxDOId);
                    }
                    //校验是否存在使用该库区单位的其他库区,不存在其他库区则删除该单位信息
                    List<KqxxDO> kqxxDOS = kqxxMapper.selectListByDwId(dwId);
                    if (ObjectUtils.isEmpty(kqxxDOS)) {
                        dwxxMapper.deleteByDwId(dwId);
                    }
                }
            }
        }
        if ("1".equals(areaLevel)) {
            //获取当前用户角色
            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, "当前银行用户不存在银行信息");
                    }
                    for (Long kqId : kqIds) {
                        KqxxDO kqxxDO = kqxxMapper.selectById(kqId);
                        if (ObjectUtils.isEmpty(kqxxDO)) {
                            throw exception(ERROR, "库区信息不存在");
                        }
                        List<UsersDO> usersDOS = usersMapper.selectListByKqId(kqId);
                        if (!ObjectUtils.isEmpty(usersDOS)) {
                            throw exception(ERROR, "存在仓房已经存粮人被选用");
                        }
                    }
                    bankMapper.deleteListByKqIdsAndBank(kqIds, bankType);
                } else {
                    // 省已选
                    provinceMapper.deleteListByKqIds(kqIds);
                    if (!ObjectUtil.isEmpty(kqIds)) {
                        for (Long kqId : kqIds) {
                            KqxxDO kqxxDO = kqxxMapper.selectById(kqId);
                            if (ObjectUtils.isEmpty(kqxxDO)) {
                                throw exception(ERROR, "库区信息不存在");
                            }
                            List<BankDO> bankDOS = bankMapper.selectListByKqId(kqId);
                            if (!ObjectUtils.isEmpty(bankDOS)) {
                                throw exception(ERROR, "存在库区已经被银行选用,不允许删除!");
                            }
                            List<UsersDO> usersDOS = usersMapper.selectListByKqId(kqId);
                            if (!ObjectUtils.isEmpty(usersDOS)) {
                                throw exception(ERROR, "存在仓房已经存粮人被选用");
                            }
                            Long dwId = kqxxDO.getDwid();
                            Integer sjly = kqxxDO.getSjly();
                            if (sjly != null && sjly == 0) {
                                //新建的库区，如果省退回全部的仓房则删除库区的全部信息
                                List<ProvinceDO> provinceDOS = provinceMapper.selectListByKqId(kqId);
                                if (ObjectUtils.isEmpty(provinceDOS)) {
                                    caxxMapper.deleteListByKqId(kqId);
                                    kqxxMapper.deleteByKqId(kqId);
                                    CwxxDO cwxxDO = cwxxMapper.selectByKqId(kqId);
                                    if (!ObjectUtil.isEmpty(cwxxDO)) {
                                        Long cwxxDOId = cwxxDO.getId();
                                        cwxxMapper.deleteById(cwxxDOId);
                                        cwxxYearMapper.deleteListByCwxxId(cwxxDOId);
                                    }
                                    //校验是否存在使用该库区单位的其他库区,不存在其他库区则删除该单位信息
                                    List<KqxxDO> kqxxDOS = kqxxMapper.selectListByDwId(dwId);
                                    if (ObjectUtils.isEmpty(kqxxDOS)) {
                                        dwxxMapper.deleteByDwId(dwId);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public PageResult<SpareRespVO> getProvinceSelectedPage(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(), "%"));
        }
        Page<SpareRespVO> page = new Page<SpareRespVO>();
        // 国家交易中心已选
        if ("0".equals(areaLevel) || ObjectUtil.isEmpty(areaLevel)) {
            page = caxxMapper.selectWrapperPageForSheng(new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
        }
        return new PageResult<SpareRespVO>(page.getRecords(), page.getTotal());
    }

    @Override
    public DwxxDO getDwxxByKqBm() {
        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> KqxxDO = kqxxMapper.selectList(new QueryWrapper<KqxxDO>().eq("KQBM", kqbm));
        if (CollectionUtils.isEmpty(KqxxDO)) {
            throw exception(ERROR, "当前库区编码下无库区信息");
        }
        DwxxDO dwxxDO = dwxxMapper.selectById(KqxxDO.get(0).getDwid());
        return dwxxDO;
    }


    @Transactional
    public void createCaAndKuAndDWForSheng(CaxxUpdateReqVO updateReqVO) {
        if (updateReqVO.getKqId() != null) {
            KqxxDO kqxxDOExist = kqxxMapper.selectById(updateReqVO.getKqId());
            if (ObjectUtils.isEmpty(kqxxDOExist)) {
                CodingKqxxDO codingKqxxDO = codingKqxxMapper.selectById(updateReqVO.getKqId());
                if (ObjectUtils.isEmpty(codingKqxxDO)) {
                    throw exception(ERROR, "当前库区信息不存在！");
                }
                List<FmxxDO> fmxxDOS = fmxxMapper.selectListByKqId(updateReqVO.getKqId());
                if (ObjectUtils.isEmpty(fmxxDOS)) {
                    throw exception(ERROR, "当前库区的赋码信息不存在！");
                }
                String kqbm = fmxxDOS.get(0).getKqdm();
                KqxxDO kqxxDO = BeanUtils.toBean(codingKqxxDO, KqxxDO.class);
                String shengAll = kqxxDO.getSheng();
                String[] parts = shengAll.split(",");
                for (int i = 0; i < parts.length; i++) {
                    parts[i] = parts[i].trim(); // 去除空格
                }
                String province = null;
                String city = null;
                String county = null;
                if (parts.length != 0) {
                    province = parts[0];
                    if (parts.length == 3) {
                        if (Arrays.asList(CityConstants.CITY).contains(province)) {
                            city = parts[2];
                            if (parts[2] == null || parts[2].isEmpty()) {
                                city = parts[1];
                            }
                        }else {
                            city = parts[1];
                            county = parts[2];
                        }
                    }
                    if (parts.length == 2) {
                        if (!Arrays.asList(CityConstants.CITY).contains(province)) {
                            city = parts[1];
                        }
                    }
                }
                List<AreaLevelDO> areaLevelDOS = areaLevelMapper.selectListByName(Arrays.asList(province, city, county));
                if (ObjectUtils.isEmpty(areaLevelDOS)) {
                    throw exception(ERROR, "当前库区所在的行政区划不存在！");
                }
                Map<String, String> map = areaLevelDOS.stream().collect(Collectors.toMap(AreaLevelDO::getAreaName, AreaLevelDO::getAreaCode, (x, y) -> x));
                if (province != null) {
                    String shengCode = map.get(province);
                    kqxxDO.setSheng(shengCode);
                    kqxxDO.setShengName(province);
                }
                if (city != null) {
                    String shiCode = map.get(city);
                    kqxxDO.setShi(shiCode);
                    kqxxDO.setShiName(city);
                }
                if (county != null) {
                    String xianCode = map.get(county);
                    kqxxDO.setXian(xianCode);
                    kqxxDO.setXianName(county);
                }
                kqxxDO.setSjly(1);
                kqxxDO.setKqbm(kqbm);
                kqxxMapper.insert(kqxxDO);
            }
        }
        if (updateReqVO.getDeptId() != null) {
            //一个单位对应多个库区
            DwxxDO dwxxDOExist = dwxxMapper.selectById(updateReqVO.getDeptId());
            if (ObjectUtils.isEmpty(dwxxDOExist)) {
                CodingDwxxDO codingDwxxDO = codingDwxxMapper.selectById(updateReqVO.getDeptId());
                if (ObjectUtils.isEmpty(codingDwxxDO)) {
                    throw exception(ERROR, "当前单位信息不存在！");
                }
                DwxxDO dwxxDO = BeanUtils.toBean(codingDwxxDO, DwxxDO.class);
                dwxxDO.setSjly(1);
                dwxxMapper.insert(dwxxDO);
            }
        }
        if (!ObjectUtils.isEmpty(updateReqVO.getIds())) {
            List<CodingCaxxDO> codingCaxxDOS = codingCaxxMapper.selectList(CodingCaxxDO::getId, updateReqVO.getIds());
            if (ObjectUtils.isEmpty(codingCaxxDOS)) {
                throw exception(ERROR, "所选仓房信息不存在！");
            }
            List<FmxxDO> fmxxDOS = fmxxMapper.selectListByCaId(updateReqVO.getIds());
            if (ObjectUtils.isEmpty(fmxxDOS)) {
                throw exception(ERROR, "当前所选仓房的赋码信息不存在");
            }
            Map<Long, String> dmMap = fmxxDOS.stream().filter(s -> s.getBaseCaxxId() != null).collect(Collectors.toMap(FmxxDO::getBaseCaxxId, FmxxDO::getCfdm, (x, y) -> x));
            List<CaxxDO> caxxDOSExist = caxxMapper.selectListByKqId(updateReqVO.getKqId());
            List<CaxxDO> caxxDOS = BeanUtils.toBean(codingCaxxDOS, CaxxDO.class);
            if (!ObjectUtils.isEmpty(caxxDOS)) {
                if (!ObjectUtils.isEmpty(caxxDOSExist)) {
                    List<Long> idsExist = caxxDOSExist.stream().map(CaxxDO::getId).collect(Collectors.toList());
                    caxxDOS.removeIf(caxxDO -> idsExist.contains(caxxDO.getId()));
                }
                if (!ObjectUtils.isEmpty(caxxDOS)) {
                    caxxDOS.stream().forEach(s -> {
                        s.setSjly(1);
                        s.setYxcf(1);
                        String caDm = dmMap.get(s.getId());
                        s.setCfdm(caDm);
                    });
                    caxxMapper.insertBatch(caxxDOS);
                }
            }
        }
    }


    @Override
    public void deleteceshi(Long id) {
        //删除单位
        dwxxMapper.deleteById(id);
        //查询单位id
        List<KqxxDO> kqid = kqxxMapper.selectList(new QueryWrapper<KqxxDO>().eq("DWID", id));
        //删除库区
        kqxxMapper.delete(new QueryWrapper<KqxxDO>().eq("DWID", id));
        //删除仓房
        caxxMapper.delete(new QueryWrapper<CaxxDO>().eq("KQID", kqid.get(0).getId()));
        //查询单位id
        List<CwxxDO> cwxxDOS = cwxxMapper.selectList(new QueryWrapper<CwxxDO>().eq("KQID", id));
        //删除财务
        cwxxMapper.delete(new QueryWrapper<CwxxDO>().eq("KQID", kqid.get(0).getId()));
        //删除财年信息
        cwxxYearMapper.delete(new QueryWrapper<CwxxYearDO>().eq("CWXX_ID", cwxxDOS.get(0).getId()));

    }

}