package com.uas.platform.b2b.erp.service.impl;

import com.uas.platform.b2b.core.util.ContextUtils;
import com.uas.platform.b2b.core.util.ThreadTask;
import com.uas.platform.b2b.dao.*;
import com.uas.platform.b2b.erp.model.B2BVendor;
import com.uas.platform.b2b.erp.model.SaleTenderErp;
import com.uas.platform.b2b.erp.service.TenderService;
import com.uas.platform.b2b.erp.service.VendorService;
import com.uas.platform.b2b.event.PurchaseTenderDecideReleaseEvent;
import com.uas.platform.b2b.event.PurchaseTenderSaveReleaseEvent;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.service.AttachService;
import com.uas.platform.b2b.support.MessageConf;
import com.uas.platform.b2b.support.SendMsgUtils;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.temporary.model.DecideTender;
import com.uas.platform.b2b.temporary.model.PurcTenderProd;
import com.uas.platform.b2b.temporary.model.TenderContactInfo;
import com.uas.platform.core.model.Constant;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dongbw on 17/03/07 14:16.
 */
@Service
public class TenderServiceImpl implements TenderService {

    @Autowired
    private PurchaseTenderDao purchaseTenderDao;

    @Autowired
    private PurchaseTenderProdDao purchaseTenderProdDao;

    @Autowired
    private SaleTenderDao saleTenderDao;

    @Autowired
    private SaleTenderErpDao saleTenderErpDao;

    @Autowired
    private SaleTenderItemDao saleTenderItemDao;

    @Autowired
    private AttachDao attachDao;

    @Autowired
    private AttachService attachService;

    @Autowired
    private EnterpriseDao enterpriseDao;

    @Autowired
    private EnterpriseBaseInfoDao enterpriseBaseInfoDao;

    @Autowired
    private VendorContactDao vendorContactDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private VendorDao vendorDao;

    @Autowired
    private DistributeDao distributeDao;

    @Autowired
    private UserOrderDao userOrderDao;

    @Autowired
    private MessageConf messageConf;

    @Autowired
    private PurchaseTenderQuestionDao purchaseTenderQuestionDao;

    @Autowired
    private PurchaseTenderAnswerDao purchaseTenderAnswerDao;

    @Autowired
    private SaleTenderQuestionDao saleTenderQuestionDao;

    @Autowired
    private VendorService vendorService;

    /**
     *  发布和保存
     * @param purchaseTender
     * @param contactInfos
     * @param tenderAttaches
     */
    @Override
    public ModelMap publishOrSave(PurchaseTender purchaseTender, List<TenderContactInfo> contactInfos, List<Attach> tenderAttaches) {
        if (Constant.YES == purchaseTender.getIsPublish()) {
            if (Constant.YES == purchaseTender.getIfOpen()) {
                return publishOpen(purchaseTender, tenderAttaches);
            } else {
                return publish(purchaseTender, contactInfos, tenderAttaches);
            }
        } else {
            if (Constant.YES == purchaseTender.getIfOpen()) {
                return saveOpen(purchaseTender, tenderAttaches);
            } else {
                return  save(purchaseTender, contactInfos, tenderAttaches);
            }
        }
    }

    private ModelMap publishOpen(PurchaseTender tender, List<Attach> attaches) {
        return publishOrSaveOpen(tender, attaches, true);
    }

    private ModelMap saveOpen(PurchaseTender tender, List<Attach> attaches) {
        return publishOrSaveOpen(tender, attaches, false);
    }

    private ModelMap publishOrSaveOpen (PurchaseTender tender, List<Attach> attaches,boolean isPublish) {
        if (isPublish) {
            tender.setStatus("待投标");
        } else {
            tender.setStatus("待发布");
        }
        Set<Attach> attachSet = new HashSet<>();
        attaches = attachDao.save(attaches);
        attachSet.addAll(attaches);
        tender.setTenderAttaches(attachSet);
        tender.setEnUU(SystemSession.getUser().getEnterprise().getUu());
        purchaseTenderDao.save(tender);
        Set<PurchaseTenderProd> tenderProds = tender.getPurchaseTenderProds();
        for (PurchaseTenderProd tenderProd : tenderProds) {
            PurchaseTenderSave purchaseTenderSave = new PurchaseTenderSave();
            BeanUtils.copyProperties(tender,purchaseTenderSave);
            tenderProd.setTender(purchaseTenderSave);
            purchaseTenderProdDao.save(tenderProd);
        }
        ModelMap map = new ModelMap();
        map.put("id", tender.getId());
        map.put("code", tender.getCode());
        return map;
    }

    private ModelMap publish(PurchaseTender tender, List<TenderContactInfo> contactInfos, List<Attach> attaches) {
        tender.setStatus("待投标");
        tender.setEnUU(SystemSession.getUser().getEnterprise().getUu());
        tender.setEnterprise(SystemSession.getUser().getEnterprise());
        return saveTenderItem(tender, contactInfos, attaches);
    }

    private ModelMap save(PurchaseTender tender, List<TenderContactInfo> contactInfos, List<Attach> attaches) {
        tender.setStatus("待发布");
        tender.setEnUU(SystemSession.getUser().getEnterprise().getUu());
        tender.setEnterprise(SystemSession.getUser().getEnterprise());
        return saveTenderItem(tender, contactInfos, attaches);
    }

    private ModelMap saveTenderItem(PurchaseTender tender, List<TenderContactInfo> contactInfos, List<Attach> attaches) {
        Set<Attach> attachSet = new HashSet<>();
        attaches = attachDao.save(attaches);
        attachSet.addAll(attaches);
        tender.setTenderAttaches(attachSet);
        Set<PurchaseTenderProd> tenderProds = tender.getPurchaseTenderProds();
        for (PurchaseTenderProd tenderProd : tenderProds) {
            PurchaseTenderSave purchaseTenderSave = new PurchaseTenderSave();
            BeanUtils.copyProperties(tender,purchaseTenderSave);
            tenderProd.setTender(purchaseTenderSave);
            purchaseTenderProdDao.save(tenderProd);
            addSaleTender(tender, contactInfos, tenderProd);
        }
        ModelMap map = new ModelMap();
        map.put("id", tender.getId());
        map.put("code", tender.getCode());
        return map;
    }

