package com.jeeplus.modules.biddingManagement.web;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.biddingManagement.entity.BiddingManagementInfo;
import com.jeeplus.modules.biddingManagement.service.BiddingManagementService;
import com.jeeplus.modules.projectAssess.entity.ProjectAssessInfo;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;

/**
 * 投标管理Controller
 * @author 徐滕
 * @version 2020-05-12
 */
@Controller
@RequestMapping(value = "${adminPath}/management/biddingManagement")
public class BiddingManagementController extends BaseController {

    @Autowired
    private BiddingManagementService biddingManagementService;
    @Autowired
    protected ProjectRecordsService projectRecordsService;

    @ModelAttribute
    public BiddingManagementInfo get(@RequestParam(required=false) String id) {
        BiddingManagementInfo entity = null;
        if (StringUtils.isNotBlank(id)){
            entity = biddingManagementService.get(id);
        }
        if (entity == null){
            entity = new BiddingManagementInfo();
        }
        return entity;
    }

    /**
     * 查询项目评估信息
     * @param biddingManagementInfo
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("management:biddingManagement:list")
    @RequestMapping(value = {"list", ""})
    public String list(BiddingManagementInfo biddingManagementInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        if(UserUtils.isManager()){
            model.addAttribute("flag","1");
        }
        Page<BiddingManagementInfo> page = biddingManagementService.findPage(new Page<BiddingManagementInfo>(request, response), biddingManagementInfo);
        model.addAttribute("page", page);
        model.addAttribute("projectName",biddingManagementInfo.getProjectName());
        model.addAttribute("tenderStatus",biddingManagementInfo.getTenderStatus());
        model.addAttribute("beginDate",biddingManagementInfo.getBeginDate());
        model.addAttribute("endDate",biddingManagementInfo.getEndDate());
        return "modules/biddingManagement/biddingManagementList";
    }

    /**
     * 查看，增加，编辑开票管理表单页面
     */
    @RequiresPermissions(value={"management:biddingManagement:add","management:biddingManagement:edit"},logical= Logical.OR)
    @RequestMapping(value = "form")
    public String form(BiddingManagementInfo biddingManagementInfo, Model model) {
        if (biddingManagementInfo != null && StringUtils.isNotBlank(biddingManagementInfo.getId())) {
            biddingManagementInfo = biddingManagementService.get(biddingManagementInfo.getId());
            biddingManagementService.queryWorkAttachment(biddingManagementInfo);
        }else {
            biddingManagementInfo.setCreateBy(UserUtils.getUser());
            biddingManagementInfo.setCreateDate(new Date());
        }
        model.addAttribute("biddingManagement", biddingManagementInfo);
        return "modules/biddingManagement/biddingManagementForm";
    }

    /**
     * 查看，增加，编辑开票管理表单页面
     */
    @RequiresPermissions(value={"management:biddingManagement:view"},logical= Logical.OR)
    @RequestMapping(value = "view")
    public String view(BiddingManagementInfo biddingManagementInfo, Model model) {
        if (biddingManagementInfo != null && StringUtils.isNotBlank(biddingManagementInfo.getId())) {
            biddingManagementInfo = biddingManagementService.get(biddingManagementInfo.getId());
            biddingManagementService.queryWorkAttachment(biddingManagementInfo);
        }else {
            biddingManagementInfo.setCreateBy(UserUtils.getUser());
            biddingManagementInfo.setCreateDate(new Date());
        }
        model.addAttribute("biddingManagement", biddingManagementInfo);
        return "modules/biddingManagement/biddingManagementView";
    }



    /**
     * 选择开票项目
     */
    @RequestMapping(value = "selectProject")
    public String selectproject(ProjectRecords project, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String ids, HttpServletRequest request, HttpServletResponse response, Model model) {
        project.setCompany(UserUtils.getSelectCompany());
        project.setProjectStatus(ProjectStatusEnum.SIGNED.getValue());//已签状态
        project.setLeaderNameStr(UserUtils.getUser().getName());
        Page<ProjectRecords> page = projectRecordsService.findPageByBiddingManagement(new Page<ProjectRecords>(request, response), project);
        try {
            fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
            fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
            searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
            searchKey = URLDecoder.decode(searchKey, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        model.addAttribute("labelNames", fieldLabels.split("\\|"));
        model.addAttribute("labelValues", fieldKeys.split("\\|"));
        model.addAttribute("fieldLabels", fieldLabels);
        model.addAttribute("fieldKeys", fieldKeys);
        model.addAttribute("url", url);
        model.addAttribute("searchLabel", searchLabel);
        model.addAttribute("searchKey", searchKey);
        model.addAttribute("obj", project);
        model.addAttribute("page",page);
        return "modules/sys/gridinvoiceproject";
    }

    /**
     * 保存项目
     */
    @RequiresPermissions(value={"management:biddingManagement:add","management:biddingManagement:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String tStore(BiddingManagementInfo biddingManagementInfo, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, biddingManagementInfo)){
            return form(biddingManagementInfo, model);
        }
        if (StringUtils.isNotBlank(biddingManagementInfo.getProjectId())){
            biddingManagementInfo.setProjectName(projectRecordsService.get(biddingManagementInfo.getProjectId()).getProjectName());
        }
        try {
            if (!biddingManagementInfo.getIsNewRecord()) {//编辑表单保存
                BiddingManagementInfo t = biddingManagementService.get(biddingManagementInfo.getId());//从数据库取出记录的值
                MyBeanUtils.copyBeanNotNull2Bean(biddingManagementInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
                biddingManagementService.saveBiddingManagementInfo(t);//保存
            } else {//新增表单保存
                biddingManagementService.saveBiddingManagementInfo(biddingManagementInfo);//保存
            }
            addMessage(redirectAttributes, "保存投标信息成功");
        }catch (Exception e){
            logger.error("保存投标信息异常：",e);
            addMessage(redirectAttributes, "保存投标信息异常:"+e.getMessage());
        }
        return "redirect:"+ Global.getAdminPath()+"/management/biddingManagement/?repage";
    }

    /**
     * 删除项目
     */
    @RequiresPermissions("management:biddingManagement:del")
    @RequestMapping(value = "delete")
    public String delete(BiddingManagementInfo biddingManagementInfo, RedirectAttributes redirectAttributes) {
        biddingManagementService.delete(biddingManagementInfo);
        addMessage(redirectAttributes, "删除项目评估成功");
        return "redirect:"+Global.getAdminPath()+"/management/biddingManagement/?repage";
    }

}
