package com.ruoyi.buyerapi.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.buyerapi.domain.*;
import com.ruoyi.buyerapi.mapper.BuyerFileInfoMapper;
import com.ruoyi.buyerapi.mapper.BuyerVoucherInfoMapper;
import com.ruoyi.buyerapi.mapper.BuyerVoucherProjectMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.buyerapi.mapper.BuyerAuxiliaryVoucherMapper;
import com.ruoyi.buyerapi.service.IBuyerAuxiliaryVoucherService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 辅助帐凭证Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-22
 */
@Service
public class BuyerAuxiliaryVoucherServiceImpl implements IBuyerAuxiliaryVoucherService
{
    @Autowired
    private BuyerAuxiliaryVoucherMapper buyerAuxiliaryVoucherMapper;

    @Autowired
    private BuyerVoucherInfoMapper buyerVoucherInfoMapper;

    @Autowired
    private BuyerVoucherProjectMapper buyerVoucherProjectMapper;

    @Autowired
    private BuyerFileInfoMapper buyerFileInfoMapper;

    /**
     * 查询辅助帐凭证
     *
     * @param id 辅助帐凭证主键
     * @return 辅助帐凭证
     */
    @Override
    public BuyerAuxiliaryVoucher selectBuyerAuxiliaryVoucherById(String id)
    {
        return buyerAuxiliaryVoucherMapper.selectBuyerAuxiliaryVoucherById(id);
    }

    /**
     * 查询辅助帐凭证列表
     *
     * @param buyerAuxiliaryVoucher 辅助帐凭证
     * @return 辅助帐凭证
     */
    @Override
    public List<BuyerAuxiliaryVoucher> selectBuyerAuxiliaryVoucherList(BuyerAuxiliaryVoucher buyerAuxiliaryVoucher)
    {
        List<BuyerAuxiliaryVoucher> list = buyerAuxiliaryVoucherMapper.selectBuyerAuxiliaryVoucherList(buyerAuxiliaryVoucher);
        for(BuyerAuxiliaryVoucher auxiliaryVoucher : list){
            // 查询凭证详情
            BuyerVoucherInfo info = new BuyerVoucherInfo();
            info.setVoucherId(auxiliaryVoucher.getId());
            auxiliaryVoucher.setBuyerVoucherInfos(buyerVoucherInfoMapper.selectBuyerVoucherInfoList(info));
            // 查询项目情况
            List<BuyerVoucherProjectGroupBySubject> buyerVoucherProjectGroupBySubjects = new ArrayList<>();
            for(BuyerVoucherInfo buyerVoucherInfo : auxiliaryVoucher.getBuyerVoucherInfos()){
                // 处理科目是研发费用的项目
                if("type1" .equals(buyerVoucherInfo.getSubject1())){
                    BuyerVoucherProjectGroupBySubject subject = new BuyerVoucherProjectGroupBySubject();
                    subject.setSubject(buyerVoucherInfo.getSubject2());
                    subject.setSubjectLabel(buyerVoucherInfo.getSubject2Label());
                    BuyerVoucherProject project = new BuyerVoucherProject();
                    project.setVoucherId(auxiliaryVoucher.getId());
                    project.setSubject(buyerVoucherInfo.getSubject2());
                    List<BuyerVoucherProject> projectList = buyerVoucherProjectMapper.selectBuyerVoucherProjectList(project);
                    if(null != projectList && projectList.size() > 0){
                        subject.setBuyerVoucherProjects(projectList);
                        buyerVoucherProjectGroupBySubjects.add(subject);
                    }
                }
            }

            // 查询文件列表
            auxiliaryVoucher.setBuyerFileInfos(buyerFileInfoMapper.selectBuyerFileInfoByLinkId(auxiliaryVoucher.getId()));
            auxiliaryVoucher.setBuyerVoucherProjects(buyerVoucherProjectGroupBySubjects);
        }
        return list;
    }