    @Override
    public Attach addTenderAttaches(FileUpload uploadItem) throws Exception {
        if (uploadItem.getFile() == null) {
            throw new Exception("没有附件");
        }
        Attach attach = attachService.upload(uploadItem, "purchaseTenderAttaches", "招标附件");
        if (attach == null) {
            throw new Exception("文件太大");
        }
        return attachDao.save(attach);
    }

    @Override
    public Attach addTenderItemAttaches(FileUpload uploadItem) throws Exception {
        if (uploadItem.getFile() == null) {
            throw new Exception("没有附件");
        }
        Attach attach = attachService.upload(uploadItem, "saleTenderAttaches", "投标附件");
        if (attach == null) {
            throw new Exception("文件太大");
        }
        return attachDao.save(attach);
    }

    @Override
    public List<PurchaseTender> findAll() {
        List<SaleTender> saleTenders = saleTenderDao.findAll(new Specification<SaleTender>() {
            @Override
            public Predicate toPredicate(Root<SaleTender> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                // 根据供应商企业uu为本企业uu筛选
                Predicate myTender = cb.equal(root.get("enterpriseBaseInfo").get("uu"), SystemSession.getUser().getEnterprise().getUu());
                query.where(myTender);
                return query.getRestriction();
            }
        });
        List<PurchaseTender> tenderList = new ArrayList<>();
        for (SaleTender saleTender : saleTenders) {
            // 理论上根据企业uu和单号可以找到唯一单据，防止数据出错，取list第一个
            PurchaseTender purchaseTender = purchaseTenderDao.findByEnUUAndCode(saleTender.getEnUU(), saleTender.getCode()).get(0);
            if (purchaseTender.getIfOpen() == Constant.NO && purchaseTender.getIsPublish() == Constant.YES && purchaseTender.getStatus().equals("待投标")) { //显示发布的待投标状态的指定招标
                tenderList.add(purchaseTender);
            }
        }
        return tenderList;
    }

    @Override
    public List<PurchaseTender> findOpen() {
        return purchaseTenderDao.findAll(new Specification<PurchaseTender>() {

            @Override
            public Predicate toPredicate(Root<PurchaseTender> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                Predicate p1 = builder.equal(root.get("ifOpen"), Constant.YES);
                Predicate p2 = builder.equal(root.get("isPublish"), Constant.YES);
                Predicate p3 = builder.notEqual(root.get("enUU"), SystemSession.getUser().getEnterprise().getUu());
                Predicate p4 = builder.equal(root.get("overdue"), Constant.NO);
                Predicate p5 = builder.equal(root.get("status"), "待投标");
                Predicate predicate = builder.and(p1, p2, p3, p4, p5);
                query.where(predicate);
                return null;
            }
        });
    }

