package com.bonus.core.allocation.advise.controller;

import cn.hutool.core.text.CharSequenceUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.core.allocation.advise.dto.BasicsComplaintDTO;
import com.bonus.core.allocation.advise.service.BasicsPlaintService;
import com.bonus.core.allocation.advise.vo.AppletPlaintVO;
import com.bonus.core.common.utils.HeaderFetchUtil;
import com.bonus.i18n.I18n;
import com.github.pagehelper.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api("小程序投诉建议")
@RequestMapping({"/api/v1/wechat/applet/complaint"})
@RestController
public class AppletPlaintController extends BaseController {
   @Autowired
   @Lazy
   private BasicsPlaintService basicsPlaintService;

   @ApiOperation("用户提出投诉建议")
   @PostMapping({"/postPlaint"})
//   @RequiresGuest
   public AjaxResult postPlaint(@RequestHeader Map<String, String> headers, @RequestBody BasicsComplaintDTO complaint) {
      complaint.setOpenid(this.getOpenidByHeaders(headers));
      complaint.setSourceType(this.getSourceTypeByHeaders(headers));
      if (StringUtil.isEmpty(complaint.getContent())) {
         throw new ServiceException(I18n.getMessage("notice_applet_plaint_post_empty_content_exception", new Object[0]));
      } else if (null == complaint.getOpenid()) {
         this.logger.error("添加投诉建议时openId为空");
         throw new ServiceException(I18n.getMessage("notice_applet_plaint_post_null_openid_exception", new Object[0]));
      } else {
         this.basicsPlaintService.postPlaint(complaint);
         return AjaxResult.success();
      }
   }

   @GetMapping({"/queryPlaint"})
//   @RequiresGuest
   @ApiOperation("用户获取投诉建议记录")
   public List<AppletPlaintVO> queryPlaints(@RequestHeader Map<String, String> headers) {
      return this.basicsPlaintService.queryPlaints(this.getOpenidByHeaders(headers), this.getSourceTypeByHeaders(headers));
   }

   protected String getOpenidByHeaders(Map<String, String> headers) {
      return HeaderFetchUtil.getValueFromHeadersIgnoreCase(headers, "openid");
   }

   protected Integer getSourceTypeByHeaders(Map<String, String> headers) {
      String value = HeaderFetchUtil.getValueFromHeadersIgnoreCase(headers, "source-type");
      return CharSequenceUtil.isNotBlank(value) ? Integer.valueOf(value) : null;
   }
}
