package com.sunxung.factoring.service.purchcontractmanagement.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.TableRenderData;
import com.deepoove.poi.data.Tables;
import com.deepoove.poi.data.style.BorderStyle;
import com.github.pagehelper.util.StringUtil;
import com.sunxung.factoring.component.datatransfer.WordWriter;
import com.sunxung.factoring.component.datatransfer.model.purchcontract.PurchContractChangeTemplateVo;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.ElectronicSignatureUtil;
import com.sunxung.factoring.component.util.fdd.TransactionIdCache;
import com.sunxung.factoring.entity.electronicsignature.FddSignData;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.purchcontractmanagement.*;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.mapper.purchcontractmanagement.PurchContractSupplementElectronicInfoMapper;
import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
import com.sunxung.factoring.service.customerinformation.CustomerService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.purchcontractmanagement.*;
import com.sunxung.factoring.service.supplier.ISupplierInfoService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购合同-补充电子合同信息表 服务实现类
 * </p>
 *
 * @author daxian
 * @since 2022-03-14
 */
@Service
public class PurchContractSupplementElectronicInfoServiceImpl extends ServiceImpl<PurchContractSupplementElectronicInfoMapper, PurchContractSupplementElectronicInfo> implements IPurchContractSupplementElectronicInfoService {

    @Autowired
    PurchContractService purchContractService;

    @Autowired
    BusinessBasicInfoService businessBasicInfoService;

    @Autowired
    IPurchContractSupplementInfoService supplementInfoService;

    @Autowired
    CustomerService customerService;

    @Autowired
    BusinessAssigneeService assigneeService;

    @Autowired
    FlowableService flowableService;

    @Autowired
    DictionaryService dictService;

    @Autowired
    IPurchContractSupplementGoodsInfoService supplementGoodsInfoService;

    @Autowired
    PurchContractBasicInfoService basicInfoService;

    @Autowired
    TransactionIdCache transactionIdCache;

    @Autowired
    UserService userService;

    @Autowired
    private IPurchContractSupplementApprovalService purchContractSupplementApprovalService;

    @Autowired
    private IUploadPurchSupplementContractService uploadPurchSupplementContractService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private IPurchSupplementContractSignConclusionService purchSupplementContractSignConclusionService;

    @Autowired
    private IPurchContractSupplementElectronicInfoService purchContractSupplementElectronicInfoService;

    @Autowired
    private IPurchContractSupplementInfoService purchContractSupplementInfoService;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Autowired
    private ISupplierInfoService supplierInfoService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IPurchContractSupplementApprovalCommentInfoService purchContractSupplementApprovalCommentInfoService;

    @Override
    public PurchContractSupplementElectronicInfo getView(Long id) {
        PurchContractSupplementElectronicInfo electronicInfo = getById(id);
        electronicInfo.setHistory(1);
        return electronicInfo;
    }


