package com.iformall.service.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.iformall.domain.po.*;
import com.iformall.enums.EnumCouponSendSendType;
import com.iformall.enums.EnumCouponSendStatus;
import com.iformall.enums.EnumCouponSendType;
import com.iformall.mapper.WxCouponMapper;
import com.iformall.service.WxCouponSendService;
import com.iformall.service.WxLevelConfigService;
import com.iformall.service.WxScoreRulesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.subject.WebSubject;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@AutoConfigureMockMvc
@FixMethodOrder(MethodSorters.JVM)
@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class WebTest {

    private static final String TENANT_ID = "456";

    @Resource
    private org.apache.shiro.mgt.SecurityManager securityManager;
    @Resource
    private WebApplicationContext webApplicationContext;
    private MockHttpServletRequest mockHttpServletRequest;
    private MockHttpServletResponse mockHttpServletResponse;

    @Autowired
    WxLevelConfigService levelConfigService;

    @Autowired
    WxCouponSendService wxCouponSendService;

    @Autowired
    WxScoreRulesService wxScoreRulesService ;

    private MockMvc mockMvc;

    @Autowired
    WxCouponMapper wxCouponMapper ;

    @Before
    public void setUp() {
        mockHttpServletRequest = new MockHttpServletRequest(webApplicationContext.getServletContext());
        mockHttpServletResponse = new MockHttpServletResponse();
        MockHttpSession mockHttpSession = new MockHttpSession(webApplicationContext.getServletContext());
        mockHttpServletRequest.setSession(mockHttpSession);
        SecurityUtils.setSecurityManager(securityManager);
        mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .build();
        login("yftest", "123456zz");
    }

    private void login(String username, String password) {
        Subject subject = new WebSubject.Builder(mockHttpServletRequest, mockHttpServletResponse)
                .buildWebSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
        subject.login(token);
        ThreadContext.bind(subject);
    }

    @Test
    public void levelList() {
        WxLevelConfig wxLevelConfig = new WxLevelConfig();
        wxLevelConfig.setTenantId(TENANT_ID);
        wxLevelConfig.setSortColumns(BaseEntity.SortField.Points_ASC);
        PageInfo<WxLevelConfig> data = levelConfigService.listAsPage(wxLevelConfig, 1, 999);
        log.debug("data:{}", JSON.toJSONString(data));
    }

    /**
     * 投放列表
     */
    @Test
    public void list() {
        WxCouponSend query = new WxCouponSend();
        query.setSendType(EnumCouponSendSendType.MERCHANT.getCode());
        query.setStatus(EnumCouponSendStatus.VALID.getCode());
        query.setSortColumns(BaseEntity.SortField.CreateDate_DESC);
        List pageInfo = wxCouponSendService.listAsPage(query, 0, 10).getList();
        log.info("couponSend list = {}", JSON.toJSONString(pageInfo));
    }

    /**
     * 商户注券，添加conditions: {limit:888}
     */
    @Test
    public void listCouponSend() throws Exception {
        MvcResult result = mockMvc.perform(
                MockMvcRequestBuilders.get("/wxCouponSend/list")
                        .param("pageNum", "1")
                        .param("pageSize", "10")
                        .param("sortColumn", "createDate")
                        .param("sortOrder", "desc")
                        .param("status", "1")
                        //.param("expired", "1")
                        .param("sendType", EnumCouponSendSendType.MERCHANT.getCode() + "")
        )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        String responseStr = result.getResponse().getContentAsString();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> respMap = mapper.readValue(responseStr, Map.class);
        log.info("respMap -> {}", JSON.toJSONString(respMap));
    }

    /**
     * 商户注券，添加conditions: {limit:888}
     */
    @Test
    public void addCouponSend() throws Exception {
        WxCouponSend wxCouponSend = new WxCouponSend();
        wxCouponSend.setSendType(EnumCouponSendSendType.MERCHANT.getCode());
        wxCouponSend.setCouponId(267460814401699840L);
        wxCouponSend.setTenantId(TENANT_ID);
        wxCouponSend.setTitle("口红666");
        wxCouponSend.setCreateDate(new Date());
        wxCouponSend.setUpdateDate(new Date());
        JSONObject jo = new JSONObject();
        jo.put(WxCouponSend.KEY_MERCHANT_LNVENTORY, 994);

        wxCouponSend.setConditions(jo.toJSONString());
        MvcResult result = mockMvc.perform(
                MockMvcRequestBuilders.post("/wxCouponSend/add")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(JSON.toJSONString(wxCouponSend)))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        String responseStr = result.getResponse().getContentAsString();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> respMap = mapper.readValue(responseStr, Map.class);
        log.info("respMap -> {}", JSON.toJSONString(respMap));
    }

    @Test
    public void add() throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("creditNum", "1");
        params.put("creditType", "12");
        params.put("cuserId", "329879374400159744");
        params.put("operatorType", "4");
        MvcResult result = mockMvc.perform(
                MockMvcRequestBuilders.post("/wxCreditHistory/add")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(JSON.toJSONString(params))
        )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        String responseStr = result.getResponse().getContentAsString();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> respMap = mapper.readValue(responseStr, Map.class);
        log.info("respMap -> {}", JSON.toJSONString(respMap));
    }

}