    /**
     * 新增辅助帐凭证
     *
     * @param buyerAuxiliaryVoucher 辅助帐凭证
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBuyerAuxiliaryVoucher(BuyerAuxiliaryVoucher buyerAuxiliaryVoucher)
    {
        buyerAuxiliaryVoucher.setCreateTime(DateUtils.getNowDate());
        buyerAuxiliaryVoucher.setDeptId(SecurityUtils.getCompanyId());

        // 凭证总金额
        BigDecimal total = new BigDecimal(0);

        // 添加凭证详细信息
        for(int i = 0; i < buyerAuxiliaryVoucher.getBuyerVoucherInfos().size(); i++){
            buyerAuxiliaryVoucher.getBuyerVoucherInfos().get(i).setId(IdUtil.simpleUUID());
            buyerAuxiliaryVoucher.getBuyerVoucherInfos().get(i).setCreateTime(DateUtils.getNowDate());
            buyerAuxiliaryVoucher.getBuyerVoucherInfos().get(i).setCreateBy(buyerAuxiliaryVoucher.getCreateBy());
            buyerAuxiliaryVoucher.getBuyerVoucherInfos().get(i).setCompanyId(SecurityUtils.getCompanyId());
            buyerAuxiliaryVoucher.getBuyerVoucherInfos().get(i).setVoucherId(buyerAuxiliaryVoucher.getId());
            buyerAuxiliaryVoucher.getBuyerVoucherInfos().get(i).setOrderIndex(i);
            NumberUtil.add(total, buyerAuxiliaryVoucher.getBuyerVoucherInfos().get(i).getCreditBalance());
            buyerVoucherInfoMapper.insertBuyerVoucherInfo(buyerAuxiliaryVoucher.getBuyerVoucherInfos().get(i));
        }

        // 添加关联附件
        for(BuyerFileInfo buyerFileInfo : buyerAuxiliaryVoucher.getBuyerFileInfos()){
            buyerFileInfo.setId(IdUtil.simpleUUID());
            buyerFileInfo.setLinkId(buyerAuxiliaryVoucher.getId());
            buyerFileInfoMapper.insertBuyerFileInfo(buyerFileInfo);
        }
        buyerAuxiliaryVoucher.setBalance(total);
        return buyerAuxiliaryVoucherMapper.insertBuyerAuxiliaryVoucher(buyerAuxiliaryVoucher);
    }

    @Override
    @Transactional
    public int importTable(MultipartFile file) throws Exception {
        Map<String, String> map1 = new HashMap<>();
        map1.put("研发费用", "type1");
        map1.put("应付职工薪酬", "type2");
        map1.put("原材料", "type3");
        map1.put("其他应付款", "type4");
        map1.put("应付账款", "type5");
        map1.put("累计折旧", "type6");
        map1.put("累计摊销", "type7");
        map1.put("长期待摊费用", "type8");
        map1.put("管理费用", "type9");
        Map<String, String> map2 = new HashMap<>();
        map2.put("人员人工费用", "type1");
        map2.put("直接投入费用", "type2");
        map2.put("折旧费用与长期待摊费用", "type3");
        map2.put("无形资产摊销费用", "type4");
        map2.put("设计费用", "type5");
        map2.put("委托外部研发开发费用（境内）", "type7");
        map2.put("委托外部研发开发费用（境外）", "type8");
        map2.put("其他费用", "type9");
        ExcelUtil<BuyerAuxiliaryVoucherExcel> util = new ExcelUtil<>(BuyerAuxiliaryVoucherExcel.class);
        List<BuyerAuxiliaryVoucherExcel> buyerAuxiliaryVouchers = util.importExcel(file.getInputStream());
        BuyerAuxiliaryVoucher buyerAuxiliaryVoucher = null;
        for (int i = 0; i < buyerAuxiliaryVouchers.size(); i++) {
            BuyerAuxiliaryVoucherExcel buyerAuxiliaryVoucherExcel = buyerAuxiliaryVouchers.get(i);
            BuyerVoucherInfo buyerVoucherInfo = new BuyerVoucherInfo();
            buyerVoucherInfo.setId(IdUtil.simpleUUID());
            buyerVoucherInfo.setSummary(buyerAuxiliaryVoucherExcel.getSummary());
            buyerVoucherInfo.setSubject1(map1.containsKey(buyerAuxiliaryVoucherExcel.getSubject1()) ? map1.get(buyerAuxiliaryVoucherExcel.getSubject1()) : buyerAuxiliaryVoucherExcel.getSubject1());
            buyerVoucherInfo.setSubject2(map2.containsKey(buyerAuxiliaryVoucherExcel.getSubject2()) ? map2.get(buyerAuxiliaryVoucherExcel.getSubject2()) : buyerAuxiliaryVoucherExcel.getSubject2());
            buyerVoucherInfo.setCreditBalance(StrUtil.isEmpty(buyerAuxiliaryVoucherExcel.getCreditBalance())
                    ? BigDecimal.valueOf(0) : new BigDecimal(buyerAuxiliaryVoucherExcel.getCreditBalance()));
            buyerVoucherInfo.setDebitBalance(StrUtil.isEmpty(buyerAuxiliaryVoucherExcel.getDebitBalance())
                    ? BigDecimal.valueOf(0) : new BigDecimal(buyerAuxiliaryVoucherExcel.getDebitBalance()));
            if(null == buyerAuxiliaryVoucher){
                buyerAuxiliaryVoucher = new BuyerAuxiliaryVoucher();
                buyerAuxiliaryVoucher.setId(IdUtil.simpleUUID());
                buyerAuxiliaryVoucher.setDate(buyerAuxiliaryVoucherExcel.getDate());
                buyerAuxiliaryVoucher.setType(buyerAuxiliaryVoucherExcel.getType());
                buyerAuxiliaryVoucher.setCode(buyerAuxiliaryVoucherExcel.getCode());
                buyerAuxiliaryVoucher.setProducer(buyerAuxiliaryVoucherExcel.getProducer());
                buyerAuxiliaryVoucher.setExpenseType(buyerAuxiliaryVoucherExcel.getExpenseType());
                buyerAuxiliaryVoucher.setCreateBy(SecurityUtils.getUsername());
                buyerAuxiliaryVoucher.setUpdateBy(SecurityUtils.getUsername());
                buyerAuxiliaryVoucher.setDeptId(SecurityUtils.getCompanyId());
            }else if(buyerAuxiliaryVoucherExcel.getAllStr().length() > 0
                    && !buyerAuxiliaryVoucherExcel.getAllStr()
                    .equals(buyerAuxiliaryVoucher.getDate() + buyerAuxiliaryVoucher.getType()
                            + buyerAuxiliaryVoucher.getCode() + buyerAuxiliaryVoucher.getProducer()
                            + buyerAuxiliaryVoucher.getExpenseType())){
                // 先保存上一个bean
                buyerAuxiliaryVoucherMapper.insertBuyerAuxiliaryVoucher(buyerAuxiliaryVoucher);

                // 判断本行是不是空行或者是不是等于前面的行都是一个凭证对象
                buyerAuxiliaryVoucher = new BuyerAuxiliaryVoucher();
                buyerAuxiliaryVoucher.setId(IdUtil.simpleUUID());
                buyerAuxiliaryVoucher.setDate(buyerAuxiliaryVoucherExcel.getDate());
                buyerAuxiliaryVoucher.setType(buyerAuxiliaryVoucherExcel.getType());
                buyerAuxiliaryVoucher.setCode(buyerAuxiliaryVoucherExcel.getCode());
                buyerAuxiliaryVoucher.setProducer(buyerAuxiliaryVoucherExcel.getProducer());
                buyerAuxiliaryVoucher.setExpenseType(buyerAuxiliaryVoucherExcel.getExpenseType());
                buyerAuxiliaryVoucher.setCreateBy(SecurityUtils.getUsername());
                buyerAuxiliaryVoucher.setUpdateBy(SecurityUtils.getUsername());
                buyerAuxiliaryVoucher.setDeptId(SecurityUtils.getCompanyId());
            }
            buyerVoucherInfo.setVoucherId(buyerAuxiliaryVoucher.getId());

            if(StrUtil.isNotEmpty(buyerAuxiliaryVoucherExcel.getCreditBalance()) && !"0".equals(buyerAuxiliaryVoucherExcel.getCreditBalance())){
                BigDecimal balance = new BigDecimal(buyerAuxiliaryVoucherExcel.getCreditBalance()).setScale(2, BigDecimal.ROUND_HALF_UP);
                buyerAuxiliaryVoucher.setBalance(null != buyerAuxiliaryVoucher.getBalance() ? buyerAuxiliaryVoucher.getBalance().add(balance) : balance);
                String[] ss = balance.toString().split("\\.");
                int zs = Integer.parseInt(ss[0]);
                int xs = Integer.parseInt(ss[1]);
                buyerVoucherInfo.setCreditUnit11(xs/1%10);
                buyerVoucherInfo.setCreditUnit10(xs/10%10);
                buyerVoucherInfo.setCreditUnit9(zs/1%10);
                buyerVoucherInfo.setCreditUnit8(zs/10%10);
                buyerVoucherInfo.setCreditUnit7(zs/100%10);
                buyerVoucherInfo.setCreditUnit6(zs/1000%10);
                buyerVoucherInfo.setCreditUnit5(zs/10000%10);
                buyerVoucherInfo.setCreditUnit4(zs/100000%10);
                buyerVoucherInfo.setCreditUnit3(zs/1000000%10);
                buyerVoucherInfo.setCreditUnit2(zs/10000000%10);
                buyerVoucherInfo.setCreditUnit1(zs/100000000%10);
            }

            if(StrUtil.isNotEmpty(buyerAuxiliaryVoucherExcel.getDebitBalance()) && !"0".equals(buyerAuxiliaryVoucherExcel.getDebitBalance())){
                BigDecimal balance = new BigDecimal(buyerAuxiliaryVoucherExcel.getDebitBalance()).setScale(2, BigDecimal.ROUND_HALF_UP);
                String[] ss = balance.toString().split("\\.");
                int zs = Integer.parseInt(ss[0]);
                int xs = Integer.parseInt(ss[1]);
                buyerVoucherInfo.setDebitUnit11(xs/1%10);
                buyerVoucherInfo.setDebitUnit10(xs/10%10);
                buyerVoucherInfo.setDebitUnit9(zs/1%10);
                buyerVoucherInfo.setDebitUnit8(zs/10%10);
                buyerVoucherInfo.setDebitUnit7(zs/100%10);
                buyerVoucherInfo.setDebitUnit6(zs/1000%10);
                buyerVoucherInfo.setDebitUnit5(zs/10000%10);
                buyerVoucherInfo.setDebitUnit4(zs/100000%10);
                buyerVoucherInfo.setDebitUnit3(zs/1000000%10);
                buyerVoucherInfo.setDebitUnit2(zs/10000000%10);
                buyerVoucherInfo.setDebitUnit1(zs/100000000%10);
            }
            buyerVoucherInfoMapper.insertBuyerVoucherInfo(buyerVoucherInfo);
            if(i == buyerAuxiliaryVouchers.size() - 1){
                // 保存最后一个bean
                buyerAuxiliaryVoucherMapper.insertBuyerAuxiliaryVoucher(buyerAuxiliaryVoucher);
            }
        }
        return buyerAuxiliaryVouchers.size();
    }

    /**
     * 修改辅助帐凭证
     *
     * @param buyerAuxiliaryVoucher 辅助帐凭证
     * @return 结果
     */
    @Override
    public int updateBuyerAuxiliaryVoucher(BuyerAuxiliaryVoucher buyerAuxiliaryVoucher)
    {
        buyerAuxiliaryVoucher.setUpdateTime(DateUtils.getNowDate());
        return buyerAuxiliaryVoucherMapper.updateBuyerAuxiliaryVoucher(buyerAuxiliaryVoucher);
    }

