package com.mobvista.apptag.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.mobvista.apptag.config.WebSecurityConfig;
import com.mobvista.apptag.entity.Feat;
import com.mobvista.apptag.entity.Tag;
import com.mobvista.apptag.entity.TagResult;
import com.mobvista.apptag.mapper.FeatDao;
import com.mobvista.apptag.mapper.ResultDao;
import com.mobvista.apptag.mapper.TagDao;
import com.mobvista.apptag.service.FeatService;
import com.mobvista.apptag.service.ResultService;
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.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangjf
 */
@Controller
@RequestMapping("/result")
public class ResultController {

    @Autowired
    private ResultService resultService;
    @Autowired
    private ResultDao resultDao;
    // @Autowired
    // private UserDao userDao;
    @Autowired
    private TagDao tagDao;
    @Autowired
    private FeatDao featDao;
    @Autowired
    private FeatService featService;

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

    @GetMapping("/edit")
    String edit(@RequestParam(name = "packageName") String packageName, Model model) {
        Tag tag = tagDao.find(packageName);
        if (StringUtils.isNotBlank(tag.getUrl()) && tag.getUrl().length() > 2 && tag.getUrl().startsWith("[") && tag.getUrl().endsWith("]")) {
            String url = tag.getUrl().substring(2, tag.getUrl().length() - 2).replace("\"", "").split(",")[0];
            tag.setUrl(url);
        } else {
            tag.setUrl("");
        }
        model.addAttribute("tag", tag);
        TagResult result = resultDao.find(packageName);
        model.addAttribute("resultCategory", JSONObject.fromObject(result.getFeatId()));
        List<Feat> categoryFeat = featDao.firstList("01");
        JSONArray jsonArray = JSONArray.fromObject(categoryFeat);
        model.addAttribute("firstCategory", jsonArray);
        List<Feat> secondCategoryFeat = featDao.list("01");
        JSONArray secondJsonArray = JSONArray.fromObject(secondCategoryFeat);
        model.addAttribute("secondCategory", secondJsonArray);
        List<Feat> ruleFeat = featDao.firstList("02");
        model.addAttribute("ruleCategory", JSONArray.fromObject(ruleFeat));
        List<Feat> styleFeat = featDao.firstList("03");
        model.addAttribute("styleCategory", JSONArray.fromObject(styleFeat));
        List<Feat> themeFeat = featDao.firstList("04");
        model.addAttribute("themeCategory", JSONArray.fromObject(themeFeat));
        return "result/edit";
    }

    @PostMapping("/save")
    @ResponseBody
    R save(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String userName,
           @RequestParam(name = "packageName") String packageName,
           @RequestParam(name = "categoryCode", required = false) String categoryCode,
           @RequestParam(name = "ruleCode", required = false) String ruleCode,
           @RequestParam(name = "styleCode", required = false) String styleCode,
           @RequestParam(name = "themeCode", required = false) String themeCode) {

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

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

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

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

        // 主题标签
        if (StringUtils.isNotBlank(themeCode)) {
            String[] codes = themeCode.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 (resultService.save(packageName, 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) {
        //  PageHelper.startPage(query.getOffset() / query.getLimit() + 1, query.getLimit());
        List<TagResult> results = resultService.list(username, query);
        int total = resultService.count(username);
        PageUtil pageUtil = new PageUtil(results, total);
        return pageUtil;
    }

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