package com.huiju.estateagents.drainage.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.DateUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.drainage.entity.TaDrainage;
import com.huiju.estateagents.drainage.service.ITaDrainageRecordService;
import com.huiju.estateagents.drainage.service.ITaDrainageService;
import com.huiju.estateagents.entity.ExtendContent;
import com.huiju.estateagents.entity.TaMiniapp;
import com.huiju.estateagents.entity.TaPersonBuilding;
import com.huiju.estateagents.mapper.TaMiniappMapper;
import com.huiju.estateagents.service.IExtendContentService;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.third.entity.TaThirdPartyMiniappConfig;
import com.huiju.estateagents.third.service.ITaThirdPartyMiniappConfigService;
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;
import java.util.UUID;
import java.util.stream.Collectors;


/**
 * <p>
    * 引流项目  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-10-18
 */
@RestController
@RequestMapping("/api")
public class TaDrainageController extends BaseController {

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

    @Autowired
    public ITaDrainageService iTaDrainageService;
    
    @Autowired
    public ITaThirdPartyMiniappConfigService iTaThirdPartyMiniappConfigService;

    @Autowired
    private ITaDrainageRecordService iTaDrainageRecordService;

    @Autowired
    public IExtendContentService iExtendContentService;

    @Autowired
    private TaMiniappMapper taMiniappMapper;

    @Autowired
    private IMiniAppService miniAppService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taDrainage",method= RequestMethod.GET)
    public ResponseBean taDrainageList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                       @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                       @RequestParam(value ="drainageId",required = false) Integer drainageId,
                                       @RequestParam(value ="name",required = false) String name,
                                       @RequestParam(value ="isMiniapp",required = false) Integer isMiniapp,
                                       @RequestParam(value ="status",required = false) Integer status,
                                       @RequestParam(value ="buildingId",required = false) String buildingId,
                                       HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            List<TaPersonBuilding> taPersonBuildingList = getTaPersonBuildingListByUserId(request);
            //使用分页插件
		    IPage<TaDrainage> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaDrainage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id",getOrgId(request));
            queryWrapper.eq(null != isMiniapp,"is_miniapp",isMiniapp);
            if (null == status){
                queryWrapper.gt("status",-1);
            }
            queryWrapper.eq(null != status,"status",status);
            queryWrapper.eq(!StringUtils.isEmpty(buildingId),"building_id",buildingId);
            queryWrapper.eq(null != drainageId,"drainage_id",drainageId);
            queryWrapper.and(taPersonBuildingList.size() > 0, wapper -> wapper.in("building_id",taPersonBuildingList.stream().map(TaPersonBuilding::getBuildingId).collect(Collectors.toList())).or().eq("create_user",getUserId(request)));
            queryWrapper.like(!StringUtils.isEmpty(name),"name",name);
            queryWrapper.orderByDesc("create_date");

