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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.unis.framework.common.util.orderNum.OrderNumberUtil;
import com.unis.module.coding.controller.admin.caxx.vo.CaxxSaveReqVO;
import com.unis.module.coding.controller.admin.cwxx.vo.CwxxSaveReqVO;
import com.unis.module.coding.controller.admin.cwxxyear.vo.CwxxYearSaveReqVO;
import com.unis.module.coding.controller.admin.delivery.vo.CaxxUpdateReqVO;
import com.unis.module.coding.controller.admin.delivery.vo.DeliverySaveVO;
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.kqxx.KqxxDO;
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.kqxx.KqxxMapper;
import com.unis.module.coding.service.caxx.CaxxService;
import com.unis.module.coding.service.cwxx.CwxxService;
import com.unis.module.coding.service.cwxxyear.CwxxYearService;
import com.unis.module.coding.service.dwxx.DwxxService;
import com.unis.module.coding.service.kqxx.KqxxService;
import com.unis.module.system.dal.dataobject.arealevel.AreaLevelDO;
import com.unis.module.system.dal.mysql.arealevel.AreaLevelMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

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

/**
 * @author qingsong.han
 * @description:
 * @create 2025-01-22 15:28
 */
@Service
@Slf4j
public class DeliveryServiceImpl implements DeliveryService {
    @Resource
    private DwxxService dwxxService;
    @Resource
    private KqxxService kqxxService;
    @Resource
    private KqxxMapper kqxxMapper;
    @Resource
    private CaxxService caxxService;
    @Resource
    private CwxxService cwxxService;
    @Resource
    private CwxxMapper cwxxMapper;
    @Resource
    private CwxxYearMapper cwxxYearMapper;
    @Resource
    private CwxxYearService cwxxYearService;
    @Resource
    private DwxxMapper dwxxMapper;
    @Resource
    private AreaLevelMapper areaLevelMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCaxxByIds(CaxxUpdateReqVO updateReqVO) {
        List<Long> ids = updateReqVO.getIds();
        if (CollectionUtils.isNotEmpty(ids)) {
            ids.forEach(id -> {
                CaxxSaveReqVO updateVO = new CaxxSaveReqVO();
                updateVO.setId(id);
                caxxService.updateCaxx(updateVO);
            });
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object createByAll(DeliverySaveVO createReqVO) {
        // 单位信息
        if (ObjectUtils.isNotEmpty(createReqVO.getDwxxReqVO())) {
            if (ObjectUtils.isEmpty(createReqVO.getDwxxReqVO().getTyxydm())) {
                throw exception(ERROR, "统一信用编码为空");
            }
            //根据统一信用编码----添加之前查询是否已经添加过该单位
            List<DwxxDO> tyxydm1 = dwxxMapper.selectList(
                    new QueryWrapper<DwxxDO>()
                            .eq("TYXYDM", createReqVO.getDwxxReqVO().getTyxydm()));

            log.info("根据统一信用编码查询单位是否存在,存在数量，({})", tyxydm1.size());
            Long dwxx = null;

            if (CollectionUtils.isEmpty(tyxydm1)) {
                createReqVO.getDwxxReqVO().setSjly(0);
                dwxx = dwxxService.createDwxx(createReqVO.getDwxxReqVO());
            } else {
                log.info("根据统一信用编码查询之前已经添加过该单位({})", tyxydm1.get(0).getId());
                dwxx = tyxydm1.get(0).getId();
                createReqVO.getDwxxReqVO().setId(dwxx);
                //是交收库新建的单位就能更新
                if (tyxydm1.get(0).getSjly().equals(0)) {
                    dwxxService.updateDwxx(createReqVO.getDwxxReqVO());
                } else {
                    log.info("该单位信息已经存在");
                    return null;
                }
            }
            ///--------库区信息-------------////////////////////////////////////////////////////////
            if (ObjectUtils.isNotEmpty(createReqVO.getKqxxReqVO())) {
                // set 单位id
                createReqVO.getKqxxReqVO().setDwid(dwxx);
                createReqVO.getKqxxReqVO().setShxydm(createReqVO.getDwxxReqVO().getTyxydm());
                /*
                 * 生成库区代码--该单位下有几个库区
                 */
                List<KqxxDO> count = kqxxMapper.selectList(
                        new QueryWrapper<KqxxDO>()
                                .eq("DWID", dwxx)
                                .orderByDesc("CREATE_TIME"));
                String countNum = count.size() == 0 ? "00" : count.get(0).getKqbm();
                //同一单位(DELIVERY_DWXX)下多个库区,生成规则 01 02 ...
                String kqdm = OrderNumberUtil.initNum(2, String.valueOf(countNum));

                createReqVO.getKqxxReqVO().setKqdm(kqdm);
                // 单位信息社会统一信用编码
                String tyxydm = createReqVO.getDwxxReqVO().getTyxydm();

                //企业性质
                String qyxz = createReqVO.getDwxxReqVO().getQyxz();
                //库区编码
                List kqbmlist = new ArrayList();
                kqbmlist.add(qyxz);//企业性质
                kqbmlist.add(tyxydm);//统一信用编码
                kqbmlist.add(kqdm);//库区代码
                String kqbm = OrderNumberUtil.generateCode(kqbmlist);
                log.info("获取库区编码({})", kqbm);

                createReqVO.getKqxxReqVO().setKqbm(kqbm);
                //所属法人企业(单位名称)
                createReqVO.getKqxxReqVO().setSsfrqy(createReqVO.getDwxxReqVO().getDwmc());
                //省市县编码获取
                if (ObjectUtils.isNotEmpty(createReqVO.getKqxxReqVO().getSheng())) {
                    AreaLevelDO sheng = areaLevelMapper.selectListByAreaCode(createReqVO.getKqxxReqVO().getSheng());
                    log.info("获取省市县编码对应的地址({})", sheng.getAreaName());
                    createReqVO.getKqxxReqVO().setShengName(sheng.getAreaName());
                }
                if (ObjectUtils.isNotEmpty(createReqVO.getKqxxReqVO().getShi())) {
                    AreaLevelDO shi = areaLevelMapper.selectListByAreaCode(createReqVO.getKqxxReqVO().getShi());
                    log.info("获取省市县编码对应的地址({})", shi.getAreaName());
                    createReqVO.getKqxxReqVO().setShiName(shi.getAreaName());
                }
                if (ObjectUtils.isNotEmpty(createReqVO.getKqxxReqVO().getXian())) {
                    AreaLevelDO xian = areaLevelMapper.selectListByAreaCode(createReqVO.getKqxxReqVO().getXian());
                    log.info("获取省市县编码对应的地址({})", xian.getAreaName());
                    createReqVO.getKqxxReqVO().setXianName(xian.getAreaName());
                }
                Long kqxx = kqxxService.createKqxx(createReqVO.getKqxxReqVO());
                // -------仓房信息---------------
                if (CollectionUtils.isNotEmpty(createReqVO.getCaxxReqVOList())) {
                    //库区编码
                    String finalKqbm = kqbm;
                    createReqVO.getCaxxReqVOList().forEach(caxx -> {
                        caxx.setYxcf(1);
                        caxx.setKqid(kqxx);
                        caxx.setKqmc(createReqVO.getKqxxReqVO().getKqmc());
                        //仓房代码生成
                        List cfdnlist = new ArrayList();
                        cfdnlist.add(finalKqbm);//统一信用编码
                        cfdnlist.add(caxx.getCfbm());//库区代码
                        String cfdn = OrderNumberUtil.generateCode(cfdnlist);
                        caxx.setCfdm(cfdn);
                        caxxService.createCaxx(caxx);
                        log.info("仓房({})的仓房编码为({})", cfdn);
                    });
                }
                // --财务信息--------------------
                CwxxSaveReqVO cwxxReqVO = createReqVO.getCwxxReqVO();
                if (ObjectUtils.isNotEmpty(cwxxReqVO)) {
                    cwxxReqVO.setKqid(kqxx);
                    cwxxReqVO.setDeptId(dwxx);
                    Long cwxx = cwxxService.createCwxx(cwxxReqVO);
                    // ---财年信息-------------
                    if (CollectionUtils.isNotEmpty(cwxxReqVO.getCwxxYearList())) {
                        for (CwxxYearSaveReqVO cwxxYear : cwxxReqVO.getCwxxYearList()) {
                            cwxxYear.setCwxxId(cwxx);
                            cwxxYearService.createCwxxYear(cwxxYear);
                        }

                    }
                }
            }
        }
        // 交通运输情况
        return null;
    }

}