    @Override
    public ModelMap delete(Long id) {
        PurchaseTender tender = purchaseTenderDao.findOne(id);
        if (null != tender) {
            List<SaleTender> saleTenders = saleTenderDao.findByEnUUAndCode(tender.getEnUU(), tender.getCode());
            if (!CollectionUtils.isEmpty(saleTenders)) {
                for (SaleTender saleTender : saleTenders) {
                    if (!CollectionUtils.isEmpty(saleTender.getSaleTenderItems())) {
                        for (SaleTenderItem saleTenderItem : saleTender.getSaleTenderItems()) {
                            SaleTenderItem oldItem = saleTenderItemDao.findOne(saleTenderItem.getId());
                            if (oldItem != null) {
                                saleTenderItemDao.delete(oldItem);
                            }
                        }
                    }
                    SaleTender oldSaleTender = saleTenderDao.findOne(saleTender.getId());
                    if (oldSaleTender != null) {
                        saleTenderDao.delete(oldSaleTender);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(tender.getPurchaseTenderProds())) {
                for (PurchaseTenderProd tenderProd : tender.getPurchaseTenderProds()) {
                    PurchaseTenderProd oldtenderProd = purchaseTenderProdDao.findOne(tenderProd.getId());
                    if (oldtenderProd != null) {
                        purchaseTenderProdDao.delete(oldtenderProd);
                    }
                }
            }
            PurchaseTender oldTender = purchaseTenderDao.findOne(tender.getId());
            if (oldTender != null) {
                purchaseTenderDao.delete(oldTender);
            }
        }
        ModelMap map = new ModelMap();
        map.put("success", true);
        return map;
    }

    @Override
    public ModelMap deleteAttach(Long attachId) {
        Attach attach = attachDao.findOne(attachId);
        ModelMap map = new ModelMap();
        if (attach != null) {
            attachDao.delete(attach);
            map.put("success", true);
            return map;
        }
        map.put("success", false);
        return map;
    }

    @Override
    public ModelMap releaseByWorkbook(Workbook workbook) {
        ModelMap modelMap = new ModelMap();
        List<String> alters = new ArrayList<String>();
        List<PurcTenderProd> tenderProds = new ArrayList<PurcTenderProd>();
        Sheet sheet = workbook.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();
        Row headerRow = sheet.getRow(0);
        int total = 0;
        if (headerRow != null) {
            for (int r = 3; r <= rowNum; r++) {
                Row row = sheet.getRow(r);
                if (row != null && row.getCell(0) != null && row.getCell(1).getCellType() != Cell.CELL_TYPE_BLANK) {
                    total++;
                    PurcTenderProd info = new PurcTenderProd();
                    // 商品名称
                    if (row.getCell(0) != null) {
                        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                        info.setProdTitle(row.getCell(0).getStringCellValue().trim());
                    }

                    // 型号
                    if (row.getCell(1) != null) {
                        row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                        info.setProdCode(row.getCell(1).getStringCellValue().trim());
                    }

                    // 品牌
                    if (row.getCell(2) != null) {
                        row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                        info.setBrand(row.getCell(2).getStringCellValue().trim());
                    }

                    // 单位
                    if (row.getCell(3) != null) {
                        row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                        info.setUnit(row.getCell(3).getStringCellValue().trim());
                    }

                    // 采购数量
                    if (row.getCell(4) != null) {
                        row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                        info.setQty(Integer.valueOf(row.getCell(4).getStringCellValue()));
                    }

                    if (info.getProdTitle() != null && info.getQty() != null && info.getProdCode() != null) {
                        modelMap.put("total", total);
                        modelMap.put("success", total - alters.size());
                        tenderProds.add(info);
                        modelMap.put("items", tenderProds);
                    }
                }
            }
        }
        return modelMap;
    }


    @Override
    public PurchaseTender findById(Long id) {
        PurchaseTender tender = purchaseTenderDao.findOne(id);
        // 已投标企业统计
        Integer saleTenders = saleTenderDao.findNumOfBIdEn(tender.getEnUU(), tender.getCode(), "待投标");
        tender.setBidEnNum(Short.valueOf(String.valueOf(saleTenders)));
        return tender;
    }

    /**
     * 公开招标单转投标单
     *
     * @param id
     * @return
     */
    @Override
    public ModelMap addTenderItemById(Long id) {
        PurchaseTender tender = purchaseTenderDao.findOne(id);
        SaleTender saleTender = new SaleTender();
        for (PurchaseTenderProd tenderProd : tender.getPurchaseTenderProds()) {
            Long vendUU = SystemSession.getUser().getEnterprise().getUu();
            EnterpriseBaseInfo enBaseInfo = enterpriseBaseInfoDao.findOne(vendUU);
            if (null == enBaseInfo) {
                Enterprise enterprise = enterpriseDao.findOne(vendUU);
                enBaseInfo = new EnterpriseBaseInfo(enterprise.getUu(), enterprise.getEnBussinessCode(), enterprise.getEnName(), enterprise.getEnAddress());
                enterpriseBaseInfoDao.save(enBaseInfo);
            }
            SaleTenderItem tenderItem = new SaleTenderItem();
            // 找不到投标单主表才新建一个
            if (tender.getEnUU() != null && tender.getCode() != null) {
                saleTender = saleTenderDao.findByEnUUAndVendUUAndCode(tender.getEnUU(), vendUU, tender.getCode());
                if (null == saleTender) { // 不存在投标单说明未转投标单，进行新增投标单操作
                    saleTender = new SaleTender(tender);
                    saleTender.setVendUU(vendUU);
                    saleTender.setUserEmail(SystemSession.getUser().getUserEmail());
                    saleTender.setUseruu(SystemSession.getUser().getUserUU());
                    saleTender.setUser(SystemSession.getUser().getUserName());
                    saleTender.setUserTel(SystemSession.getUser().getUserTel());
//                    saleTender.setEnterpriseBaseInfo(enBaseInfo); // 投标单主表构造完毕
                    saleTenderDao.save(saleTender);
                }
                tenderItem.setSaleTender(saleTender);
                tenderItem.setTenderProd(tenderProd);
                saleTenderItemDao.save(tenderItem);
            }
        }
        tender.setModified(new Date());
        purchaseTenderDao.save(tender);
        ModelMap map = new ModelMap();
        map.put("id", saleTender.getId());
        map.put("code", tender.getCode());
        return map;
    }

    /**
     * 发布已保存单据
     *
     * @param purchaseTender
     * @param enInfos
     */
    @Override
    public ModelMap publishSaved(PurchaseTender purchaseTender, List<TenderContactInfo> enInfos) {
        return publishOrUpdateSaved(purchaseTender, enInfos, true, false);
    }

    @Override
    public ModelMap publishSaved(PurchaseTender purchaseTender, List<TenderContactInfo> enInfos, List<Attach> attachList) {
        Set<Attach> attachSet = new HashSet<>();
        attachList = attachDao.save(attachList);
        attachSet.addAll(attachList);
        purchaseTender.setTenderAttaches(attachSet);
        return publishOrUpdateSaved(purchaseTender, enInfos, true, false);
    }

    /**
     * 发布已保存单据为公开招标
     *
     * @param purchaseTender
     */
    @Override
    public ModelMap publishSavedOpen(PurchaseTender purchaseTender) {
        return publishOrUpdateSaved(purchaseTender, null, true, true);
    }

    @Override
    public ModelMap publishSavedOpen(PurchaseTender purchaseTender, List<Attach> attachList) {
        Set<Attach> attachSet = new HashSet<>();
        attachList = attachDao.save(attachList);
        attachSet.addAll(attachList);
        purchaseTender.setTenderAttaches(attachSet);
        return publishOrUpdateSaved(purchaseTender, null, true, true);
    }

    /**
     * 更新已保存单据
     *
     * @param purchaseTender
     * @param enInfos
     */
    @Override
    public ModelMap updateSaved(PurchaseTender purchaseTender, List<TenderContactInfo> enInfos) {
        return publishOrUpdateSaved(purchaseTender, enInfos, false, false);
    }

    @Override
    public ModelMap updateSaved(PurchaseTender purchaseTender, List<TenderContactInfo> enInfos, List<Attach> attachList) {
        Set<Attach> attachSet = new HashSet<>();
        attachList = attachDao.save(attachList);
        attachSet.addAll(attachList);
        purchaseTender.setTenderAttaches(attachSet);
        return publishOrUpdateSaved(purchaseTender, enInfos, false, false);
    }

    /**
     * 更新已保存单据为公开
     *
     * @param purchaseTender
     */
    @Override
    public ModelMap updateSavedOpen(PurchaseTender purchaseTender) {
        return publishOrUpdateSaved(purchaseTender, null, false, true);
    }

    @Override
    public ModelMap updateSavedOpen(PurchaseTender purchaseTender, List<Attach> attachList) {
        Set<Attach> attachSet = new HashSet<>();
        attachList = attachDao.save(attachList);
        attachSet.addAll(attachList);
        purchaseTender.setTenderAttaches(attachSet);
        return publishOrUpdateSaved(purchaseTender, null, false, true);
    }

    @Override
    public List<VendorContact> getVendContacts(Long enuu, Long venduu) {
        return vendorContactDao.findByMyenuuAndVenduu(enuu, venduu);
    }

    /**
     * UAS发布招标单审核通过
     *
     * @param id
     * @return
     */
    @Override
    public ModelMap publishTender(Long id) {
        ModelMap map = new ModelMap();
        PurchaseTender tender = purchaseTenderDao.findOne(id);
        if (null == tender) {
            map.put("error", "根据id未找到对应招标单");
            return map;
        }
        tender.setIsPublish(Constant.YES);
        tender.setStatus("待投标");
        purchaseTenderDao.save(tender);
        // 不开放的要同时把投标单发布状态修改
        if (tender.getIfOpen() != Constant.YES) {
            List<SaleTender> saleTenders = saleTenderDao.findByEnUUAndCode(tender.getEnUU(), tender.getCode());
            List<SaleTender> saveList = new ArrayList<>();
            for (SaleTender saleTender : saleTenders) {
                saleTender.setIsPublish(Constant.YES);
                saleTender.setStatus("待投标");
                saveList.add(saleTender);
            }
            saleTenderDao.save(saveList);
            for (SaleTender saleTender : saveList) {
                saveUserOrders(saleTender, tender);
            }
        }
        map.put("success", true);
        map.put("ifOpen", tender.getIfOpen());
        return map;
    }

    /**
     * 提前开标(实际上是修改投标截止时间)
     * @param id
     * @return
     */
    @Override
    public ModelMap decideInAdvance(Long id, Long date) {
        ModelMap map = new ModelMap();
        PurchaseTender tender = purchaseTenderDao.findOne(id);
        if (null == tender) {
            map.put("error", "根据id未找到对应招标单");
            return map;
        }
//        Date currentTime = new Date();
//        //获取昨天时间
//        Date backupTime = DateUtils.addDays(currentTime, -1);
        // 传日期时间戳进行设置
        tender.setEndDate(new Date(date));
        tender.setStatus("待评标");
        purchaseTenderDao.save(tender);
        // 不开放的要同时把投标单发布状态修改
        if (tender.getIfOpen() != Constant.YES) {
            List<SaleTender> saleTenders = saleTenderDao.findByEnUUAndCode(tender.getEnUU(), tender.getCode());
            List<SaleTender> saveList = new ArrayList<>();
            for (SaleTender saleTender : saleTenders) {
                saleTender.setEndDate(new Date(date));
//                saleTender.setStatus("待评标");
                saveList.add(saleTender);
            }
            saleTenderDao.save(saveList);
        }
        map.put("success", true);
        return map;
    }

    @Override
    public ModelMap getSaleTenderVendors(Long id) {
        ModelMap map = new ModelMap();
        PurchaseTender tender = purchaseTenderDao.findOne(id);
        List<SaleTender> saleTenders = saleTenderDao.findByEnUUAndCode(tender.getEnUU(), tender.getCode());
        List<B2BVendor> vendors = new ArrayList<>();
        for (SaleTender saleTender : saleTenders) {
            List<Vendor> vendor = vendorDao.findByMyEnUUAndVendUU(tender.getEnUU(), saleTender.getVendUU());
            if (!CollectionUtils.isEmpty(vendor)) {
                B2BVendor b2BVendor = new B2BVendor(vendor.get(0));
                b2BVendor.setVe_email(saleTender.getUserEmail());
                b2BVendor.setVe_contact(saleTender.getUser());
                vendors.add(b2BVendor);
            }
        }
        tender.setPurchaseTenderProds(new HashSet<PurchaseTenderProd>());
        map.put("vendors", vendors);
        map.put("tender", tender);
        return map;
    }

    @Override
    public ModelMap sendMobileMessage(Long id) {
        ModelMap map = new ModelMap();
        PurchaseTender tender = purchaseTenderDao.findOne(id);
        List<SaleTender> saleTenders = saleTenderDao.findByEnUUAndCode(tender.getEnUU(), tender.getCode());
        for (SaleTender saleTender : saleTenders) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = dateFormat.format(saleTender.getDate());
                String[] args = {String.valueOf(saleTender.getEnUU()), saleTender.getEnterprise().getEnName(), saleTender.getEnterpriseBaseInfo().getEnName(), saleTender.getCode(), date};
                SendMsgUtils.sendMsg(saleTender.getUserTel(), messageConf.getMsgTenderForB2B(), args);
            } catch (Exception e) {
                map.put("error", "发送知会短信失败，单号：" + tender.getCode());
                e.printStackTrace();
            }
        }
        if (null == map.get("error")) {
            map.put("success", true);
        }
        return map;
    }

