package com.yunzhi.marketing.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.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.entity.TaPersonBuilding;
import com.yunzhi.marketing.entity.TaRaise;
import com.yunzhi.marketing.entity.TaSalesBatch;
import com.yunzhi.marketing.service.ITaRaiseService;
import com.yunzhi.marketing.service.ITaSalesBatchService;
import com.yunzhi.marketing.service.ITdCityService;
import com.yunzhi.marketing.service.impl.TaRaiseInviteServiceImpl;
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 TaRaiseController extends BaseController {

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

    @Autowired
    public ITaRaiseService iTaRaiseService;

    @Autowired
    public ITdCityService iTdCityService;

    @Autowired
    public ITaSalesBatchService iTaSalesBatchService;

    @Autowired
    private TaRaiseInviteServiceImpl iTaRaiseInviteService;

    /**
     * 获取认筹列表
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param salesBatchName
     * @param status
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/listRaiseByCondition", method = RequestMethod.GET)
    public ResponseBean listRaiseByCondition(@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 = iTaRaiseService.listRaiseByCondition(pageSize, pageNum, salesBatchName, buildingId, orgId, status, personBuildingList);
            logger.info("listRaiseByCondition 返回结果：{}", JSONObject.toJSONString(responseBean));
        } catch (Exception e) {
            logger.error("listRaiseByCondition -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


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

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

    /**
     * 保存对象
     *
     * @param taRaise 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taRaise", method = RequestMethod.POST)
    public ResponseBean taRaiseAdd(@RequestBody TaRaise taRaise, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            // 参数校验
            Integer raisePrice = taRaise.getRaisePrice();
            if (raisePrice != null && (raisePrice > CommConstant.MAX_RAISE_PRICE || raisePrice < 0)) {
                responseBean.addError("认筹金额范围为0到50000元");
                return responseBean;
            }

            Integer orgId = getOrgId(request);

            // 校验批次是否已经认筹过
            QueryWrapper<TaRaise> taRaiseQueryWrapper = new QueryWrapper<>();
            taRaiseQueryWrapper.eq("org_Id", orgId);
            taRaiseQueryWrapper.eq("sales_batch_id", taRaise.getSalesBatchId());
            taRaiseQueryWrapper.eq("status", 1);
            TaRaise tr = iTaRaiseService.getOne(taRaiseQueryWrapper);
            if (tr != null) {
                responseBean.addError("该销售批次已添加过认筹");
                return responseBean;
            }

            // 获取销售批次状态
            TaSalesBatch taSalesBatch = new TaSalesBatch();
            if (taRaise.getSalesBatchId() != null) {
                QueryWrapper<TaSalesBatch> taSalesBatchQueryWrapper = new QueryWrapper<>();
                taSalesBatchQueryWrapper.eq("sales_batch_id", taRaise.getSalesBatchId());
                taSalesBatch = iTaSalesBatchService.getOne(taSalesBatchQueryWrapper);
            }

            taRaise.setOrgId(orgId);
            taRaise.setRaisePrice(taRaise.getRaisePrice() != null ? taRaise.getRaisePrice() : null);
            taRaise.setStatus(taSalesBatch.getStatus());
            taRaise.setCreateDate(LocalDateTime.now());
            if (iTaRaiseService.save(taRaise)) {
                // 为邀请制，添加认筹被邀请清单
                if (CommConstant.STATUS_NORMAL == taRaise.getInvite()) {
                    iTaRaiseService.saveOrUpdateInvite(taRaise, getOrgId(request), true);
                }
                responseBean.addSuccess(taRaise);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            logger.error("taRaiseAdd -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 批量删除
     *
     * @param taRaiseList
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/admin/raise/batchDelete", method = RequestMethod.DELETE)
    public ResponseBean batchDelete(@RequestBody List<TaRaise> taRaiseList, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            Integer orgId = getOrgId(request);
            responseBean = iTaRaiseService.batchDelete(taRaiseList, orgId);

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

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

    /**
     * 修改对象
     *
     * @param id      实体ID
     * @param taRaise 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taRaise/{id}", method = RequestMethod.PUT)
    public ResponseBean taRaiseUpdate(@PathVariable Integer id,
                                      @RequestBody TaRaise taRaise,
                                      HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            Integer raisePrice = taRaise.getRaisePrice();
            if (raisePrice != null && (raisePrice > CommConstant.MAX_RAISE_PRICE || raisePrice < 0)) {
                responseBean.addError("认筹金额范围为0到50000元");
                return responseBean;
            }

            taRaise.setRaiseId(id);
            taRaise.setRaisePrice(taRaise.getRaisePrice() != null ? taRaise.getRaisePrice() : null);
            if (iTaRaiseService.updateById(taRaise)) {
                // 为邀请制，添加认筹被邀请清单
                if (CommConstant.STATUS_NORMAL == taRaise.getInvite()) {
                    iTaRaiseService.saveOrUpdateInvite(taRaise, getOrgId(request), false);
                }
                responseBean.addSuccess(taRaise);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taRaiseUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    @GetMapping("/wx/taRaise")
    public ResponseBean getRaiseProfile(@RequestParam(required = false) Integer salesBatchId,
                                        @RequestParam(required = false) Integer raiseId,
                                        @RequestParam(required = false) Integer raiseRecordId,
                                        HttpServletRequest request) {
        TaRaise taRaise = iTaRaiseService.getRaiseProfile(raiseId, raiseRecordId, salesBatchId);
        return ResponseBean.success(taRaise);
    }

}
