package com.uas.platform.b2b.erp.controller;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.platform.b2b.erp.model.SaleTenderErp;
import com.uas.platform.b2b.erp.service.TenderService;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.search.SearchService;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.service.VendorService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.temporary.model.DecideTender;
import com.uas.platform.b2b.temporary.model.TenderContactInfo;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.PageParams;
import com.uas.platform.core.model.Status;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import com.uas.platform.core.web.bind.RequestState;
import com.uas.search.b2b.model.MultiValue;
import com.uas.search.b2b.model.SPage;
import com.uas.search.b2b.model.Sort;
import com.uas.search.b2b.util.SearchConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by dongbw
 * 17/05/03 9:54.
 */
@SuppressWarnings("deprecation")
@RestController
@RequestMapping(value = "/erp/tender")
public class TenderController {

    @Autowired
    private TenderService tenderService;

    @Autowired
    private SearchService searchService;

    @Autowired
    private UserService userService;

    @Autowired
    private VendorService vendorService;

    /**
     * 作为采购方，发布招标单
     *
     * @param tender 招标单
     */
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public ModelMap publishTender(String tender, String enInfos, String attaches) throws UnsupportedEncodingException {
        tender = URLDecoder.decode(tender, "UTF-8");
        PurchaseTender purchaseTender = FlexJsonUtils.fromJson(tender, PurchaseTender.class);
        if (null != enInfos) {
            enInfos = URLDecoder.decode(enInfos, "UTF-8");
            List<TenderContactInfo> contactInfos = FlexJsonUtils.fromJsonArray(enInfos, TenderContactInfo.class);
            if (null != attaches) {
                attaches = URLDecoder.decode(attaches, "UTF-8");
                List<Attach> tenderAttaches = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                return tenderService.publishOrSave(purchaseTender, contactInfos, tenderAttaches);
            } else {
                return tenderService.publishOrSave(purchaseTender, contactInfos, null);
            }

        } else {
            if (null != attaches) {
                attaches = URLDecoder.decode(attaches, "UTF-8");
                List<Attach> tenderAttaches = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                return tenderService.publishOrSave(purchaseTender, null, tenderAttaches);
            } else {
                return tenderService.publishOrSave(purchaseTender, null, null);
            }
        }
    }