    /**
     * 发布或保存方法（针对保存的单据）
     *
     * @param purchaseTender
     * @param enInfos
     * @param isPublish
     * @param ifOpen
     */
    private ModelMap publishOrUpdateSaved(PurchaseTender purchaseTender, List<TenderContactInfo> enInfos, boolean isPublish, boolean ifOpen) {
        PurchaseTender oldTender = purchaseTenderDao.findOne(purchaseTender.getId());
        ModelMap map = new ModelMap();
        if (null != oldTender) {
            if (isPublish) {
                oldTender.setIsPublish(Constant.YES);
                oldTender.setStatus("待投标");
            } else {
                oldTender.setIsPublish(Constant.NO);
            }
            if (ifOpen) {
                oldTender.setIfOpen(Constant.YES);
            } else {
                oldTender.setIfOpen(Constant.NO);
            }
            oldTender.setModified(new Date());
            if (null != purchaseTender.getCertificate()) {
                oldTender.setCertificate(purchaseTender.getCertificate());
            } else {
                oldTender.setCertificate("");
            }
            oldTender.setCurrency(purchaseTender.getCurrency());
            oldTender.setEndDate(purchaseTender.getEndDate());
            oldTender.setPublishDate(purchaseTender.getPublishDate());
            oldTender.setIfTax(purchaseTender.getIfTax());
            oldTender.setInvoiceType(purchaseTender.getInvoiceType());
            oldTender.setPayment(purchaseTender.getPayment());
            oldTender.setShipAddress(purchaseTender.getShipAddress());
            oldTender.setTitle(purchaseTender.getTitle());
            oldTender.setUser(purchaseTender.getUser());
            oldTender.setUserTel(purchaseTender.getUserTel());
            oldTender.setUseruu(purchaseTender.getUseruu());
            oldTender.setIfAll(purchaseTender.getIfAll());
            oldTender.setQuestionEndDate(purchaseTender.getQuestionEndDate());
            oldTender.setTenderAttaches(purchaseTender.getTenderAttaches());
            oldTender = purchaseTenderDao.save(oldTender);
            if (!CollectionUtils.isEmpty(enInfos)) { // 不为空时，是修改过供应商的。
                // 先清除掉所有存在的投标单
                List<SaleTender> oldSaleTenders = saleTenderDao.findByEnUUAndCode(oldTender.getEnUU(), oldTender.getCode());
                for (SaleTender saleTender : oldSaleTenders) {
                    for (SaleTenderItem saleTenderItem : saleTender.getSaleTenderItems()) {
                        saleTenderItemDao.delete(saleTenderItem.getId());
                    }
                    saleTenderDao.delete(saleTender.getId());
                }
            }
            // 新的招标产品明细
            Set<PurchaseTenderProd> tenderProds = purchaseTender.getPurchaseTenderProds();
            if (!CollectionUtils.isEmpty(tenderProds)) { // 不为空是产品明细修改
                for (PurchaseTenderProd tenderProd : tenderProds) {
                    if (tenderProd.getId() != null) { // 存在id的是修改的
                        PurchaseTenderProd oldTenderProd = purchaseTenderProdDao.findOne(tenderProd.getId());
                        oldTenderProd.setBrand(tenderProd.getBrand());
                        oldTenderProd.setProdCode(tenderProd.getProdCode());
                        oldTenderProd.setProdTitle(tenderProd.getProdTitle());
                        oldTenderProd.setUnit(tenderProd.getUnit());
                        oldTenderProd.setQty(tenderProd.getQty());
                        Set<SaleTenderItem> saleTenderItems = new HashSet<>();
                        oldTenderProd.setSaleTenderItems(saleTenderItems);
                        purchaseTenderProdDao.save(oldTenderProd);
                    } else { // 新增的
                        PurchaseTenderSave purchaseTenderSave = new PurchaseTenderSave();
                        BeanUtils.copyProperties(oldTender,purchaseTenderSave);
                        tenderProd.setTender(purchaseTenderSave);
                        purchaseTenderProdDao.save(tenderProd);
                    }
                    if (!ifOpen) { // 指定招标的增加招标单
                        addSaleTender(oldTender, enInfos, tenderProd);
                    }
                }
            } else {
                tenderProds = oldTender.getPurchaseTenderProds();
                for (PurchaseTenderProd tenderProd : tenderProds) {
                    if (!ifOpen) { // 指定招标的增加招标单
                        addSaleTender(oldTender, enInfos, tenderProd);
                    }
                }
            }
            map.put("id", oldTender.getId());
            map.put("code", oldTender.getCode());
            return map;
        }
        map.put("success", false);
        return map;
    }

