package com.huiju.estateagents.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.entity.*;
import com.huiju.estateagents.service.*;
import com.huiju.estateagents.service.impl.TaPreselectionServiceImpl;
import com.huiju.estateagents.service.impl.TaRaiseServiceImpl;
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.ArrayList;
import java.util.List;

/**
 * <p>
 * 销售批次表  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-02-10
 */
@RestController
@RequestMapping("/api")
public class TaSalesBatchController extends BaseController {

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

    @Autowired
    public ITaSalesBatchService iTaSalesBatchService;

    @Autowired
    public ITaMiniappService taMiniappService;

    @Autowired
    public IMiniAppService miniAppService;

    @Autowired
    private TaShareContentService taShareContentService;

    @Autowired
    public IExtendContentService iExtendContentService;

    @Autowired
    public TaRaiseServiceImpl taRaiseService;

    @Autowired
    private TaPreselectionServiceImpl taPreselectionService;

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/admin/taSalesBatch", method = RequestMethod.GET)
    public ResponseBean taSalesBatchList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                         @RequestParam(value = "salesBatchName", required = false) String salesBatchName,
                                         @RequestParam(value = "buildingId", required = false) String buildingId,
                                         @RequestParam(value = "status", required = false) Integer status, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaSalesBatch> pg = new Page<>(pageNum, pageSize);

