//package com.sunxung.factoring.service.purchcontractmanagement.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.sunxung.factoring.component.exception.BusinessException;
//import com.sunxung.factoring.component.exception.ValidatorException;
//import com.sunxung.factoring.component.util.*;
//import com.sunxung.factoring.dict.impl.PurchContractStatusDict;
//import com.sunxung.factoring.entity.businessmanagement.BusinessBasicInfo;
//import com.sunxung.factoring.entity.customerinformation.Customer;
//import com.sunxung.factoring.entity.purchcontractmanagement.*;
//import com.sunxung.factoring.entity.purchcontractmanagement.vo.PurchContractSignConfirmVo;
//import com.sunxung.factoring.entity.sys.Dictionary;
//import com.sunxung.factoring.entity.tradingPlatform.Platform;
//import com.sunxung.factoring.mapper.purchcontractmanagement.PurchContractSignConfirmMapper;
//import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
//import com.sunxung.factoring.service.businessmanagement.BusinessSupplierInfoService;
//import com.sunxung.factoring.service.customerinformation.CustomerService;
//import com.sunxung.factoring.service.project.BusinessAssigneeService;
//import com.sunxung.factoring.service.purchcontractmanagement.*;
//import com.sunxung.factoring.service.salescontractmanagement.SalesContractGoodsInfoService;
//import com.sunxung.factoring.service.sys.DictionaryService;
//import com.sunxung.factoring.service.sys.flowable.FlowableService;
//import com.sunxung.factoring.service.tradingPlatform.PlatformService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.File;
//import java.util.*;
//
///**
// * @Description : 采购合同签署service实现类
// * @Author : JiaYf
// * @Date: 2021-09-22 18:30
// */
//@Service("purch_contract_sign_confirmService")
//public class PurchContractConfirmServiceImpl extends ServiceImpl<PurchContractSignConfirmMapper, PurchContractSignConfirm>
//        implements PurchContractConfirmService {
//
//    @Autowired
//    private PurchContractService purchContractService;
//
//    @Autowired
//    private PurchContractBasicInfoService purchContractBasicInfoService;
//
//    @Autowired
//    private PurchContractElectronicInfoService purchContractElectronicInfoService;
//
//    @Autowired
//    private BusinessAssigneeService assigneeService;
//
//    @Autowired
//    private BusinessBasicInfoService businessBasicInfoService;
//
//    @Autowired
//    private FlowableService flowableService;
//
//    @Autowired
//    private DictionaryService dictService;
//
//    @Autowired
//    private PlatformService platformService;
//
//    @Autowired
//    private BusinessSupplierInfoService businessSupplierInfoService;
//
//    @Autowired
//    private CustomerService customerService;
//
//    @Autowired
//    private PurchContractGoodsInfoService purchContractGoodsInfoService;
//
//    @Autowired
//    private SalesContractGoodsInfoService salesContractGoodsInfoService;
//
//    @Autowired
//    private PurchContractReplenishInfoService purchContractReplenishInfoService;
//
//    @Autowired
//    private PurchContractVatInfoService purchContractVatInfoService;
//
//    @Autowired
//    private PurchContractQualityAcceptService purchContractQualityAcceptService;
//
//    @Autowired
//    private PurchContractSettlePaymentService purchContractSettlePaymentService;
//
//    @Autowired
//    private PurchContractDeliverClauseService purchContractDeliverClauseService;
//
//    @Autowired
//    private PurchContractBuyerReceiverService purchContractBuyerReceiverService;
//
//    @Autowired
//    private PurchContractSellerSenderService purchContractSellerSenderService;
//
//    @Autowired
//    private PurchContractSellerBlameService purchContractSellerBlameService;
//
//    @Autowired
//    private PurchContractPunishClauseService purchContractPunishClauseService;
//
//    @Autowired
//    private PurchContractOtherClauseService purchContractOtherClauseService;
//
//    @Autowired
//    private PurchContractApprovalService purchContractApprovalService;
//
//
//    @Override
//    public PurchContractSignConfirmVo getView(Long id) {
//        PurchContractSignConfirm purchContractSignConfirm = baseMapper.selectById(id);
//        if (purchContractSignConfirm == null) {
//            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同签署信息");
//        }
//        String conclusion = ConstantConversionUtil.processApprovalResult.get(purchContractSignConfirm.getConclusion());
//        purchContractSignConfirm.setConclusion(conclusion);
//        PurchContractSignConfirmVo purchContractSignConfirmVo = new PurchContractSignConfirmVo();
//        purchContractSignConfirmVo.setPurchContractSignConfirm(purchContractSignConfirm);
//
//        //PurchContractBasicInfo purch = purchContractBasicInfoService.getById(purchContractSignConfirm.getPurchContractBasicInfoId());
//        PurchContractElectronicInfo electronicInfo = purchContractElectronicInfoService.findByPurchContApprId(id);
//        purchContractSignConfirmVo.setPurchContractElectronicInfo(electronicInfo);
//        return purchContractSignConfirmVo;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void sign(PurchContractSignConfirmVo purchContractSignConfirmVo, String businessKey,
//                     String taskId, HttpServletRequest request) {
//        if (purchContractSignConfirmVo.getPurchContractSignConfirm() == null || businessKey == null) {
//            throw new ValidatorException(CodeUtil.FAIL, "审核信息或者业务id不能为空");
//        }
//
//        PurchContractManagement purchContractManagement = purchContractService.getById(businessKey);
//        if (purchContractManagement == null) {
//            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同管理信息");
//        }
//
//        PurchContractBasicInfo purch = purchContractBasicInfoService.getLatestBasicInfo(purchContractManagement.getId(), null);
//        if (purch == null) {
//            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同信息");
//        }
//        PurchContractElectronicInfo electronicInfo = purchContractElectronicInfoService.getById(purchContractSignConfirmVo.getPurchContractElectronicInfo().getId());
//        PurchContractSignConfirm savedPurchContractSignConfirm = baseMapper.selectById(purchContractElectronicInfoService.getById(electronicInfo.getId()).getPurchContractSignConfirmId());
//        if(electronicInfo.getSignStatus() == 0){
//            throw new BusinessException(CodeUtil.FAIL, "合同未签署，请先签署合同");
//        }
//        savedPurchContractSignConfirm.setConclusion(purchContractSignConfirmVo.getPurchContractSignConfirm().getConclusion());
//        savedPurchContractSignConfirm.setAssigneeId(ThreadLocalUtil.getUserId());
//
//        baseMapper.updateById(savedPurchContractSignConfirm);
//
//        //采购合同电子合同信息 保存
//        purchContractElectronicInfoService.updateById(electronicInfo);
//
//        //流程处理
//        String processKey;
//        String assigneeKey;
//        if (purchContractManagement.getChangeable()) {
//            //走变更流程
//            processKey = ConstantUtil.PURCH_CONTRACT_CHANGE_PROCESS;
//            assigneeKey = ConstantUtil.PURCH_CONTRACT_CHANGE_FINAL_APPROVAL + ConstantUtil.ASSIGNEE;
//        } else {
//            //走正常流程
//            processKey = ConstantUtil.PURCH_CONTRACT;
//            assigneeKey = ConstantUtil.PURCH_CONTRACT_FINAL_APPROVAL + ConstantUtil.ASSIGNEE;
//        }
//        Map<String, Object> procVariables = new HashMap<>(1);
//        procVariables.put(assigneeKey,
//                assigneeService.getIdByBusiness(purchContractManagement.getId(), processKey, ConstantUtil.ASSIGNEE_LEGAL_SPECIALIST));
//
//        Map<String, Object> msgVariables = new HashMap<>(2);
//        BusinessBasicInfo businessBasicInfo = businessBasicInfoService.getByBusinessNumber(purchContractManagement.getBusinessNumber());
//        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, businessBasicInfo.getBusinessName());
//        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
//                "业务编号为" + purchContractManagement.getBusinessNumber() + "”的项目已inOut“"
//                        + ConstantConversionUtil.flowBusinessKeyNames.get(processKey) + "—formBusiness”阶段，");
//        Boolean success = flowableService.completeMyTask(taskId, purchContractManagement, procVariables,
//                ConstantConversionUtil.processApprovalResult.get(savedPurchContractSignConfirm.getConclusion()),
//                savedPurchContractSignConfirm.getId(), msgVariables, processKey);
//        if (success == null || !success) {
//            throw new ValidatorException(CodeUtil.FAIL, "采购合同签署出错啦！");
//        }
//
//        Dictionary signConfirmDict = dictService.getByCode(PurchContractStatusDict.ChildEnum.SIGN.getCode());
//        Dictionary inputDict = dictService.getByCode(PurchContractStatusDict.ChildEnum.INPUT.getCode());
//        if (signConfirmDict == null || inputDict == null) {
//            throw new BusinessException(CodeUtil.FAIL, "采购合同状态字典项不能为空");
//        }
//
//        //如果审核结论为完成、修改合同状态为已签署
//        if (savedPurchContractSignConfirm.getConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_COMPLETE)) {
//            purchContractManagement.setContractStatus(signConfirmDict.getId());
//        }
//        //如果审核结论为退回、修改合同状态为已录入
//        if (savedPurchContractSignConfirm.getConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
//            purchContractManagement.setContractStatus(inputDict.getId());
//        }
//        purchContractService.updateById(purchContractManagement);
//    }
//
//    //根据合同基本信息ID获取最新的签署信息
//    @Override
//    public PurchContractSignConfirm getLatestPurchContractSignConfirm(Long id){
//        return   getOne(new QueryWrapper<PurchContractSignConfirm>().eq("purch_contract_basic_info_id", id).orderByDesc("id").last("LIMIT 1"));
//    }
//
//    /**
//     * 制作合同：模板填充数据生成docx
//     * @param purchContractManagement
//     * @param purch
//     * @return
//     */
//    @Override
//    public File makePurchContractDocx(PurchContractManagement purchContractManagement, PurchContractBasicInfo purch) {
//        try {
//            XMlToDoc xmlDoc = new XMlToDoc();
//            Map<String, Object> dataMap = new HashMap<>();
//            // 合同名称
//            String contractName = purch.getContractName();
//
//            //合同模板数据填充 开始
//            //获取对应的业务信息
//            BusinessBasicInfo businessBasicInfo = businessBasicInfoService.getByBusinessNumber(purchContractManagement.getBusinessNumber());
//            //获取平台信息
//            Platform platform =platformService.getById(businessBasicInfo.getTradingPlatformId());
//            //获取对应供货商的企业客户信息
//            Customer supplierCustomer = customerService.getById(purchContractManagement.getSupplierId());
//            //获取业务买方对应的企业客户信息
//            Customer purchaserCustomer =  customerService.getById(businessBasicInfo.getEnterpriseCustomerInfoId());
//
//            //合同名称
//            dataMap.put("contractName", contractName);
//            //合同编号
//            dataMap.put("contractNumber", purch.getContractNumber());
//            //签订日期  暂时给null，后边需处理
//            dataMap.put("signDate", DateUtil.getDayStringFormat(new Date()));
//            //需方公司名称
//            dataMap.put("platformName", platform.getPlatformName());
//            //需方统一社会信用代码
//            dataMap.put("platformSocialCreditCode", platform.getSocialCreditCode());
//            //供货公司名称
//            dataMap.put("supplierName", supplierCustomer.getEnterpriseName());
//            //供应商统一社会信用代码
//            dataMap.put("supplierSocialCreditCode", supplierCustomer.getSocialCreditCode());
//            //买方名称
//            dataMap.put("purchaserName", purchaserCustomer.getEnterpriseName());
//            //业务名称
//            dataMap.put("businessName", businessBasicInfo.getBusinessName());
//
//            //交易标的物  开始
//            List<Map<String, Object>> dealGoodsList = new ArrayList<>();
//            //获取货物信息
//            List<PurchContractGoodsInfo> purchGoodsList = purchContractGoodsInfoService.findByPurchContId(purch.getId());
//            for (PurchContractGoodsInfo purchGoods : purchGoodsList){
//                purchGoods.setSalesContractGoodsInfo(salesContractGoodsInfoService.findByGoodsId(purchGoods.getSalesContractGoodsInfoId()));
//                Map<String, Object> gMap = new HashMap<>();
//                //序号
//                gMap.put("goodsCode", purchGoods.getGoodsCode());
//                //材料名称
//                gMap.put("goodsName", purchGoods.getSalesContractGoodsInfo().getGoodsName());
//                //规格型号
//                gMap.put("modelNumber", purchGoods.getSalesContractGoodsInfo().getModelNumber());
//                //生产厂家
//                gMap.put("goodsFactory", purchGoods.getSalesContractGoodsInfo().getGoodsFactory());
//                //计量单位
//                gMap.put("Units", purchGoods.getSalesContractGoodsInfo().getUnits());
//                //数量
//                gMap.put("quantity", purchGoods.getSalesContractGoodsInfo().getQuantity());
//                //暂定单价
//                gMap.put("purchPrice", purchGoods.getPurchPrice());
//                //备注
//                gMap.put("remark", purchGoods.getRemark());
//                dealGoodsList.add(gMap);
//            }
//            dataMap.put("dealGoodsList", dealGoodsList);
//            //交易标的物  结束
//
//            //获取采购合同补充信息
//            //获取合同对应的最新审核信息
//            PurchContractApproval purchContractApproval =  purchContractApprovalService.getLatestPurchContractApproval(purch.getId());
//            PurchContractReplenishInfo purchContractReplenishInfo = purchContractReplenishInfoService.findByPurchContApprId(purchContractApproval.getId());
//            //工程量类别
//            dataMap.put("projectAmountCategory", purchContractReplenishInfo.getProjectAmountCategoryDic().getName());
//            //货物单价结算方式
//            dataMap.put("goodsPriceSettleMethod", purchContractReplenishInfo.getGoodsPriceSettleMethod());
//
//            //获取增值税要求
//            PurchContractVatInfo purchContractVatInfo = purchContractVatInfoService.findByPurchContApprId(purchContractApproval.getId());
//            //增值税要求 税率
//            dataMap.put("taxRate", purchContractVatInfo.getTaxRate());
//            //增值税要求 发票类型
//            dataMap.put("receiptType", purchContractVatInfo.getReceiptType());
//            //开票信息 开票单位名称(需方)
//            dataMap.put("openCompanyName", platform.getPlatformName());
//            //开票信息 开票单位统一社会信用代码
//            dataMap.put("openCompanySocialCreditCode", platform.getSocialCreditCode());
//            //开票信息 地址
//            dataMap.put("openCompanyAddress", platform.getAddress());
//            //开票信息 电话
//            dataMap.put("openCompanyPhoneNumber", platform.getPhoneNumber() == null? "/" : platform.getPhoneNumber());
//            //开票信息 发票开户行
//            dataMap.put("openBank", purchContractVatInfo.getOpenBank()) ;
//            //开票信息 发票账号
//            dataMap.put("receiptAccount", purchContractVatInfo.getReceiptAccount()) ;
//            //发票备注
//            dataMap.put("receiptRemark", purchContractVatInfo.getReceiptRemark()) ;
//
//            //获取采购合同质量与验收
//            PurchContractQualityAccept purchContractQualityAccept = purchContractQualityAcceptService.findByPurchContApprId(purchContractApproval.getId());
//            //验收标准
//            dataMap.put("acceptCriteria", purchContractQualityAccept.getAcceptCriteria());
//            //质量标准
//            dataMap.put("qualityCriteria", purchContractQualityAccept.getQualityCriteria());
//
//            //获取采购合同结算与付款
//            PurchContractSettlePayment purchContractSettlePayment = purchContractSettlePaymentService.findByPurchContApprId(purchContractApproval.getId());
//            //结算方式
//            dataMap.put("settleMethod", purchContractSettlePayment.getSettleMethod());
//            //付款方式
//            dataMap.put("paymentMethod", purchContractSettlePayment.getPaymentMethod());
//
//            //获取采购合同交货规定
//            PurchContractDeliverClause purchContractDeliverClause = purchContractDeliverClauseService.findByPurchContApprId(purchContractApproval.getId());
//            //交货方式
//            dataMap.put("deliverMethod", purchContractDeliverClause.getDeliverMethod());
//            //交货地点
//            dataMap.put("deliverSite", purchContractDeliverClause.getDeliverSite());
//
//            //需方收货人  开始
//            List<Map<String, Object>> receiverList = new ArrayList<>();
//            //获取采购合同需方收货人
//            List<PurchContractBuyerReceiver> buyerReceiverList = purchContractBuyerReceiverService.findByPurchContApprId(purchContractApproval.getId());
//            int i = 1;
//            for (PurchContractBuyerReceiver buyerReceiver : buyerReceiverList) {
//                Map<String, Object> bMap = new HashMap<>();
//                //序号
//                bMap.put("receiverId", i++);
//                //姓名
//                bMap.put("receiverName", buyerReceiver.getName());
//                //身份证号
//                bMap.put("receiverCertno", buyerReceiver.getCertno());
//                //联系方式
//                bMap.put("receiverContact", buyerReceiver.getContact());
//                receiverList.add(bMap);
//            }
//            dataMap.put("receiverList", receiverList);
//            //需方收货人  结束
//
//            //供应商发货人  开始
//            List<Map<String, Object>> senderList = new ArrayList<>();
//            //采购合同供货商发货人
//            List<PurchContractSellerSender> sellerSenderList = purchContractSellerSenderService.findByPurchContApprId(purchContractApproval.getId());
//            int j = 1;
//            for (PurchContractSellerSender sellerSender : sellerSenderList) {
//                Map<String, Object> sMap = new HashMap<>();
//                //序号
//                sMap.put("sellerId", j++);
//                //姓名
//                sMap.put("sellerName", sellerSender.getName());
//                //身份证号
//                sMap.put("sellerCertno", sellerSender.getCertno());
//                //联系方式
//                sMap.put("sellerContact", sellerSender.getContact());
//                senderList.add(sMap);
//            }
//            dataMap.put("senderList", senderList);
//            //供应商发货人  结束
//
//            //需方指定验收人
//            //姓名
//            dataMap.put("acceptName", buyerReceiverList.get(0).getName());
//            //身份证号
//            dataMap.put("acceptCertno", buyerReceiverList.get(0).getCertno());
//            //联系方式
//            dataMap.put("acceptContact", buyerReceiverList.get(0).getContact());
//            //需方指定结算人
//            //姓名
//            dataMap.put("paymentName", buyerReceiverList.get(0).getName());
//            //身份证号
//            dataMap.put("paymentCertno", buyerReceiverList.get(0).getCertno());
//            //联系方式
//            dataMap.put("paymentContact", buyerReceiverList.get(0).getContact());
//
//            //获取采购合同供货商责任
//            PurchContractSellerBlame purchContractSellerBlame = purchContractSellerBlameService.findByPurchContApprId(purchContractApproval.getId());
//            //供应商违约金比例
//            dataMap.put("penaltyRate", purchContractSellerBlame.getPenaltyRate());
//            //向谁出售  买方名称
//            dataMap.put("toWhoPurchaserName", purchaserCustomer.getEnterpriseName());
//
//            //获取采购合同违约条款
//            PurchContractPunishClause purchContractPunishClause = purchContractPunishClauseService.findByPurchContApprId(purchContractApproval.getId());
//            //合同补偿金
//            dataMap.put("contractCompensateRate", purchContractPunishClause.getContractCompensateRate());
//            //合同违约金比例
//            dataMap.put("contractPenaltyRate", purchContractPunishClause.getContractPenaltyRate());
//
//            //获取其他条款
//            List<PurchContractOtherClause> contractOtherClauseList = purchContractOtherClauseService.findByPurchContApprId(purchContractApproval.getId());
//            //其他条款  开始
//            List<Map<String, Object>> otherClauseList = new ArrayList<>();
//            for (PurchContractOtherClause otherClause : contractOtherClauseList) {
//                Map<String, Object> cMap = new HashMap<>();
//                //序号
//                cMap.put("serialNumber", otherClause.getSerialNumber()+"、");
//                //付款条件
//                cMap.put("paymentCondition", otherClause.getPaymentCondition());
//                otherClauseList.add(cMap);
//            }
//            dataMap.put("otherClauseList", otherClauseList);
//            //其他条款  结束
//
//            //单位名称需方公司名称
//            dataMap.put("companyPlatformName", platform.getPlatformName());
//            //单位名称供应商名称
//            dataMap.put("companySupplierName", supplierCustomer.getEnterpriseName());
//
//            //需方签订日期  需处理
//            dataMap.put("companyPlatformDate", DateUtil.getDayStringFormat(new Date()));
//            //供应商签订日期  需处理
//            dataMap.put("companySupplierDate", DateUtil.getDayStringFormat(new Date()));
//
//            File outFile = null;
//            outFile = xmlDoc.makePurchContract(dataMap, contractName, "/ftl/purchcontract/export/",
//                    "PurchContract.zip");
//            return outFile;
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(CodeUtil.FAIL, "制作采购合同出错" + e.getMessage());
//        }
//    }
//
//
//}