    /**
     * 根据供应商信息和招标单新增投标单
     *
     * @param tender
     * @param contactInfos
     * @param tenderProd
     */
    private void addSaleTender(PurchaseTender tender, List<TenderContactInfo> contactInfos, PurchaseTenderProd tenderProd) {
        List<SaleTender> eventList = new ArrayList<>();
        final String appId = "uas";// 应用来源
        if (!CollectionUtils.isEmpty(contactInfos)) {
            List<SaleTenderItem> saleTenderItems = new ArrayList<>();
            for (TenderContactInfo contactInfo : contactInfos) {
                if (null != contactInfo.getUu()) {
                    Enterprise enterprise = enterpriseDao.findOne(contactInfo.getUu());
                    if (null != enterprise) {
                        List<User> users = userDao.findUserByUserTel(contactInfo.getContactTel());
                        if (!CollectionUtils.isEmpty(users)) { // 根据手机号找不到用户时,设置为企业管理员信息
                            contactInfo.setContactUU(users.get(0).getUserUU());
                        } else {
                            User admin = userDao.findOne(enterprise.getEnAdminuu());
                            if (null != admin) {
                                contactInfo.setContactTel(admin.getUserTel());
                                contactInfo.setContact(admin.getUserName());
                                contactInfo.setContactUU(admin.getUserUU());
                            }
                        }
                        EnterpriseBaseInfo enBaseInfo = enterpriseBaseInfoDao.findOne(contactInfo.getUu());
                        if (null == enBaseInfo) {
                            enBaseInfo = new EnterpriseBaseInfo(enterprise.getUu(), enterprise.getEnBussinessCode(), enterprise.getEnName(), enterprise.getEnAddress());
                        }
                        SaleTenderItem tenderItem = new SaleTenderItem();
                        // 找不到投标单主表才新建一个,确保只有一个投标单
                        if (tender.getEnUU() != null && enBaseInfo.getUu() != null && tender.getCode() != null) {
                            SaleTender saleTender = saleTenderDao.findByEnUUAndVendUUAndCode(tender.getEnUU(), enBaseInfo.getUu(), tender.getCode());
                            if (null == saleTender) {
                                saleTender = new SaleTender(tender, contactInfo);
                                saleTender.setVendUU(enBaseInfo.getUu());
                                saleTender.setEnterpriseBaseInfo(enBaseInfo); // 投标单主表构造完毕
                                List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(saleTender.getEnUU(), saleTender.getVendUU());
                                Vendor vendor = null;
                                if (vendors.size() == 0) {// 供应商列表中不存在供应商关系
                                    vendor = addVendor(saleTender);// 增加供应商关系
                                    if (null != vendor) {
                                        vendorService.addPartnerShipRecord(vendor, appId);
                                    }
                                } else {
                                    vendor = vendors.get(0);
                                }
                                if (vendor != null) {// 供应商uu号不为非法的值
                                    // 如果客户联系人UU号为空或者UU号不存在对应的用户，则设为供应商资料中的供应商联系人（可能为空）
                                    if (saleTender.getUseruu() != null) {
                                        List<User> vendUsers = userDao.findByEnUUAndUserUU(vendor.getVendEnUU(),
                                                saleTender.getUseruu());
                                        if (vendUsers.size() == 0) {
                                            saleTender.setUseruu(vendor.getVendUserUU());
                                        }
                                    }
                                }
                                saleTender = saleTenderDao.save(saleTender);
                                // 新增消息
                                eventList.add(saleTender);
                                if (tender.getIsPublish() == Constant.YES) {
                                    saveUserOrders(saleTender, tender);
                                }
                            }
                            tenderItem.setSaleTender(saleTender);
                        }
                        tenderItem.setTenderProd(tenderProd);
                        saleTenderItemDao.save(tenderItem);
                        saleTenderItems.add(tenderItem);
                    }
                }
            }
        } else {
            if (tender.getEnUU() != null && tender.getCode() != null) {
                List<SaleTender> saleTenders = saleTenderDao.findByEnUUAndCode(tender.getEnUU(), tender.getCode());
                for (SaleTender saleTender : saleTenders) {
                    saleTender.setIsPublish(Constant.YES);
                    if (tender.getIsPublish() == Constant.YES) {
                        saveUserOrders(saleTender, tender);
                    }
                }
                saleTenderDao.save(saleTenders);
            }
        }
        if (Constant.YES == tender.getIsPublish()) {
            ContextUtils.publishEvent(new PurchaseTenderSaveReleaseEvent(eventList));
        }
    }