    /**
     * 批量删除辅助帐凭证
     *
     * @param ids 需要删除的辅助帐凭证主键
     * @return 结果
     */
    @Override
    public int deleteBuyerAuxiliaryVoucherByIds(String[] ids)
    {
        // 删除关联信息
        for(String id : ids){
            BuyerVoucherInfo info = new BuyerVoucherInfo();
            info.setVoucherId(id);
            buyerVoucherInfoMapper.deleteBuyerVoucherInfo(info);

            BuyerVoucherProject project = new BuyerVoucherProject();
            project.setVoucherId(id);
            buyerVoucherProjectMapper.deleteBuyerVoucherProject(project);
        }
        return buyerAuxiliaryVoucherMapper.deleteBuyerAuxiliaryVoucherByIds(ids);
    }

    @Override
    public int updateFileInfos(BuyerAuxiliaryVoucher buyerAuxiliaryVoucher) {
        // 先删除相关文件
        buyerFileInfoMapper.deleteBuyerFileInfoByLinkId(buyerAuxiliaryVoucher.getId());
        // 添加关联附件
        for(BuyerFileInfo buyerFileInfo : buyerAuxiliaryVoucher.getBuyerFileInfos()){
            buyerFileInfo.setId(IdUtil.simpleUUID());
            buyerFileInfo.setLinkId(buyerAuxiliaryVoucher.getId());
            buyerFileInfoMapper.insertBuyerFileInfo(buyerFileInfo);
        }
        return 1;
    }

    /**
     * 删除辅助帐凭证信息
     *
     * @param id 辅助帐凭证主键
     * @return 结果
     */
    @Override
    public int deleteBuyerAuxiliaryVoucherById(String id)
    {
        return buyerAuxiliaryVoucherMapper.deleteBuyerAuxiliaryVoucherById(id);
    }
}