    /**
     * 作为采购方，保存招标单
     *
     * @param tender    招标单
     * @param enInfos 所选供应商uu
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public ModelMap saveTender(String tender, String enInfos, String attaches) throws UnsupportedEncodingException {
        tender = URLDecoder.decode(tender, "UTF-8");
        PurchaseTender purchaseTender = FlexJsonUtils.fromJson(tender, PurchaseTender.class);
        if (null != enInfos) {
            enInfos = URLDecoder.decode(enInfos, "UTF-8");
            List<TenderContactInfo> contactInfos = FlexJsonUtils.fromJsonArray(enInfos, TenderContactInfo.class);
            if (null != attaches) {
                attaches = URLDecoder.decode(attaches, "UTF-8");
                List<Attach> saleTenderAttaches = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                return tenderService.publishOrSave(purchaseTender, contactInfos, saleTenderAttaches);
            } else {
                return tenderService.publishOrSave(purchaseTender, contactInfos, null);
            }

        } else {
            if (null != attaches) {
                attaches = URLDecoder.decode(attaches, "UTF-8");
                List<Attach> saleTenderAttaches = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                return tenderService.publishOrSave(purchaseTender, null, saleTenderAttaches);
            } else {
                return tenderService.publishOrSave(purchaseTender, null, null);
            }
        }
    }

    /**
     * 供应商投标
     *
     * @param saleTender  投标单
     * @param attaches 投标附件
     */
    @RequestMapping(value = "/reply", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap replyTender(String saleTender, String attaches) throws UnsupportedEncodingException {
        SaleTender saleTender1 = new SaleTender();
        if (null != saleTender && !"".equals(saleTender)) {
            saleTender = URLDecoder.decode(saleTender, "UTF-8");
            saleTender1 = FlexJsonUtils.fromJson(saleTender, SaleTender.class);
        }
        if (null != attaches && !"".equals(attaches)) {
            attaches = URLDecoder.decode(attaches, "UTF-8");
            List<Attach> saleTenderAttaches = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
            return tenderService.reply(saleTender1, saleTenderAttaches);
        }
        return tenderService.reply(saleTender1);
    }

    /**
     *  获取平台供应商
     * @param params  分页参数
     * @param keyword  关键词
     * @return  企业信息分页
     */
    @RequestMapping(value = "/vendors", method = RequestMethod.GET)
    public SPage<Enterprise> getVendors(PageParams params, String keyword) {
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, null);
        pageParams.getFilters().put("ve_myenuu", SystemSession.getUser().getEnterprise().getUu());
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("ve_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        return searchService.searchVendorIds(keyword, pageParams);
    }

    /**
     * 获取供应商联系人
     * @param enuu 招标企业uu
     * @param venduu 供应商UU
     *
     */
    @RequestMapping(value = "/contacts", method = RequestMethod.GET)
    public List<VendorContact> getVendorContacts(Long enuu, Long venduu) {
       return tenderService.getVendContacts(enuu, venduu);
    }

    /**
     * 保存供应商联系人
     *
     * @param contact
     * @return
     */
    @RequestMapping(value = "/addcontact", method = RequestMethod.POST)
    public ModelMap savecontact(String contact) throws UnsupportedEncodingException {
        contact = URLDecoder.decode(contact, "UTF-8");
        VendorContact vendor = JSON.parseObject(contact, VendorContact.class);
        vendorService.saveContact(vendor);
        ModelMap map = new ModelMap();
        map.put("success", true);
        return map;
    }

    /**
     * 查看招标单详情
     *
     * @param id 招标单id
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public PurchaseTender getTenderById(Long id) {
        PurchaseTender tender =  tenderService.findById(id);
        return tender;
    }


    /**
     * 公开招标转投标单
     *
     * @param id 招标单id
     * @return 投标单id 和code
     */
    @RequestMapping(value = "/addItems", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap addTenderItemById(Long id) {
        return tenderService.addTenderItemById(id);
    }



    /**
     * 招标方定标
     *
     * @param saleTenderItems 投标明细
     */
    @RequestMapping(value = "/decide", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap decideTender(String saleTenderItems) throws UnsupportedEncodingException {
        saleTenderItems = URLDecoder.decode(saleTenderItems, "UTF-8");
        List<SaleTenderItem> tenderItems = FlexJsonUtils.fromJsonArray(saleTenderItems, SaleTenderItem.class);
        return tenderService.decide(tenderItems);
    }

    /**
     * 作为供应商，查看收到的投标单（全部）
     *
     * @param params 分页参数
     * @return Spage
     */
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public SPage<SaleTenderErp> getAllTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 判断当前用户是否被客户分配
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("st_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("st_ispublish", Constant.NO); // 已发布
        pageParams.setNotEqualFilters(map);
        pageParams.getFilters().put("st_venduu", SystemSession.getUser().getEnterprise().getUu()); // 投标单属于本企业
        return searchService.erpSearchSaleTenderIds(keyword, pageParams);
    }

    /**
     * 作为供应商，查看收到的投标单（已结标）
     *
     * @param params 分页参数
     * @return Sapge
     */
    @RequestMapping(params = RequestState.END, method = RequestMethod.GET)
    @ResponseBody
    public SPage<SaleTenderErp> getDoneTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 判断当前用户是否被客户分配
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("st_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("st_ispublish", Constant.NO); // 已发布
        pageParams.setNotEqualFilters(map);
        pageParams.getFilters().put("st_venduu", SystemSession.getUser().getEnterprise().getUu()); // 投标单属于本企业
        pageParams.getFilters().put("st_status", "已结标");
        return searchService.erpSearchSaleTenderIds(keyword, pageParams);
    }

    /**
     * 作为供应商，查看收到的投标单（已投标）
     *
     * @param params 分页参数
     * @return 招标单Spage
     */
    @RequestMapping(params = RequestState.DONE, method = RequestMethod.GET)
    @ResponseBody
    public SPage<SaleTenderErp> getWaitingTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 判断当前用户是否被客户分配
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("st_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("st_ispublish", Constant.NO); // 已发布
        pageParams.setNotEqualFilters(map);
        pageParams.getFilters().put("st_venduu", SystemSession.getUser().getEnterprise().getUu()); // 投标单属于本企业
        pageParams.getFilters().put("st_status", "已投标");
        return searchService.erpSearchSaleTenderIds(keyword, pageParams);
    }


    /**
     * 作为供应商，查看收到的投标单（待投标）
     *
     * @param params 分页参数
     * @return 招标单Spage
     */
    @RequestMapping(params = RequestState.TODO, method = RequestMethod.GET)
    @ResponseBody
    public SPage<SaleTenderErp> getTodoTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 判断当前用户是否被客户分配
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("st_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("st_ispublish", Constant.NO); // 已发布
        pageParams.setNotEqualFilters(map);
        pageParams.getFilters().put("st_venduu", SystemSession.getUser().getEnterprise().getUu()); // 投标单属于本企业
        pageParams.getFilters().put("st_status", "待投标");
        return searchService.erpSearchSaleTenderIds(keyword, pageParams);
    }


//    /**
//     * 作为供应商，查看收到的投标单（过期）
//     *
//     * @param params 分页参数
//     * @return 招标单Spage
//     */
//    @RequestMapping(params = RequestState.END, method = RequestMethod.GET)
//    @ResponseBody
//    public SPage<PurchaseTender> getEndTenders(PageParams params, String searchFilter) {
//        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
//        String keyword = jsonObject.getString("keyword");
//        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
//        // 判断当前用户是否被客户分配
//        SearchFilter filter = userService.distribute();
//        if (filter != null && filter.getDistribute() == null) {
//            return null;
//        }
//        List<Sort> sortList = new ArrayList<>();
//        sortList.add(new Sort("pt_id", false, Sort.Type.LONG, 1L));
//        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
//        pageParams.getFilters().put("tp_ptid", SystemSession.getUser().getEnterprise().getEnName());
//        pageParams.getFilters().put("pt_ispublish", Constant.YES);
////        pageParams.getFilters().put("pt_ifopen", Constant.NO);
//        pageParams.getFilters().put("pt_status", "待投标");
//        pageParams.getFilters().put("pt_overdue", Constant.YES);
//        return searchService.erpSearchPurcTenderIds(keyword, pageParams);
//    }


    /**
     * 作为供应商，查看平台开放招标单（全部）
     *
     * @param params 分页参数
     * @return 招标单Spage
     */
    @RequestMapping(value = "/open", method = RequestMethod.GET)
    @ResponseBody
    public SPage<PurchaseTender> getAllOpenTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("pt_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("pt_enuu", SystemSession.getUser().getEnterprise().getUu());
        pageParams.setNotEqualFilters(map);
        pageParams.getFilters().put("pt_ispublish", Constant.YES);
        pageParams.getFilters().put("pt_ifopen", Constant.YES);
        return searchService.erpSearchPurcTenderIds(keyword, pageParams);
    }



    /**
     * 作为采购方，查看发出的招标单（全部）
     *
     * @param params 分页参数
     * @return   招标单分页
     */
    @RequestMapping(value = "/purc", method = RequestMethod.GET)
    @ResponseBody
    public SPage<PurchaseTender> getMyAllTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 当前登录企业作为客户
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        buildFilter(filter, pageParams);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("pt_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("pt_enuu", SystemSession.getUser().getEnterprise().getUu());
        return searchService.erpSearchPurcTenderIds(keyword, pageParams);
    }

    /**
     * filter处理
     *
     * @param filter     拦截器
     * @param pageParams 分页参数
     */
    private void buildFilter(SearchFilter filter, com.uas.search.b2b.model.PageParams pageParams) {
        if (filter != null && !CollectionUtils.isEmpty(filter.getDistribute())) {
            List<Object> list = new ArrayList<>();
            list.addAll(filter.getDistribute());
            pageParams.getFilters().put("pti_venduu", new MultiValue(list, true));
        }
    }

    /**
     * 作为采购方，查看发出的招标单（已结标）
     *
     * @param params  分页参数
     * @return   招标单分页
     */
    @RequestMapping(value = "/purc",params = RequestState.DONE, method = RequestMethod.GET)
    @ResponseBody
    public SPage<PurchaseTender> getMyDoneTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 当前登录企业作为客户
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        buildFilter(filter, pageParams);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("pt_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("pt_enuu", SystemSession.getUser().getEnterprise().getUu());
        pageParams.getFilters().put("pt_ispublish", Constant.YES);
        pageParams.getFilters().put("pt_status", "已结标");
        pageParams.getFilters().put("pt_overdue", Constant.YES);
//        pageParams.getFilters().put("pt_result", Constant.YES);
        return searchService.erpSearchPurcTenderIds(keyword, pageParams);
    }

    /**
     * 作为采购方，查看发出的招标单（流标）
     *
     * @param params  分页参数
     * @return   招标单分页
     */
    @RequestMapping(value = "/purc",params = RequestState.END, method = RequestMethod.GET)
    @ResponseBody
    public SPage<PurchaseTender> getMyEndTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 当前登录企业作为客户
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        buildFilter(filter, pageParams);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("pt_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("pt_enuu", SystemSession.getUser().getEnterprise().getUu());
        pageParams.getFilters().put("pt_ispublish", Constant.YES);
        pageParams.getFilters().put("pt_status", "流标");
        pageParams.getFilters().put("pt_overdue", Constant.YES);
//        pageParams.getFilters().put("pt_result", Constant.YES);
        return searchService.erpSearchPurcTenderIds(keyword, pageParams);
    }


    /**
     * 作为采购方，查看发出的招标单（待评标）
     *
     * @param params  分页参数
     * @return   招标单分页
     */
    @RequestMapping(value = "/purc",params = "_state=tobid", method = RequestMethod.GET)
    @ResponseBody
    public SPage<PurchaseTender> getMyWaitingTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 当前登录企业作为客户
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        buildFilter(filter, pageParams);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("pt_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("pt_enuu", SystemSession.getUser().getEnterprise().getUu());
        pageParams.getFilters().put("pt_ispublish", Constant.YES);
        pageParams.getFilters().put("pt_status", "待评标");
        pageParams.getFilters().put("pt_overdue", Constant.YES);
        pageParams.getFilters().put("pt_result", Constant.NO);
        return searchService.erpSearchPurcTenderIds(keyword, pageParams);
    }

    /**
     * 作为采购方，查看发出的招标单（待投标）
     *
     * @param params 参数
     * @return 单据
     */
    @RequestMapping(value = "/purc", params = RequestState.TODO, method = RequestMethod.GET)
    @ResponseBody
    public SPage<PurchaseTender> getMyTodoTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 当前登录企业作为客户
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        buildFilter(filter, pageParams);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("pt_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("pt_enuu", SystemSession.getUser().getEnterprise().getUu());
        pageParams.getFilters().put("pt_ispublish", Constant.YES);
        pageParams.getFilters().put("pt_overdue", Constant.NO);
        return searchService.erpSearchPurcTenderIds(keyword, pageParams);
    }


    /**
     * 作为客户，查看发出的招标单（待发布）
     *
     * @param params       参数
     * @param searchFilter 搜索参数
     */
    @RequestMapping(value = "/purc", params = RequestState.WAITING, method = RequestMethod.GET)
    @ResponseBody
    public SPage<PurchaseTender> getWaitingPTenders(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 当前登录企业作为客户

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("pt_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("pt_enuu", SystemSession.getUser().getEnterprise().getUu());
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        buildFilter(filter, pageParams);
        pageParams.getFilters().put("pt_ispublish", Constant.NO);
        pageParams.getFilters().put("pt_status", "待发布");
        return searchService.erpSearchPurcTenderIds(keyword, pageParams);
    }

    /**
     * 招标附件上传
     *
     * @return attach
     */
    @RequestMapping(value = "/addTenderAttach", method = RequestMethod.POST)
    @ResponseBody
    public Attach addTenderAttaches(FileUpload uploadItem) throws Exception {
        return tenderService.addTenderAttaches(uploadItem);
    }

    /**
     * 投标附件上传
     *
     * @return attach
     */
    @RequestMapping(value = "/addTenderItemAttach", method = RequestMethod.POST)
    @ResponseBody
    public Attach addTenderItemAttaches(FileUpload uploadItem) throws Exception {
        return tenderService.addTenderItemAttaches(uploadItem);
    }

    /**
     * 查看最近公开招标
     *
     * @return 招标单List
     */
    @RequestMapping(value = "/latestOpenTender", method = RequestMethod.GET)
    @ResponseBody
    public List<PurchaseTender> getLatestOpenTender() {
//        PageInfo info = new PageInfo(params);
//        info.sorting("date", Direction.DESC); // 按发布日期倒序
        return tenderService.findOpen();
    }

    /**
     * 删除在录入的单据
     *
     * @param id 招标单id
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap deleteTender(Long id) {
        return tenderService.delete(id);
    }

    /**
     * 发布在录入单据
     *
     * @param tender 招标单json
     */
    @RequestMapping(value = "/publishSaved", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public ModelMap publishSavedTender(String tender, String enInfos, String attaches) throws UnsupportedEncodingException {
        tender = URLDecoder.decode(tender, "UTF-8");
        PurchaseTender purchaseTender = FlexJsonUtils.fromJson(tender, PurchaseTender.class);
        if (purchaseTender.getIfOpen() == Constant.YES) { // 开放时进另外的方法
            if (null != attaches) {
                attaches = URLDecoder.decode(attaches, "UTF-8");
                List<Attach> attachList = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                return tenderService.publishSavedOpen(purchaseTender, attachList);
            }
            return tenderService.publishSavedOpen(purchaseTender);
        } else {
            if (null != enInfos) {
                enInfos = URLDecoder.decode(enInfos, "UTF-8");
                List<TenderContactInfo> contactInfos = FlexJsonUtils.fromJsonArray(enInfos, TenderContactInfo.class);
                if (null != attaches) {
                    attaches = URLDecoder.decode(attaches, "UTF-8");
                    List<Attach> attachList = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                    return tenderService.publishSaved(purchaseTender, contactInfos, attachList);
                } else {
                    return tenderService.publishSaved(purchaseTender, contactInfos);
                }
            } else {
                if (null != attaches) {
                    attaches = URLDecoder.decode(attaches, "UTF-8");
                    List<Attach> attachList = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                    return tenderService.publishSaved(purchaseTender, null, attachList);
                } else {
                    return tenderService.publishSaved(purchaseTender, null);
                }
            }
        }
    }

    /**
     * 更新在录入单据
     *
     * @param tender    招标单
     * @param enInfos 供应商uu
     */
    @RequestMapping(value = "/updateSaved", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public ModelMap updateSavedTender(String tender, String enInfos, String attaches) throws UnsupportedEncodingException {
        tender = URLDecoder.decode(tender, "UTF-8");
        PurchaseTender purchaseTender = FlexJsonUtils.fromJson(tender, PurchaseTender.class);
        if (purchaseTender.getIfOpen() == Constant.YES) { // 开放时进另外的方法
            if (null != attaches) {
                attaches = URLDecoder.decode(attaches, "UTF-8");
                List<Attach> attachList = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                return tenderService.updateSavedOpen(purchaseTender, attachList);
            }
            return tenderService.updateSavedOpen(purchaseTender);
        } else {
            if (null != enInfos) {
                enInfos = URLDecoder.decode(enInfos, "UTF-8");
                List<TenderContactInfo> contactInfos = FlexJsonUtils.fromJsonArray(enInfos, TenderContactInfo.class);
                if (null != attaches) {
                    attaches = URLDecoder.decode(attaches, "UTF-8");
                    List<Attach> attachList = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                    return tenderService.updateSaved(purchaseTender, contactInfos, attachList);
                } else {
                    return tenderService.updateSaved(purchaseTender, contactInfos);
                }
            } else {
                if (null != attaches) {
                    attaches = URLDecoder.decode(attaches, "UTF-8");
                    List<Attach> attachList = FlexJsonUtils.fromJsonArray(attaches, Attach.class);
                    return tenderService.updateSaved(purchaseTender, null, attachList);
                } else {
                    return tenderService.updateSaved(purchaseTender, null);
                }
            }
        }
    }

    /**
     * 删除对应产品明细
     *
     * @param tenderProdId 招标产品明细id
     */
    @RequestMapping(value = "/deleteProd", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap deleteProd(Long tenderProdId) {
        return tenderService.deleteProd(tenderProdId);
    }

    /**
     * 删除对应供应商投标单
     *
     * @param id     招标单id
     * @param vendUU 删除的投标单的供应商UU
     */
    @RequestMapping(value = "/removeSaleTender", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap removeSaleTender(Long id, Long vendUU) {
        return tenderService.removeSaleTender(id, vendUU);
    }

    /**
     * 删除单个附件
     *
     * @param attachId 附件id
     */
    @RequestMapping(value = "/removeAttach", method = RequestMethod.POST)
    public ModelMap deleteAttach(Long attachId) {
        return tenderService.deleteAttach(attachId);
    }

    /**
     * 招标单审批状态修改（定标审核）
     *
     * @param id 招标单id
     */
    @RequestMapping(value = "/audit/purc", method = RequestMethod.POST)
    public ModelMap auditPurchaseTender(Long id,  Short auditStatus) {return tenderService.auditPurchaseTender(id, auditStatus);
    }

    /**
     * 投标单审批状态修改（投标审核）
     *
     * @param id 投标单id
     */
    @RequestMapping(value = "/audit/sale", method = RequestMethod.POST)
    public ModelMap auditSaleTender(Long id, Short auditStatus) {
        return tenderService.auditSaleTender(id, auditStatus);
    }

    /**
     * 获取投标单详情
     *
     * @param id 投标单id
     */
    @RequestMapping(value = "/saleTender", method = RequestMethod.GET)
    public ModelMap getSaleTenderDetail(Long id) {
        return tenderService.getSaleTenderDetail(id);
    }

    /**
     * UAS审批招标单
     */
    @RequestMapping(value = "/auditTender", method = RequestMethod.POST)
    public ModelMap aduitTender(Long id) {
        return tenderService.publishTender(id);
    }

    /**
     * 提前开标
     */
    @RequestMapping(value = "/decide/inAdvance", method = RequestMethod.POST)
    public ModelMap decideInAdvance(Long id, Long date) {
        return tenderService.decideInAdvance(id, date);
    }

    /**
     * 获取招标单供应商列表
     */
    @RequestMapping(value = "/thisVendors", method = RequestMethod.GET)
    public ModelMap getThisVendors (Long id) {
        return tenderService.getSaleTenderVendors(id);
    }


    /**
     * 短信通知接口
     */
    @RequestMapping(value = "/message/mobile", method = RequestMethod.POST)
    public ModelMap sendMobileMessage (Long id) {
        return tenderService.sendMobileMessage(id);
    }

    /**
     * 全包类型评标
     */
    @RequestMapping(value = "/decide/all", method = RequestMethod.POST)
    public ModelMap decideTenderAll (String data) throws UnsupportedEncodingException {
        data = URLDecoder.decode(data, "UTF-8");
        List<DecideTender> decideTenders = FlexJsonUtils.fromJsonArray(data, DecideTender.class);
        return tenderService.decideTenderAll(decideTenders);
    }


    /**
     * 获取提问单列表
     */
    @RequestMapping(value = "/question/list", method = RequestMethod.GET)
    public List<PurchaseTenderQuestion> getQuestionList(Long uu) {
        return tenderService.getQuestionList(uu);
    }

    /**
     * 获取单个提问单详情
     */
    @RequestMapping(value = "/question/detail", method = RequestMethod.GET)
    public SaleTenderQuestion getQuestionDetail(Long id) {
        return tenderService.getQuestionDetail(id);
    }

    /**
     * 获取当前招标单的全部提问单
     */
    @RequestMapping(value = "/question/this", method = RequestMethod.GET)
    public PurchaseTenderAnswer getThisQuestionAll(Long tenderId) {
        return tenderService.getThisQuestionAll(tenderId);
    }

    /**
     * 保存答疑结果
     */
    @RequestMapping(value = "/question/answer/save", method = RequestMethod.POST)
    public ModelMap saveQuestionAnswer(String data) throws UnsupportedEncodingException {
        data = URLDecoder.decode(data, "UTF-8");
        PurchaseTenderAnswer answer = FlexJsonUtils.fromJson(data, PurchaseTenderAnswer.class);
        return tenderService.saveQuestionAnswer(answer);
    }

    /**
     * 作为投标方，查看自己发出的提问单（全部）
     *
     * @param params 分页参数
     * @return Spage
     */
    @RequestMapping(value = "/question", method = RequestMethod.GET)
    @ResponseBody
    public SPage<SaleTenderQuestion> getAllTenderQuestions(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 判断当前用户是否被客户分配
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("stq_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("stq_ptaid", SystemSession.getUser().getEnterprise().getUu());
        return searchService.searchSaleTenderQuestion(keyword, pageParams);
    }

    /**
     * 作为投标方，查看自己发出的提问单（已回复）
     *
     * @param params 分页参数
     * @return Spage
     */
    @RequestMapping(value = "/question",params = RequestState.DONE, method = RequestMethod.GET)
    @ResponseBody
    public SPage<SaleTenderQuestion> getDoneTenderQuestions(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 判断当前用户是否被客户分配
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("stq_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("stq_ptaid", SystemSession.getUser().getEnterprise().getUu());
        pageParams.getFilters().put("stq_status", Status.REPLIED.value());
        return searchService.searchSaleTenderQuestion(keyword, pageParams);
    }

    /**
     * 作为投标方，查看自己发出的提问单（未回复）
     *
     * @param params 分页参数
     * @return Spage
     */
    @RequestMapping(value = "/question",params = RequestState.TODO, method = RequestMethod.GET)
    @ResponseBody
    public SPage<SaleTenderQuestion> getTodoTenderQuestions(PageParams params, String searchFilter) {
        JSONObject jsonObject = JSONObject.parseObject(searchFilter);
        String keyword = jsonObject.getString("keyword");
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, searchFilter);
        // 判断当前用户是否被客户分配
        SearchFilter filter = userService.distribute();
        if (filter != null && filter.getDistribute() == null) {
            return null;
        }
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("stq_id", false, Sort.Type.LONG, 1L));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        pageParams.getFilters().put("stq_ptaid", SystemSession.getUser().getEnterprise().getUu());
        pageParams.getFilters().put("stq_status", Status.NOT_REPLY.value());
        return searchService.searchSaleTenderQuestion(keyword, pageParams);
    }
}