    /**
     * 保存
     *
     * @param saleTender 客户招标
     * @param purchaseTender 采购招标
     * @return
     */
    private void saveUserOrders(final SaleTender saleTender, final PurchaseTender purchaseTender) {
        ThreadTask.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                /* 添加供应商的阅读记录*/
                List<UserOrders> list = new ArrayList<>();
                Set<Long> userUUs = new HashSet<>();
                // 添加管理员
                List<Role> roles = roleDao.findByEnUUAndIssys(saleTender.getVendUU(), Constant.YES);
                if (!CollectionUtils.isEmpty(roles)) {
                    List<User> admins = userDao.findByRole(roles.get(0).getId());
                    for (User admin : admins) {
                        if (!userUUs.contains(admin.getUserUU())) {
                            userUUs.add(admin.getUserUU());
                        }
                    }
                }
                List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(saleTender.getEnUU(), saleTender.getVendUU());
                // 查找有权限的用户
                if (!CollectionUtils.isEmpty(vendors)) {
                    Long vendorId = vendors.get(0).getId();
                    List<Distribute> distributes = distributeDao.findByVendorId(vendorId);
                    if (!CollectionUtils.isEmpty(distributes)) {
                        for (Distribute distribute : distributes) {
                            if (!userUUs.contains(distribute.getUserUU())) {
                                userUUs.add(distribute.getUserUU());
                            }
                        }
                    }
                }
                UserOrders userOrders;
                for (Long userUU : userUUs) {
                    if (userUU == null) {
                        continue;
                    }
                    userOrders = new UserOrders(userUU, saleTender.getVendUU(), purchaseTender.getId(), "sale", "v$purc$tender");
                    list.add(userOrders);
                }
                    /* 添加采购员的阅读记录*/
                if (purchaseTender.getUseruu() != null) {
                    userOrders = new UserOrders(purchaseTender.getUseruu(), purchaseTender.getEnUU(), purchaseTender.getId(), "purc", "v$purc$tender");
                    list.add(userOrders);
                }
                userOrderDao.save(list);
            }
        });
    }

    /**
     * 添加供应商资料
     *
     * @param saleTender
     */
    private Vendor addVendor(SaleTender saleTender) {
        Enterprise enterprise = enterpriseDao.findOne(saleTender.getVendUU());
        if (enterprise != null) {
            Vendor vendor = new Vendor();
            vendor.setMyEnUU(saleTender.getEnUU());
            vendor.setMyEnterprise(saleTender.getEnterprise());
            vendor.setMyUserUU(saleTender.getRecorderuu());
            vendor.setVendorEnterprise(enterprise);
            vendor.setVendEnUU(enterprise.getUu());
            vendor.setCustswitch(Constant.YES);
            vendor.setVendswitch(Constant.YES);
            if (saleTender.getUseruu() != null) {
                List<User> users = userDao.findByEnUUAndUserUU(enterprise.getUu(), saleTender.getUseruu());
                if (users.size() > 0) {
                    vendor.setVendUserUU(saleTender.getUseruu());
                }
            }
            return vendorDao.save(vendor);
        }
        return null;
    }

    /**
     * 删除产品明细
     *
     * @param tenderProdId
     */
    @Override
    public ModelMap deleteProd(Long tenderProdId) {
        PurchaseTenderProd tenderProd = purchaseTenderProdDao.findOne(tenderProdId);
        ModelMap map = new ModelMap();
        if (null != tenderProd) {
            for (SaleTenderItem saleTenderItem : tenderProd.getSaleTenderItems()) {
                saleTenderItemDao.delete(saleTenderItem.getId());
            }
            purchaseTenderProdDao.delete(tenderProd.getId());
            map.put("success", true);
            return map;
        }
        map.put("success", false);
        return map;
    }

    /**
     * 删除对应供应商的投标单
     *
     * @param id
     * @param vendUU
     */
    @Override
    public ModelMap removeSaleTender(Long id, Long vendUU) {
        PurchaseTender purchaseTender = purchaseTenderDao.findOne(id);
        ModelMap map = new ModelMap();
        if (purchaseTender != null) {
            SaleTender saleTender = saleTenderDao.findByEnUUAndVendUUAndCode(purchaseTender.getEnUU(), vendUU, purchaseTender.getCode());
            if (saleTender != null) {
                for (SaleTenderItem saleTenderItem : saleTender.getSaleTenderItems()) {
                    saleTenderItemDao.delete(saleTenderItem.getId());
                }
                SaleTender oldSaleTender = saleTenderDao.findOne(saleTender.getId());
                if (oldSaleTender != null) {
                    saleTenderDao.delete(oldSaleTender);
                }
                map.put("success", true);
                return map;
            }
        }
        map.put("success", false);
        return map;
    }

    @Override
    public ModelMap auditPurchaseTender(Long id, Short auditStatus) {
        ModelMap map = new ModelMap();
        PurchaseTender purchaseTender = purchaseTenderDao.findOne(id);
        List<SaleTender> saleTenders = saleTenderDao.findByEnUUAndCode(purchaseTender.getEnUU(), purchaseTender.getCode());
        purchaseTender.setAuditStatus(auditStatus);
//        boolean hasBid = false; // 投标单是否投标
        boolean hasDecided = false; // 招标明细是否定标
        for (SaleTender saleTender : saleTenders) {
            for (SaleTenderItem saleTenderItem : saleTender.getSaleTenderItems()) {
//                if (null != saleTenderItem.getPrice() && (null == saleTender.getAuditStatus() || Constant.YES == saleTender.getAuditStatus())) { // 存在有价格且投标单状态不是已提交的就是已投标
//                    hasBid = true;
//                }
                if (null != saleTenderItem.getApplyStatus() && Constant.YES == saleTenderItem.getApplyStatus()) { // 存在采纳的就是已结标
                    hasDecided = true;
                }
            }
//            if (auditStatus == Constant.NO) {
//                if (hasBid) {
//                    saleTender.setStatus("已投标");
//                } else {
//                    saleTender.setStatus("待投标");
//                }
//            } else {
//                  saleTender.setStatus("已结标");  // 这里不设置为已结标，在数据库视图根据publishDate去判断是否显示为已结标。
//            }
        }
        if (auditStatus == Constant.NO) {  // 招标单状态整体判断
            purchaseTender.setStatus("待评标");
        } else {
            if (hasDecided) {
                purchaseTender.setStatus("已结标");
            } else {
                purchaseTender.setStatus("流标");
            }
        }
        purchaseTenderDao.save(purchaseTender);
        saleTenderDao.save(saleTenders);
        map.put("success", true);
        return map;
    }

    @Override
    public ModelMap auditSaleTender(Long id, Short auditStatus) {
        ModelMap map = new ModelMap();
        SaleTender saleTender = saleTenderDao.findOne(id);
        saleTender.setAuditStatus(auditStatus);
        List<PurchaseTender> purchaseTenders = purchaseTenderDao.findByEnUUAndCode(saleTender.getEnUU(), saleTender.getCode());
        if (!CollectionUtils.isEmpty(purchaseTenders)) {
            PurchaseTender tender = purchaseTenders.get(0);
            if (Constant.NO == auditStatus) {
                boolean hasBid = false; // 默认无供应商投标
                saleTender.setStatus("待投标");
                for (PurchaseTenderProd tenderProd : tender.getPurchaseTenderProds()) {
                    for (SaleTenderItem item : tenderProd.getSaleTenderItems()) {
                        if (null != item.getPrice() && (null == saleTender.getAuditStatus() || Constant.YES == saleTender.getAuditStatus())) { // 投标明细存在价格，对应投标单单据不是已提交时，招标单为已投标
                            hasBid = true;
                        }
                    }
                }
                if (!hasBid) {
                    tender.setStatus("待投标");
                    purchaseTenderDao.save(tender);
                }
            } else {
                saleTender.setStatus("已投标");
                tender.setStatus("待评标");
                purchaseTenderDao.save(tender);
            }
        }
        saleTenderDao.save(saleTender);
        map.put("success", true);
        return map;
    }

    @Override
    public ModelMap getSaleTenderDetail(Long id) {
        SaleTenderErp saleTenderErp = saleTenderErpDao.findOne(id);
        List<PurchaseTender> tenders = purchaseTenderDao.findByEnUUAndCode(saleTenderErp.getEnUU(), saleTenderErp.getCode());
        Set<Attach> attachSet = new HashSet<>();
        TenderContactInfo tenderContactInfo = new TenderContactInfo();
        if (!CollectionUtils.isEmpty(tenders)) {
            PurchaseTender tender = tenders.get(0);
            attachSet = tender.getTenderAttaches();
            tenderContactInfo.setContact(tender.getUser());
            tenderContactInfo.setContactTel(tender.getUserTel());
            tenderContactInfo.setUu(tender.getEnUU());
        }
        ModelMap map = new ModelMap();
        map.put("saleTenderTemp", saleTenderErp);
        map.put("tenderAttaches", attachSet);
        map.put("tenderContactInfo", tenderContactInfo);
        return map;
    }

    /**
     * 投标
     *
     * @param saleTender
     * @param attaches
     * @return
     */
    @Override
    public ModelMap reply(SaleTender saleTender, List<Attach> attaches) {
        SaleTender oldSaleTender = saleTenderDao.findOne(saleTender.getId());
        Set<Attach> attachSet = new HashSet<>();
        oldSaleTender.setModified(new Date());
        // 提交时设置为0，审核后改为1
        oldSaleTender.setAuditStatus(Constant.NO);
        oldSaleTender.setCycle(saleTender.getCycle());
        oldSaleTender.setTaxrate(saleTender.getTaxrate());
        oldSaleTender.setTotalMoney(saleTender.getTotalMoney());
        if (null != saleTender.getEnterpriseBaseInfo()) {
            oldSaleTender.setEnterpriseBaseInfo(saleTender.getEnterpriseBaseInfo());
        }
        List<Attach> attachList = new ArrayList<>();
        for (Attach attach : attaches) {
            if (null == attach.getId()) {
                attach.setDescription("UAS投标附件");
                attachList.add(attach);
            } else {
                attachSet.add(attach);
            }
        }
        if (!CollectionUtils.isEmpty(attachList)) {
            attachList = attachDao.save(attachList);
            attachSet.addAll(attachList);
        }
        oldSaleTender.setBidAttaches(attachSet);
        saleTenderDao.save(oldSaleTender);
        if (saleTender.getSaleTenderItems().size() > 0 ) {
            for (SaleTenderItem tenderItem : saleTender.getSaleTenderItems()) {
                SaleTenderItem saleTenderItem = saleTenderItemDao.findOne(tenderItem.getId());
                // 需要修改见索引主表中的字段来触发索引更新
                saleTenderItem.getTenderProd().getTender().setModified(new Date());
//                saleTenderItem.getTenderProd().getTender().setStatus("待评标");  //审核时修改状态
                saleTenderItem.setPrice(tenderItem.getPrice());
                saleTenderItem.setTaxrate(tenderItem.getTaxrate());
                saleTenderItem.setCycle(tenderItem.getCycle());
                saleTenderItemDao.save(saleTenderItem);
            }
        }
        ModelMap map = new ModelMap();
        map.put("success", true);
        return map;
    }

    /**
     * 投标（未修改附件）
     *
     * @param saleTender
     * @return
     */
    @Override
    public ModelMap reply(SaleTender saleTender) {
        SaleTender oldSaleTender = saleTenderDao.findOne(saleTender.getId());
        EnterpriseBaseInfo enterpriseBaseInfo = saleTender.getEnterpriseBaseInfo();
        if (null != enterpriseBaseInfo) {
            enterpriseBaseInfoDao.save(enterpriseBaseInfo);
            oldSaleTender.setEnterpriseBaseInfo(enterpriseBaseInfo);
        }
        oldSaleTender.setModified(new Date());
        // 提交时设置为0，审核后改为1
        oldSaleTender.setAuditStatus(Constant.NO);
        oldSaleTender.setCycle(saleTender.getCycle());
        oldSaleTender.setTaxrate(saleTender.getTaxrate());
        oldSaleTender.setTotalMoney(saleTender.getTotalMoney());
        saleTenderDao.save(oldSaleTender);
        if (!CollectionUtils.isEmpty(saleTender.getSaleTenderItems())) {
            for (SaleTenderItem tenderItem : saleTender.getSaleTenderItems()) {
                SaleTenderItem saleTenderItem = saleTenderItemDao.findOne(tenderItem.getId());
                // 需要修改见索引主表中的字段来触发索引更新
                saleTenderItem.getTenderProd().getTender().setModified(new Date());
//                saleTenderItem.getTenderProd().getTender().setStatus("待评标");  //审核时修改状态
                saleTenderItem.setPrice(tenderItem.getPrice());
                saleTenderItem.setTaxrate(tenderItem.getTaxrate());
                saleTenderItem.setCycle(tenderItem.getCycle());
                saleTenderItemDao.save(saleTenderItem);
            }
        }
        ModelMap map = new ModelMap();
        map.put("success", true);
        return map;
    }


    /**
     * 采购方定标操作
     *
     * @param saleTenderItems
     * @return
     */
    @Override
    public ModelMap decide(List<SaleTenderItem> saleTenderItems) {
        SaleTenderItem tenderItem = saleTenderItemDao.findOne(saleTenderItems.get(0).getId());
        PurchaseTender tender = new PurchaseTender();
        PurchaseTenderSave purchaseTenderSave = tenderItem.getTenderProd().getTender();
        BeanUtils.copyProperties(purchaseTenderSave,tender);
        tender.setModified(new Date());
        // 提交时设为0，审核后改为1
        tender.setAuditStatus(Constant.NO);
        purchaseTenderDao.save(tender);
        List<SaleTenderItem> items = new ArrayList<>();
        if (saleTenderItems.size() > 0 ) {
            for (SaleTenderItem item : saleTenderItems) {
                SaleTenderItem saleTenderItem = saleTenderItemDao.findOne(item.getId());
                saleTenderItem.setApplyStatus(item.getApplyStatus());
                saleTenderItem.setDescription(item.getDescription());
                items.add(saleTenderItem);
            }
            saleTenderItemDao.save(items);
        }
        Set<Long> saleTenderIds = new HashSet<>();
        List<SaleTender> saleTenders = new ArrayList<>();
        for (SaleTenderItem saleTenderItem : saleTenderItems) {
            SaleTenderItem item = saleTenderItemDao.findOne(saleTenderItem.getId());
            if (!saleTenderIds.contains(item.getSaleTender().getId())) {
                saleTenderIds.add(item.getSaleTender().getId());
                saleTenders.add(item.getSaleTender());
            }
        }
        try {
            // 定标时，给供应商产生消息
            ContextUtils.publishEvent(new PurchaseTenderDecideReleaseEvent(saleTenders));
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelMap map = new ModelMap();
        map.put("success", true);
        return map;
    }

    /**
     * 全包类型招标单定标
     * @param decideTenders
     * @return
     */
    @Override
    public ModelMap decideTenderAll(List<DecideTender> decideTenders) {
        ModelMap map = new ModelMap();
        if (!CollectionUtils.isEmpty(decideTenders)) {
            Set<Long> saleTenderIds = new HashSet<>();
            Set<Long> tenderIds = new HashSet<>();
            List<SaleTender> eventList = new ArrayList<>();
            for (DecideTender decideTender : decideTenders) {
                SaleTender saleTender = saleTenderDao.findOne(decideTender.getSaleTenderId());
                if (null != saleTender) {
//                    PurchaseTender tender = purchaseTenderDao.findOne(saleTender.getPtId());
//                    if (null != tender) {
//                        tender.setModified(new Date());
//                        // 提交时设为0，审核后改为1
//                        tender.setAuditStatus(Constant.NO);
//                    }
                    tenderIds.add(saleTender.getPtId());
                    purchaseTenderDao.updateSaleTenderItemDecide(decideTender.getApplyStatus(), decideTender.getReason(), decideTender.getSaleTenderId());
                    if (!saleTenderIds.contains(saleTender.getId())) {
                        saleTenderIds.add(saleTender.getId());
                        eventList.add(saleTender);
                    }
                }
            }
            purchaseTenderDao.updateTenderDecide(tenderIds, new Date());
            map.put("success", true);
            try {
                // 定标时，给供应商产生消息
                ContextUtils.publishEvent(new PurchaseTenderDecideReleaseEvent(eventList));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            map.put("success", "参数为空");
        }
        return map;
    }

    @Override
    public List<PurchaseTenderQuestion> getQuestionList(Long uu) {
        return purchaseTenderQuestionDao.findByVendUU(uu);
    }

    @Override
    public SaleTenderQuestion getQuestionDetail(Long id) {
        return saleTenderQuestionDao.findOne(id);
    }

    @Override
    public PurchaseTenderAnswer getThisQuestionAll(Long tenderId) {
        PurchaseTender tender = purchaseTenderDao.findOne(tenderId);
        if (null != tender) {
            return tender.getAnswer();
        }
        return null;
    }

    @Override
    public ModelMap saveQuestionAnswer(PurchaseTenderAnswer answer) {
        ModelMap map = new ModelMap();
        Set<Attach> answerAttaches = answer.getAnswerAttaches();
        PurchaseTenderAnswer purchaseTenderAnswer = purchaseTenderAnswerDao.findOne(answer.getId());
        if (!CollectionUtils.isEmpty(answerAttaches)) {
            attachDao.save(answerAttaches);
            purchaseTenderAnswer.setAnswerAttaches(answerAttaches);
        }
        purchaseTenderAnswer.setCode(answer.getCode());
        purchaseTenderAnswer.setAuditDate(answer.getAuditDate());
        purchaseTenderAnswer.setInDate(answer.getInDate());
        purchaseTenderAnswer.setRecorder(answer.getRecorder());
        purchaseTenderAnswer.setRemark(answer.getRemark());
        purchaseTenderAnswer.setReplyDate(answer.getReplyDate());
        purchaseTenderAnswer.setStatus(answer.getStatus());
        // 对应提问单修改为已回复
        purchaseTenderAnswer = purchaseTenderAnswerDao.save(purchaseTenderAnswer);
        saleTenderQuestionDao.setReplied(purchaseTenderAnswer.getId(), purchaseTenderAnswer.getReplyDate());
        map.put("success", true);
        map.put("id", purchaseTenderAnswer.getId());
        return map;
    }
}

