package com.yunzhi.marketing.third.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.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.TaPerson;
import com.yunzhi.marketing.entity.TaPersonVisitRecord;
import com.yunzhi.marketing.service.IMiniAppService;
import com.yunzhi.marketing.service.ITaPersonService;
import com.yunzhi.marketing.service.ITaPersonVisitRecordService;
import com.yunzhi.marketing.service.ITaShareService;
import com.yunzhi.marketing.third.entity.TaThirdPartyMiniappConfig;
import com.yunzhi.marketing.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.util.List;
import java.util.Map;

/**
 * <p>
    *   前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-10-17
 */
@RestController
@RequestMapping("/api")
public class TaThirdPartyMiniappConfigController extends BaseController {

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

    @Autowired
    public ITaThirdPartyMiniappConfigService iTaThirdPartyMiniappConfigService;

    @Autowired
    private IMiniAppService miniAppService;

    @Autowired
    private ITaPersonVisitRecordService taPersonVisitRecordService;

    @Autowired
    private ITaPersonService iTaPersonService;

    @Autowired
    private ITaShareService taShareService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/thirdPartyMiniapp",method= RequestMethod.GET)
    public ResponseBean taThirdPartyMiniappConfigList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                                      @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<TaThirdPartyMiniappConfig> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaThirdPartyMiniappConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", getOrgId(request));

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

    /**
     * 保存对象
     * @param taThirdPartyMiniappConfig 实体对象
     * @return
     */
    @RequestMapping(value="/admin/thirdPartyMiniapp/add",method= RequestMethod.POST)
    public ResponseBean taThirdPartyMiniappConfigAdd(@RequestBody TaThirdPartyMiniappConfig taThirdPartyMiniappConfig,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            taThirdPartyMiniappConfig.setOrgId(getOrgId(request));
            if (iTaThirdPartyMiniappConfigService.save(taThirdPartyMiniappConfig)){
                responseBean.addSuccess(taThirdPartyMiniappConfig);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taThirdPartyMiniappConfigAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    /**
     * 修改对象
     * @param taThirdPartyMiniappConfig 实体对象
     * @return
     */
    @RequestMapping(value="/admin/thirdPartyMiniapp/update",method= RequestMethod.PUT)
    public ResponseBean taThirdPartyMiniappConfigUpdate(@RequestBody TaThirdPartyMiniappConfig taThirdPartyMiniappConfig){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaThirdPartyMiniappConfigService.updateById(taThirdPartyMiniappConfig)){
                responseBean.addSuccess(taThirdPartyMiniappConfig);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taThirdPartyMiniappConfigUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    /**
     * 第三方生成
     * @return
     */
    @PostMapping("/third/qrcode")
    public ResponseBean thirdQrcode(@RequestBody String paramsStr,
                                    @RequestParam (required = false) String targetType,
                                    @RequestParam (required = false) String targetId,
                                    @RequestParam (required = false) String buildingId,
                                    @RequestParam (required = false) String personId,
                                    @RequestParam (required = false) String consultant,
                                    HttpServletRequest request) {
        //获取H5项目相关信息
//        String xAppid = request.getHeader("x-appid");
//        QueryWrapper<TaThirdPartyMiniappConfig> taThirdPartyMiniappConfigQueryWrapper = new QueryWrapper<>();
//
//        taThirdPartyMiniappConfigQueryWrapper.eq("appid", xAppid);
//        TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = iTaThirdPartyMiniappConfigService.getOne(taThirdPartyMiniappConfigQueryWrapper);
//        if (null == taThirdPartyMiniappConfig){
//            return ResponseBean.error("不存在的H5活动",ResponseBean.ERROR_UNAVAILABLE);
//        }
        String appid = request.getHeader("appid");

        ResponseBean res = miniAppService.getQrCode(paramsStr, appid);

        // 埋點流程, 不影響主流程

        try {
            if (StringUtils.isEmpty(personId)) {
                return res;
            }

            TaPerson taPerson = iTaPersonService.getById(personId);

            TaPersonVisitRecord taPersonVisitRecord = new TaPersonVisitRecord();
            taPersonVisitRecord.setPropertyName("H5海报");
            taPersonVisitRecord.setActivity("H5海报");
            taPersonVisitRecord.setOrgId(taPerson.getOrgId().toString());
            taPersonVisitRecord.setPersonId(personId);
            taPersonVisitRecord.setTargetId(targetId);
            taPersonVisitRecord.setTargetType(targetType);
            taPersonVisitRecord.setData("{}");
            taPersonVisitRecord.setEvent("poster");
            taPersonVisitRecord.setEventType(CommConstant.EVENT_H5);
            taPersonVisitRecord.setConsultantId(consultant);
            taPersonVisitRecord.setSharePersonId(personId);
            taPersonVisitRecord.setBuildingId(buildingId);

            taPersonVisitRecordService.newRecord(taPersonVisitRecord, taPerson);

            taShareService.saveData(taPerson.getMiniOpenid(), CommConstant.EVENT_H5, targetId);
        } catch (Exception e) {}

        return res;
    }

    @GetMapping("/third/stat-top-share")
    public ResponseBean genQRcode(
            @RequestParam (required = false) String h5Id,
            @RequestParam (required = false) String personId,
            @RequestParam (required = false, defaultValue = "10") Integer top,
            @RequestParam (required = false) String beginDate,
            @RequestParam (required = false) String endDate
    ) {
        // 暂时没有任何校验
        QueryWrapper<TaThirdPartyMiniappConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("target_type", CommConstant.TARGET_TYPE_H5);
        queryWrapper.eq("target_id", h5Id);
        queryWrapper.last("limit 1");

        TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = iTaThirdPartyMiniappConfigService.getOne(queryWrapper);

        List<Map<String, Object>> res = taShareService.statTopShare(taThirdPartyMiniappConfig.getOrgId(), "h5_share", h5Id, top, beginDate, endDate);
        return ResponseBean.success(res);
    }
}