    /**
     * 制作合同：模板填充数据生成docx
     *
     * @param purchContractManagement
     * @param supplementInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public File makePurchContractDocx(PurchContractManagement purchContractManagement, PurchContractBasicInfo purchContractBasicInfo,
                                      Platform platform, PurchContractSupplementInfo supplementInfo, PurchContractSupplementApproval purchContractSupplementApproval) throws IOException {

        //获取对应供货商的企业客户信息
        SupplierInfo supplierCustomer = supplierInfoService.get(purchContractManagement.getSupplierId());
        Enterprise supplier = enterpriseService.getById(supplierCustomer.getcEnterpriseId());
        //获取业务买方对应的企业客户信息
//        Customer purchaserCustomer = customerService.getById(businessBasicInfo.getEnterpriseCustomerInfoId());
        DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        List<PurchContractSupplementGoodsInfo> goodsInfoList = supplementGoodsInfoService
                .lambdaQuery().eq(PurchContractSupplementGoodsInfo::getPurchContractSupplementInfoId, supplementInfo.getId()).list();

        PurchContractChangeTemplateVo templateVo = new PurchContractChangeTemplateVo();
        //合同编号
        templateVo.setContractNumber(supplementInfo.getSupplementContractNumber());
        //买方
        templateVo.setBuyerName(platform.getPlatformName());
        //买方社会统一信用代码
        templateVo.setBuyerSocialCreditCode(platform.getSocialCreditCode());
        //卖方
        templateVo.setSeller(purchContractBasicInfo.getSupplierName());
        //卖方社会统一信用代码
        templateVo.setSellerSocialCreditCode(supplier.getSocialCreditCode());
        //下游企业名称
        templateVo.setPurchaserName(purchContractBasicInfo.getBuyerName());
        //项目名称
        templateVo.setBusinessName(purchContractBasicInfo.getProjectName());
        //原合同名称
        templateVo.setOldContractName(purchContractBasicInfo.getContractName());
        //原合同编号
        templateVo.setOldContractNumber(purchContractBasicInfo.getContractNumber());
        //货物信息
        templateVo.setGoods(buildTableRenderData(goodsInfoList));
        //甲方单位名称
        templateVo.setCompanyPlatformName(platform.getPlatformName());
        //甲方签订日期
        templateVo.setCompanyPlatformDate(LocalDateTime.now().format(dfDateTime));
        //乙方单位名称
        templateVo.setCompanySupplierName(supplier.getCorporateName());
        //乙方签订日期
        templateVo.setCompanySupplierDate(LocalDateTime.now().format(dfDateTime));
        //价格计算规则
        templateVo.setPriceRuleDetail(supplementInfo.getPriceRuleDetail());
        //合同生效时间
        templateVo.setContractEffectDate(purchContractSupplementApproval.getContractEffectDate());
        if (purchContractSupplementApproval != null) {
            if (CollectionUtil.isNotEmpty(purchContractSupplementApproval.getComments())) {
                String comment = purchContractSupplementApproval.getComments().stream().collect(Collectors.joining(","));
                templateVo.setOtherConvention(StringUtil.isEmpty(comment) ? "无" : comment);
            }

        }

        return WordWriter.buildPurchContractChangeFile(supplementInfo.getSupplementContractNumber() + "-" + purchContractBasicInfo.getContractName() + "-补充合同", templateVo);
    }

    private TableRenderData buildTableRenderData(List<PurchContractSupplementGoodsInfo> goodsInfoList) {
        Tables.TableBuilder tableBuilder = Tables.ofA4MediumWidth();

        BorderStyle borderStyle = new BorderStyle();
        borderStyle.setSize(5);
        borderStyle.setType(XWPFTable.XWPFBorderType.SINGLE);

        RowRenderData header = Rows.of("序号", "材料名称", "规格型号", "计量单位", "暂定数量", "暂定单价（元/吨）", "备注")
                .center()
                .textFontFamily("宋体")
                .textFontSize(10)
                .create();
        ;
        tableBuilder.addRow(header);
        int indexNumber = 1;
        BigDecimal unitsTotal = new BigDecimal(0);

        for (PurchContractSupplementGoodsInfo goodsInfo : goodsInfoList) {
            RowRenderData data = Rows.of(indexNumber + "", goodsInfo.getGoodsName(), goodsInfo.getModelNumber(), goodsInfo.getUnits(), goodsInfo.getQuantity(), goodsInfo.getPrice(), goodsInfo.getRemark())
                    .center()
                    .textFontFamily("宋体")
                    .textFontSize(10)
                    .create();
            tableBuilder.addRow(data);
            indexNumber++;
        }
        if (CollectionUtil.isEmpty(goodsInfoList)) {
            RowRenderData empty = Rows.of("无", null, null, null, null, null, null)
                    .center()
                    .textFontFamily("宋体")
                    .textFontSize(10)
                    .create();
            tableBuilder.addRow(empty);
        }

        TableRenderData goodsTable = tableBuilder.center().border(borderStyle).create();
        return goodsTable;
    }

    @Override
    public void updateShortUrl(Date date) {
        List<PurchContractSupplementElectronicInfo> list = lambdaQuery().eq(PurchContractSupplementElectronicInfo::getCertifyStatus,1).eq(PurchContractSupplementElectronicInfo::getSignStatus,0).list();
        if (list != null && list.size() > 0) {
            for (PurchContractSupplementElectronicInfo electronicInfo : list) {
                Date shortContractLinkCreate = electronicInfo.getShortContractLinkCreate();
                long between = DateUtil.between(shortContractLinkCreate, date, DateUnit.DAY);
                if (between >= 6) {
                    String newShortUrl = ElectronicSignatureUtil.shortUrl(null, electronicInfo.getContractLink());
                    electronicInfo.setShortContractLink(newShortUrl);
                    electronicInfo.setShortContractLinkCreate(date);
                    updateById(electronicInfo);
                }
            }
        }
    }
}
