package com.huiju.estateagents.eContract.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.eContract.entity.TaCompany;
import com.huiju.estateagents.eContract.entity.TaContractBusiness;
import com.huiju.estateagents.eContract.entity.TaContractTemplate;
import com.huiju.estateagents.eContract.service.ITaCompanySealService;
import com.huiju.estateagents.eContract.service.ITaCompanyService;
import com.huiju.estateagents.eContract.service.ITaContractBusinessService;
import com.huiju.estateagents.eContract.service.ITaContractTemplateService;
import com.huiju.estateagents.entity.TaRaise;
import com.huiju.estateagents.mapper.TaRaiseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
    * 合同与业务关系表  前端控制器
    * </p>
 *
 * @author fxf
 * @since 2020-03-26
 */
@RestController
@RequestMapping("/api")
public class TaContractBusinessController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaContractBusinessController.class);

    @Autowired
    public ITaContractBusinessService iTaContractBusinessService;

    @Autowired
    private ITaContractTemplateService iTaContractTemplateService;

    @Autowired
    private TaRaiseMapper taRaiseMapper;

    @Autowired
    private ITaCompanyService iTaCompanyService;

    @Autowired
    private ITaCompanySealService iTaCompanySealService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taContractBusiness",method= RequestMethod.GET)
    public ResponseBean taContractBusinessList(@RequestParam(value ="contractName", required = false) String contractName,
                                               @RequestParam(value ="targetType", required = false) String targetType,
                                               @RequestParam(value ="targetName", required = false) String targetName,
                                               @RequestParam(value ="companyName", required = false) String companyName,
                                               @RequestParam(value ="status", required = false) Integer status,
                                               @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                               @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                               HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            Integer orgId = getOrgId(request);
            IPage<TaContractBusiness> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaContractBusiness> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", orgId);
            queryWrapper.like(!StringUtils.isEmpty(contractName), "contract_template_name", contractName);
            queryWrapper.eq(!StringUtils.isEmpty(targetType), "target_type", targetType);
            queryWrapper.like(!StringUtils.isEmpty(targetName), "target_name", targetName);
            queryWrapper.like(!StringUtils.isEmpty(companyName), "company_name", companyName);
            queryWrapper.eq(status != null, "status", status);
            queryWrapper.ne("status", CommConstant.STATUS_DELETE);
            queryWrapper.orderByDesc("create_date");
            IPage<TaContractBusiness> result = iTaContractBusinessService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taContractBusinessList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taContractBusiness 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taContractBusiness",method= RequestMethod.POST)
    public ResponseBean taContractBusinessAdd(@RequestBody TaContractBusiness taContractBusiness, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaContractTemplate taContractTemplate = iTaContractTemplateService.getById(taContractBusiness.getContractTemplateId());
            taContractBusiness.setContractTemplateName(taContractTemplate.getContractTemplateName());
            Integer targetId = taContractBusiness.getTargetId();
            QueryWrapper<TaContractBusiness> taContractBusinessQueryWrapper = new QueryWrapper<>();
            taContractBusinessQueryWrapper.eq("org_id", getOrgId(request));
            taContractBusinessQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            taContractBusinessQueryWrapper.eq("target_id", targetId);
            Integer contractBusinessNum = iTaContractBusinessService.count(taContractBusinessQueryWrapper);
            if (contractBusinessNum > 0 && CommConstant.STATUS_NORMAL.equals(taContractBusiness.getStatus())){
                responseBean.addError("所选业务已有发布的业务配置，无法再新增已发布的业务配置");
                return responseBean;
            }

            taContractBusiness.setOrgId(getOrgId(request));
            taContractBusiness.setCreateDate(LocalDateTime.now());
            taContractBusiness.setUpdateDate(LocalDateTime.now());
            if (iTaContractBusinessService.save(taContractBusiness)){
                responseBean.addSuccess(taContractBusiness);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taContractBusinessAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/taContractBusiness/{id}", method= RequestMethod.PUT)
    public ResponseBean taContractBusinessDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaContractBusinessService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taContractBusinessDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id批量删除对象
     */
    @ResponseBody
    @RequestMapping(value="/admin/batchDelBusinessConfig", method= RequestMethod.PUT)
    public ResponseBean batchDelBusinessConfig(@RequestBody TaContractBusiness contractBusinesses, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        for (TaContractBusiness taContractBusiness : contractBusinesses.getContractBusinessList()){
            taContractBusiness.setStatus(CommConstant.STATUS_DELETE);
        }
        try{
            iTaContractBusinessService.updateBatchById(contractBusinesses.getContractBusinessList());
            responseBean.addSuccess("success");
        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError("fail");
        }

        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taContractBusiness 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taContractBusiness/{id}",method= RequestMethod.PUT)
    public ResponseBean taContractBusinessUpdate(@PathVariable Integer id,
                                        @RequestBody TaContractBusiness taContractBusiness, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaContractTemplate taContractTemplate = iTaContractTemplateService.getById(taContractBusiness.getContractTemplateId());
            TaRaise taRaise = taRaiseMapper.getRaiseById(taContractBusiness.getTargetId(), getOrgId(request));
            TaCompany taCompany = iTaCompanyService.getById(taContractBusiness.getCompanyId());

            Integer targetId = taContractBusiness.getTargetId();
            QueryWrapper<TaContractBusiness> taContractBusinessQueryWrapper = new QueryWrapper<>();
            taContractBusinessQueryWrapper.eq("org_id", getOrgId(request));
            taContractBusinessQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            taContractBusinessQueryWrapper.eq("target_id", targetId);
            taContractBusinessQueryWrapper.ne("contract_business_id", id);


            Integer contractBusinessNum = iTaContractBusinessService.count(taContractBusinessQueryWrapper);
            if (contractBusinessNum > 0 && CommConstant.STATUS_NORMAL.equals(taContractBusiness.getStatus())){
                responseBean.addError("所选业务已有发布的业务配置，无法再新增已发布的业务配置");
                return responseBean;
            }

            taContractBusiness.setContractBusinessId(id);
            taContractBusiness.setContractTemplateName(taContractTemplate.getContractTemplateName());
            taContractBusiness.setTargetName(taRaise.getSalesBatchName());
            taContractBusiness.setCompanyName(taCompany.getCompanyName());
            taContractBusiness.setUpdateDate(LocalDateTime.now());
            if (iTaContractBusinessService.updateById(taContractBusiness)){
                responseBean.addSuccess(taContractBusiness);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taContractBusinessUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/admin/taContractBusiness/{id}",method= RequestMethod.GET)
    public ResponseBean taContractBusinessGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaContractBusinessService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taContractBusinessDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