            IPage<TaSalesBatch> result = iTaSalesBatchService.selectByCondition(pg, salesBatchName, buildingId, status, getOrgId(request), getTaPersonBuildingListByUserId(request));
            responseBean.addSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taSalesBatchList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     *
     * @param taSalesBatch 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taSalesBatch", method = RequestMethod.POST)
    public ResponseBean taSalesBatchAdd(@RequestBody TaSalesBatch taSalesBatch, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            Integer orgId = getOrgId(request);

            taSalesBatch.setOrgId(orgId);
            taSalesBatch.setCreateDate(LocalDateTime.now());
            taSalesBatch.setUpdateTime(LocalDateTime.now());
            iTaSalesBatchService.save(taSalesBatch);

            QueryWrapper<TaMiniapp> taMiniappQuery = new QueryWrapper<>();
            taMiniappQuery.eq("org_id", orgId);
            TaMiniapp taMiniapp = taMiniappService.getOne(taMiniappQuery);
            // 生成二维码
            ResponseBean taMiniappQrcode = miniAppService.getQrCode(CommConstant.HOUSE_QRCODE.replace("#0", taSalesBatch.getSalesBatchId().toString()).replace("#1", "house"), taMiniapp.getMiniappId());
            taSalesBatch.setQrCode(String.valueOf(taMiniappQrcode.getData()));
            iTaSalesBatchService.updateById(taSalesBatch);

            // 设置默认分享设置
            TaShareContent shareContent = new TaShareContent();
            shareContent.setOrgId(orgId);
            shareContent.setTargetId(taSalesBatch.getSalesBatchId().toString());
            shareContent.setShareContentTitle("诚挚邀您在线选房购房~");
            shareContent.setShareContentImg(taSalesBatch.getAerialViewImg());
            shareContent.setShareContentType(CommConstant.HOUSE);
            shareContent.setStatus(CommConstant.STATUS_NORMAL);
            shareContent.setCreateDate(LocalDateTime.now());
            taShareContentService.save(shareContent);

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

    /**
     * 删除批次
     *
     * @param salesBatchs
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/taSalesBatch", method = RequestMethod.PUT)
    public ResponseBean taSalesBatchDel(@RequestBody List<TaSalesBatch> salesBatchs, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {

            Integer orgId = getOrgId(request);

            for (TaSalesBatch ts : salesBatchs) {

                // 校验批次下是否有预选记录
                QueryWrapper<TaPreselection> preselectionQueryWrapper = new QueryWrapper<>();
                preselectionQueryWrapper.eq("org_id", orgId);
                preselectionQueryWrapper.eq("sales_batch_id", ts.getSalesBatchId());
                preselectionQueryWrapper.eq("status", 1);
                TaPreselection preselection = taPreselectionService.getOne(preselectionQueryWrapper);
                if (preselection != null) {
                    responseBean.addError(String.format("销售批次%s关联有预选,请先删除关联的预选模块", ts.getSalesBatchName()));
                    return responseBean;
                }

                // 校验批次下是否有认筹
                QueryWrapper<TaRaise> raiseQueryWrapper = new QueryWrapper<>();
                raiseQueryWrapper.eq("org_id", orgId);
                raiseQueryWrapper.eq("sales_batch_id", ts.getSalesBatchId());
                raiseQueryWrapper.eq("status", 1);
                TaRaise raise = taRaiseService.getOne(raiseQueryWrapper);
                if (raise != null) {
                    responseBean.addError(String.format("销售批次%s关联有认筹,请先删除关联的认筹模块", ts.getSalesBatchName()));
                    return responseBean;
                }
            }

            List<Integer> liveActivityIds = new ArrayList<>();
            for (TaSalesBatch taSalesBatch : salesBatchs) {
                liveActivityIds.add(taSalesBatch.getSalesBatchId());
            }
            QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", getOrgId(request));
            queryWrapper.eq("content_type", CommConstant.SALES_BATCH);
            queryWrapper.in("target_id", liveActivityIds);
            List<ExtendContent> list = iExtendContentService.list(queryWrapper);
            list.forEach(e -> {
                e.setStatus(CommConstant.NOT_PUBLISH);
            });
            if (list.size() > 0) {
                iExtendContentService.updateBatchById(list);
            }

            responseBean = iTaSalesBatchService.delSalesBatchList(getOrgId(request), salesBatchs);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taSalesBatchAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

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

            if (taSalesBatch.getStatus() != null && taSalesBatch.getStatus() != 1) {
                // 校验批次下是否有预选记录
                QueryWrapper<TaPreselection> preselectionQueryWrapper = new QueryWrapper<>();
                preselectionQueryWrapper.eq("org_id", getOrgId(request));
                preselectionQueryWrapper.eq("sales_batch_id", taSalesBatch.getSalesBatchId());
                preselectionQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
                TaPreselection preselection = taPreselectionService.getOne(preselectionQueryWrapper);
                if (preselection != null) {
//                    responseBean.addError(String.format("销售批次%s关联有预选,请先删除关联的预选模块", taSalesBatch.getSalesBatchName()));
//                    return responseBean;
                    preselection.setStatus(CommConstant.STATUS_UNACCALIMED);
                    taPreselectionService.updateById(preselection);
                }

                // 校验批次下是否有认筹
                QueryWrapper<TaRaise> raiseQueryWrapper = new QueryWrapper<>();
                raiseQueryWrapper.eq("org_id", getOrgId(request));
                raiseQueryWrapper.eq("sales_batch_id", taSalesBatch.getSalesBatchId());
                raiseQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
                TaRaise raise = taRaiseService.getOne(raiseQueryWrapper);
                if (raise != null) {
//                    responseBean.addError(String.format("销售批次%s关联有认筹,请先删除关联的认筹模块", taSalesBatch.getSalesBatchName()));
//                    return responseBean;
                    raise.setStatus(CommConstant.STATUS_UNACCALIMED);
                    taRaiseService.updateById(raise);
                }
            }

            QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", getOrgId(request));
            queryWrapper.eq("content_type", CommConstant.SALES_BATCH);
            queryWrapper.eq("target_id", taSalesBatch.getSalesBatchId());
            List<ExtendContent> list = iExtendContentService.list(queryWrapper);
            if (CommConstant.NOT_PUBLISH.equals(taSalesBatch.getStatus())) {
                list.forEach(e -> {
                    e.setStatus(CommConstant.NOT_PUBLISH);
                });
            }
            if (list.size() > 0) {
                iExtendContentService.updateBatchById(list);
            }

            QueryWrapper<TaPreselection> taPreselectionQueryWrapper = new QueryWrapper<>();
            TaPreselection taPreselection = new TaPreselection();
            taPreselection.setStatus(taSalesBatch.getStatus());
            taPreselectionQueryWrapper.eq("org_id", getOrgId(request));
            taPreselectionQueryWrapper.eq("sales_batch_id", taSalesBatch.getSalesBatchId());
            taPreselectionQueryWrapper.ne("status", CommConstant.STATUS_DELETE);
            taPreselectionService.update(taPreselection, taPreselectionQueryWrapper);

            QueryWrapper<TaRaise> taRaiseQueryWrapper = new QueryWrapper<>();
            TaRaise taRaise = new TaRaise();
            taRaise.setStatus(taSalesBatch.getStatus());
            taRaiseQueryWrapper.eq("org_id", getOrgId(request));
            taRaiseQueryWrapper.eq("sales_batch_id", taSalesBatch.getSalesBatchId());
            taRaiseService.update(taRaise, taRaiseQueryWrapper);

            if (iTaSalesBatchService.updateById(taSalesBatch)) {
                responseBean.addSuccess(taSalesBatch);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taSalesBatchUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    /**
     * 根据id提示信息-小程序端
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/wx/getNoticeInfo/{id}", method = RequestMethod.GET)
    public ResponseBean getNoticeInfo(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaSalesBatchService.getNoticeInfo(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getNoticeInfo -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象--小程序
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/wx/taSalesBatch/{id}", method = RequestMethod.GET)
    public ResponseBean taSalesBatchGetForMiniApp(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaSalesBatchService.getSalesBatchById(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taSalesBatchGetForMiniApp -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @RequestMapping(value = "/admin/salesBatchList", method = RequestMethod.GET)
    public ResponseBean salesBatchList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       @RequestParam(value = "salesBatchName", required = false) String salesBatchName,
                                       @RequestParam(value = "buildingId", required = false) String buildingId,
                                       @RequestParam(value = "status", required = false) Integer status, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaSalesBatch> pg = new Page<>(pageNum, pageSize);

            IPage<TaSalesBatch> result = iTaSalesBatchService.selectByCondition(pg, salesBatchName, buildingId, status, getOrgId(request), getTaPersonBuildingListByUserId(request));
            List<TaSalesBatch> taSalesBatches = result.getRecords();
            responseBean.addSuccess(taSalesBatches);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taSalesBatchList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 查询销售批次列表--小程序
     */
    @RequestMapping(value = "/wx/taSalesBatch/choice", method = RequestMethod.GET)
    public ResponseBean taSalesBatchGetForMiniApp(@RequestParam(value = "buildingId", required = false) String buildingId, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            QueryWrapper<TaSalesBatch> taSalesBatchQueryWrapper = new QueryWrapper<>();
            taSalesBatchQueryWrapper.eq("org_id", getOrgId(request));
            taSalesBatchQueryWrapper.eq(!StringUtils.isEmpty(buildingId), "building_id", buildingId);
            taSalesBatchQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            List<TaSalesBatch> list = iTaSalesBatchService.list(taSalesBatchQueryWrapper);
            responseBean.addSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taSalesBatchGetForMiniApp -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据销售批次查询项目信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/taSalesBatch/getBuildingById/{id}", method = RequestMethod.GET)
    public ResponseBean getBuildingById(@PathVariable("id") String id, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaSalesBatchService.getBuildingById(id, getOrgId(request));
        } catch (Exception e) {
            logger.error("taSalesBatchGetForMiniApp -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

}
