package com.tykj.dev.confirmcheck;

import com.github.wenhao.jpa.Specifications;
import com.google.common.collect.Lists;
import com.tykj.dev.device.confirmcheck.entity.vo.CheckBillVo;
import com.tykj.dev.device.confirmcheck.entity.vo.CheckDetailVo;
import com.tykj.dev.device.confirmcheck.entity.vo.DevLibVo;
import com.tykj.dev.device.confirmcheck.repository.DeviceCheckDetailDao;
import com.tykj.dev.device.confirmcheck.repository.DeviceCheckStatRepo;
import com.tykj.dev.device.confirmcheck.utils.ObjTransUtil;
import com.tykj.dev.device.task.repository.TaskDao;
import com.tykj.dev.device.task.subject.common.StatusEnum;
import com.tykj.dev.device.task.subject.domin.Task;
import com.tykj.dev.union.BaseTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

import static com.tykj.dev.misc.utils.JacksonUtil.toJSon;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * DeviceCheckControllerTest.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2020/9/15 at 11:17 上午
 */
@SuppressWarnings("ALL")
@WithMockUser(username = "shena", password = "qwer1234", authorities = "省A专管员")
@AutoConfigureMockMvc
class DeviceCheckControllerTest extends BaseTest {

    @Autowired
    protected MockMvc mockMvc;

    @Autowired
    private DeviceCheckDetailDao detailRepo;

    @Autowired
    private DeviceCheckStatRepo statRepo;

    @Autowired
    private TaskDao taskRepo;

    @Autowired
    private ObjTransUtil transUtil;

    @Test
    void startManualCheck() throws Exception {


        CheckBillVo param = new CheckBillVo();
        param.setUnitId(1);
        param.setAreaRange(Lists.newArrayList(1));
        param.setCheckTitle("单元测试手动核查");
        param.setRemark("这是一段测试用的数据");
        param.setUserAId(1);
        param.setUserBId(2);

        // 测试
        RequestBuilder request;

        request = post("/check/confirm/check/bill")
                .header("Origin", "*")
                .contentType(MediaType.APPLICATION_JSON)
                .content(toJSon(param));

        mockMvc.perform(request)
                .andExpect(status().isOk())
                .andDo(mvcResult1 -> System.out.println("[测试结果] 手动发起核查任务测试通过"));

        // checkUserA 接口
        Task initTask = taskRepo.findAll(Specifications.<Task>and()
                .eq("billStatus", StatusEnum.CHECK_DETAIL_0.id)
                .build())
                .get(0);
        Integer detailBillId = initTask.getBillId();

        CheckDetailVo detailVoList = detailRepo.findById(detailBillId)
                .map(transUtil::CheckDetailDo2Vo)
                .orElse(null);

        DevLibVo devLibVo = new DevLibVo(detailVoList.getDevInLibrary(), detailVoList.getDevNotInLibrary());


        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("assignUserId", "2");
        paramMap.put("checkResult", "\"检查结果无误\"");

        String baseUrl = "/check/confirm/detail/";
        String url_a = baseUrl + "A/" + detailBillId;
        StringJoiner joiner = new StringJoiner("&", "?", "");

        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            joiner.add(k + "=" + v);
        }
        url_a += joiner.toString();
        System.out.println("url is " + url_a);
        request = put(url_a)
                .header("Origin", "*")
                .contentType(MediaType.APPLICATION_JSON)
                .content(toJSon(devLibVo));

        mockMvc.perform(request)
                .andExpect(status().isOk())
                .andDo(s -> System.out.println(
                        String.format("[测试结果] 对任务id=%d的任务执行岗位A详情审核操作成功，审核的详情表id为%d",
                                initTask.getId(),
                                initTask.getBillId())));

        // checkUserB 接口 测试审核通过
        String url_b = baseUrl + "B/" + detailBillId + "?" + "checkStatus=1";
        request = put(url_b)
                .header("Origin", "*");

        mockMvc.perform(request)
                .andExpect(status().isOk())
                .andDo(s -> System.out.println(
                        String.format("[测试结果] 对任务id=%d的任务执行岗位B详情审核操作成功，审核的详情表id为%d",
                                initTask.getId(),
                                initTask.getBillId())));

        // checkUserC - C 接口 测试审核通过
        String url_c = baseUrl + "C/" + detailBillId + "?" + "pass=1";
        request = put(url_c)
                .header("Origin", "*");

        mockMvc.perform(request)
                .andExpect(status().isOk())
                .andDo(s -> System.out.println(
                        String.format("[测试结果] 对任务id=%d的任务执行岗位C详情审核操作成功，审核的详情表id为%d",
                                initTask.getId(),
                                initTask.getBillId())));

        // checkUserC - D 接口 测试审核通过
        String url_d = baseUrl + "C/" + detailBillId + "?" + "pass=1";
        request = put(url_c)
                .header("Origin", "*");

        mockMvc.perform(request)
                .andExpect(status().isOk())
                .andDo(s -> System.out.println(
                        String.format("[测试结果] 对任务id=%d的任务执行岗位D详情审核操作成功，审核的详情表id为%d",
                                initTask.getId(),
                                initTask.getBillId())));

        // 统计数据确认接口
        // 获取父级的billId
        Integer statTaskId = initTask.getParentTaskId();
        Integer statId = taskRepo.findById(statTaskId).get().getBillId();
        String url_verify = "/check/confirm/stat/verify?statId=" + statId;
        request = post(url_verify)
                .header("Origin", "*");

        mockMvc.perform(request)
                .andExpect(status().isOk())
                .andDo(s -> System.out.println(
                        String.format("[测试结果] 对任务id=%d的任务执行统计数据确认操作成功，审核的数据表id为%d",
                                statTaskId,
                                statId)));

        // 结束之后删除本次建立的数据 包括 task 以及相应的业务表数据
        // 删除父级任务
//        Task fatherTask = taskRepo.findById(statTaskId).get();
//        Integer statBillId = fatherTask.getBillId();
//        taskRepo.deleteById(fatherTask.getId());
//        statRepo.deleteById(statBillId);
//
//        List<Task> childTask = taskRepo.findAllByParentTaskId(statTaskId);
//        List<Integer> childTaskIds = childTask.stream().map(Task::getId).collect(toList());
//        List<Integer> childBillIds = childTask.stream().map(Task::getBillId).collect(toList());

    }
}