            IPage<TaDrainage> result = iTaDrainageService.page(pg, queryWrapper);
            List<TaDrainage> records = result.getRecords();
            records.forEach(e -> {
                QueryWrapper<TaThirdPartyMiniappConfig> taThirdPartyMiniappConfigQueryWrapper = new QueryWrapper<>();
                taThirdPartyMiniappConfigQueryWrapper.eq("target_type",CommConstant.TARGET_TYPE_H5);
                taThirdPartyMiniappConfigQueryWrapper.eq("target_id",e.getDrainageId());
                taThirdPartyMiniappConfigQueryWrapper.eq("org_id",getOrgId(request));
                TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = iTaThirdPartyMiniappConfigService.getOne(taThirdPartyMiniappConfigQueryWrapper);
                if (null != taThirdPartyMiniappConfig){
                    e.setAppid(taThirdPartyMiniappConfig.getAppid());
                    e.setAppSecret(taThirdPartyMiniappConfig.getAppSecret());
                }
            });
            result.setRecords(records);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taDrainage 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taDrainage/add",method= RequestMethod.POST)
    public ResponseBean taDrainageAdd(@RequestBody TaDrainage taDrainage,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            taDrainage.setOrgId(getOrgId(request));
            taDrainage.setCreateDate(LocalDateTime.now());
            taDrainage.setStatus(CommConstant.STATUS_UNACCALIMED);
            if (DateUtils.dayToLocalDateime(taDrainage.getEndDate()).isAfter(LocalDateTime.now())){
                taDrainage.setStatus(CommConstant.STATUS_NORMAL);
            }
            taDrainage.setCreateUser(getUserId(request));
            if (iTaDrainageService.save(taDrainage)){
                // 根据ORGID查询当前小程序表的miniapp_id
                QueryWrapper<TaMiniapp> taMiniappQuery= new QueryWrapper<>();
                taMiniappQuery.eq("org_id",getOrgId(request));
                TaMiniapp taMiniapp = taMiniappMapper.selectOne(taMiniappQuery);
                // 生成二维码
                ResponseBean taMiniappQrcode = miniAppService.getQrCode(CommConstant.DRAINAGE_QRCODE.replace("#0",taDrainage.getDrainageId().toString()).replace("#1","h5"),taMiniapp.getMiniappId());
                taDrainage.setQrCode(String.valueOf(taMiniappQrcode.getData()));
                iTaDrainageService.updateById(taDrainage);

                //添加第三方appid和secretis
                TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = new TaThirdPartyMiniappConfig();
                taThirdPartyMiniappConfig.setOrgId(getOrgId(request));
                taThirdPartyMiniappConfig.setAppid(getUUIDS());
                taThirdPartyMiniappConfig.setAppSecret(getUUIDS());
                taThirdPartyMiniappConfig.setExpirationDate(LocalDateTime.now().plusDays(7));
                taThirdPartyMiniappConfig.setTargetType(CommConstant.TARGET_TYPE_H5);
                taThirdPartyMiniappConfig.setTargetId(taDrainage.getDrainageId().toString());
                iTaThirdPartyMiniappConfigService.save(taThirdPartyMiniappConfig);
                responseBean.addSuccess(taDrainage);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 获取uuid
     * @return
     */
    private String getUUIDS() {
        String uuid= UUID.randomUUID().toString().replace("-", "");
        return uuid;
    }
    
    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/admin/taDrainage/{id}", method= RequestMethod.DELETE)
    public ResponseBean taDrainageDelete(@PathVariable Integer id, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {

            // 判断是否产生业务数据
            TaDrainage drainage = iTaDrainageService.getById(id);
            if (null != drainage.getEnlistNum() && drainage.getEnlistNum().intValue() > 0) {
                responseBean.addError("此H5活动已有用户提交数据，删除项目会删除全部数据，不建议删除数据。可以点击下架按钮终止活动。");
                return responseBean;
            }

            QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id",drainage.getOrgId());
            queryWrapper.eq("content_type",CommConstant.EVENT_H5);
            queryWrapper.eq("target_id",drainage.getDrainageId());
            List<ExtendContent> list = iExtendContentService.list(queryWrapper);
            if (null != drainage.getStatus() && drainage.getStatus().equals(CommConstant.STATUS_NORMAL) && list.size() > 0){
                responseBean.addError("删除项目会删除全部数据，不建议删除数据。可以点击下架按钮终止活动。");
                return responseBean;
            }

            drainage.setStatus(-1);
            if(iTaDrainageService.updateById(drainage)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taDrainage 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taDrainage/{id}",method= RequestMethod.PUT)
    public ResponseBean taDrainageUpdate(@PathVariable Integer id,
                                        @RequestBody TaDrainage taDrainage){
        ResponseBean responseBean = new ResponseBean();
        try {
            taDrainage.setDrainageId(id);
            if (!taDrainage.getIsMiniapp()){
                taDrainage.setShareImg("");
                taDrainage.setH5Address("");
                taDrainage.setShareTitle("");
                taDrainage.setMiddleImg("");
            }
            if (iTaDrainageService.updateById(taDrainage)){
                responseBean.addSuccess(taDrainage);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/admin/taDrainage/{id}",method= RequestMethod.GET)
    public ResponseBean taDrainageGet(@PathVariable Integer id,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaDrainage taDrainage = iTaDrainageService.getById(id);
            QueryWrapper<TaThirdPartyMiniappConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("target_type",CommConstant.TARGET_TYPE_H5);
            queryWrapper.eq("target_id",taDrainage.getDrainageId());
            queryWrapper.eq("org_id",getOrgId(request));
            TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = iTaThirdPartyMiniappConfigService.getOne(queryWrapper);
            if (null != taThirdPartyMiniappConfig){
                taDrainage.setAppid(taThirdPartyMiniappConfig.getAppid());
                taDrainage.setAppSecret(taThirdPartyMiniappConfig.getAppSecret());
            }
            responseBean.addSuccess(taDrainage);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 更改上架下架状态
     * @param id  实体ID
     * @param taDrainage 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taDrainage/exchange/{id}",method= RequestMethod.PUT)
    public ResponseBean exchangeDrainage(@PathVariable Integer id,
                                         @RequestBody TaDrainage taDrainage){
        ResponseBean responseBean = new ResponseBean();
        try {
            taDrainage.setDrainageId(id);
            QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id",taDrainage.getOrgId());
            queryWrapper.eq("content_type",CommConstant.EVENT_H5);
            queryWrapper.eq("target_id",taDrainage.getDrainageId());

            queryWrapper.gt("status", CommConstant.STATUS_DELETE); // fix bug #6816

            List<ExtendContent> list = iExtendContentService.list(queryWrapper);
            if (null != taDrainage.getStatus() && taDrainage.getStatus().equals(CommConstant.STATUS_NORMAL)){
                taDrainage.setStatus(CommConstant.STATUS_UNACCALIMED);
                //如果H5有被轮播图或开屏广告选中则轮播图和开屏广告都要下架
                list.forEach(e -> {
                    e.setStatus(CommConstant.STATUS_UNACCALIMED);
                });
            }else{
                if (DateUtils.dayToLocalDateime(taDrainage.getEndDate()).isBefore(LocalDateTime.now())){
                    responseBean.addError("已过下架时间，无法上架");
                    return responseBean;
                }
                taDrainage.setStatus(CommConstant.STATUS_NORMAL);
                //如果H5有被轮播图或开屏广告选中则轮播图和开屏广告都要上架
                list.forEach(e -> {
                    e.setStatus(CommConstant.STATUS_NORMAL);
                });
            }
            if (list.size() > 0){
                iExtendContentService.updateBatchById(list);
            }
            if (iTaDrainageService.updateById(taDrainage)){
                responseBean.addSuccess(taDrainage);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 微信端获取数据
     * @param id  实体ID
     */
    @RequestMapping(value="/wx/taDrainage/{id}",method= RequestMethod.GET)
    public ResponseBean wxDrainageGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaDrainageService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
