package com.mobvista.apptag.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mobvista.apptag.config.WebSecurityConfig;
import com.mobvista.apptag.entity.ECTag;
import com.mobvista.apptag.entity.ECTagResult;
import com.mobvista.apptag.entity.Feat;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.FeatDao;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.ECResultService;
import com.mobvista.apptag.service.ECTagService;
import com.mobvista.apptag.service.FeatService;
import com.mobvista.apptag.utils.PageUtil;
import com.mobvista.apptag.utils.Query;
import com.mobvista.apptag.utils.R;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author wangjf
 */
@Controller
@RequestMapping("/ec_result")
public class ECResultController {

    @Autowired
    private ECResultService ecResultService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ECTagService ecTagService;
    @Autowired
    private FeatDao featDao;
    @Autowired
    private FeatService featService;

    public static final Logger logger = LoggerFactory.getLogger(ECResultController.class);

    @GetMapping("/edit")
    String edit(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String userName,
                @RequestParam(name = "urlMd5") String urlMd5, Model model) {
        User user = userDao.find(userName);
        ECTag tag = ecTagService.find(urlMd5);
        model.addAttribute("ecTag", tag);
        ECTagResult result = ecResultService.find(urlMd5, user.getUserId());
        model.addAttribute("resultECTag", JSONObject.fromObject(result.getFeatId()));
        List<Feat> categoryFeat = featDao.firstList("05");
        JSONArray jsonArray = JSONArray.fromObject(categoryFeat);
        model.addAttribute("firstECTag", jsonArray);
        List<Feat> secondCategoryFeat = featDao.list("05");
        JSONArray secondJsonArray = JSONArray.fromObject(secondCategoryFeat);
        model.addAttribute("secondECTag", secondJsonArray);
        return "ec_result/edit";
    }

    @PostMapping("/save")
    @ResponseBody
    R save(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String userName,
           @RequestParam(name = "urlMd5") String urlMd5,
           @RequestParam(name = "ecCode", required = false) String ecCode) {

        Map<String, String> codeMap = new HashMap<String, String>();
        Map<String, String> featMap = featService.getMap();

        // 类型标签
        if (StringUtils.isNotBlank(ecCode)) {
            String[] codes = ecCode.split(",");
            for (String code : codes) {
                codeMap.put(code, featMap.get(code));
            }
        }

        ObjectMapper mapper = new ObjectMapper();
        String json = "";
        try {
            json = mapper.writeValueAsString(codeMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        if (ecResultService.save(urlMd5, userName, json)) {
            return R.ok();
        } else {
            return R.error(1, "保存失败！");
        }
    }

    @PostMapping("/list")
    @ResponseBody
    public PageUtil list(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String username, @RequestBody Query query) {
        List<ECTagResult> results = ecResultService.list(username, query);
        String search = query.getSearch();
        int total = ecResultService.count(username, search);
        PageUtil pageUtil = new PageUtil(results, total);
        return pageUtil;
    }

    @GetMapping("")
    String trueTag(Model model) {
        return "ec_result/list";
    }
}