package com.huiju.estateagents.controller;

import com.alibaba.fastjson.JSONObject;
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.entity.TaPersonBuilding;
import com.huiju.estateagents.entity.TaPreselection;
import com.huiju.estateagents.entity.TaSalesBatch;
import com.huiju.estateagents.service.ITaPreselectionService;
import com.huiju.estateagents.service.impl.TaSalesBatchServiceImpl;
import org.apache.commons.lang3.StringUtils;
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;
import java.util.List;

/**
 * <p>
 * 预选表  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-02-26
 */
@RestController
@RequestMapping("/api")
public class TaPreselectionController extends BaseController {

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

    @Autowired
    public ITaPreselectionService iTaPreselectionService;

    @Autowired
    private TaSalesBatchServiceImpl taSalesBatchService;

    /**
     * 条件查询预选列表
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param salesBatchName
     * @param status
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/listPresecretByCondition", method = RequestMethod.GET)
    public ResponseBean listPresecretByCondition(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                 String buildingId, String salesBatchName, Integer status,
                                                 HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();

        try {
            Integer orgId = getOrgId(request);
            List<TaPersonBuilding> personBuildingList = getTaPersonBuildingListByUserId(request);

            responseBean = iTaPreselectionService.listPresecretByCondition(pageSize, pageNum, salesBatchName, buildingId, orgId, status, personBuildingList);
            logger.info("listSalesBatchForPreselect 返回结果：{}", JSONObject.toJSONString(responseBean));
        } catch (Exception e) {
            logger.error("listSalesBatchForPreselect -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/taPreselection", method = RequestMethod.GET)
    public ResponseBean taPreselectionList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaPreselection> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaPreselection> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date");

            IPage<TaPreselection> result = iTaPreselectionService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPreselectionList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     *
     * @param taPreselection 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taPreselection", method = RequestMethod.POST)
    public ResponseBean taPreselectionAdd(@RequestBody TaPreselection taPreselection, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (taPreselection.getSalesBatchId() == null) {
                responseBean.addError("销售批次为空");
                return responseBean;
            }

            Integer orgId = getOrgId(request);
            // 校验是否预选过
            QueryWrapper<TaPreselection> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", orgId);
            queryWrapper.eq("sales_batch_id", taPreselection.getSalesBatchId());
            queryWrapper.eq("status", 1);
            TaPreselection record = iTaPreselectionService.getOne(queryWrapper);
            if (record != null) {
                responseBean.addError("销售批次已新增过预选");
                return responseBean;
            }

            // 更新批次表信息
            TaSalesBatch taSalesBatch = new TaSalesBatch();
            taSalesBatch.setSalesBatchId(taPreselection.getSalesBatchId());
            taSalesBatch.setPreselectionStartTime(taPreselection.getPreselectionStartTime());
            taSalesBatch.setPreselectionEndTime(taPreselection.getPreselectionEndTime());
            Boolean updateResult = taSalesBatchService.updateById(taSalesBatch);
            if (!updateResult) {
                responseBean.addError("fail");
                return responseBean;
            }

            // 新增数据
            taPreselection.setOrgId(getOrgId(request));
            taPreselection.setStatus(CommConstant.IS_PUBLISH);
            taPreselection.setCreateDate(LocalDateTime.now());
            if (iTaPreselectionService.save(taPreselection)) {
                responseBean.addSuccess(taPreselection);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPreselectionAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 批量删除
     *
     * @param taPreselectionList
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/admin/preselection/batchDelete", method = RequestMethod.PUT)
    public ResponseBean batchDelete(@RequestBody List<TaPreselection> taPreselectionList, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            Integer orgId = getOrgId(request);
            responseBean = iTaPreselectionService.batchDelete(taPreselectionList, orgId);
            logger.info("TaPreselectionController.batchDelete 返回：{}", JSONObject.toJSONString(responseBean));

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPreselectionDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 删除
     *
     * @param id 实体ID
     */
    @ResponseBody
    @RequestMapping(value = "/admin/taPreselection/{id}", method = RequestMethod.DELETE)
    public ResponseBean taPreselectionDelete(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaPreselectionService.removeById(id)) {
                responseBean.addSuccess("success");
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPreselectionDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     *
     * @param id             实体ID
     * @param taPreselection 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taPreselection/{id}", method = RequestMethod.PUT)
    public ResponseBean taPreselectionUpdate(@PathVariable Integer id,
                                             @RequestBody TaPreselection taPreselection) {
        ResponseBean responseBean = new ResponseBean();
        try {

            if (taPreselection.getSalesBatchId() == null) {
                responseBean.addError("销售批次为空");
                return responseBean;
            }

            if (taPreselection.getPreselectionStartTime() != null && taPreselection.getPreselectionEndTime() != null) {
                // 更新批次表信息
                TaSalesBatch taSalesBatch = new TaSalesBatch();
                taSalesBatch.setSalesBatchId(taPreselection.getSalesBatchId());
                taSalesBatch.setPreselectionStartTime(taPreselection.getPreselectionStartTime());
                taSalesBatch.setPreselectionEndTime(taPreselection.getPreselectionEndTime());
                Boolean updateResult = taSalesBatchService.updateById(taSalesBatch);
                if (!updateResult) {
                    responseBean.addError("fail");
                    return responseBean;
                }
            }

            taPreselection.setPreselectionId(id);
            if (iTaPreselectionService.updateById(taPreselection)) {
                responseBean.addSuccess(taPreselection);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPreselectionUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/admin/taPreselection/{id}", method = RequestMethod.GET)
    public ResponseBean taPreselectionGet(@PathVariable Integer id, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaPreselectionService.getPresecretById(id, getOrgId(request));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPreselectionDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 校验批次下是否有预选
     *
     * @param salesBatchId
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/checkHavingRecord/{salesBatchId}", method = RequestMethod.GET)
    public ResponseBean checkHavingRecordForSalesBatch(@PathVariable("salesBatchId") Integer salesBatchId, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaPreselectionService.checkHavingRecordForSalesBatch(salesBatchId, getOrgId(request));
            logger.info("checkHavingRecordForSalesBatch 返回结果：{}", JSONObject.toJSONString(responseBean));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("checkHavingRecordForSalesBatch -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
