package com.mobvista.apptag.controller;

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

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.mapper.FeatDao;
import com.mobvista.apptag.mapper.TagDao;
import com.mobvista.apptag.service.FeatService;
import com.mobvista.apptag.service.ResultService;
import com.mobvista.apptag.service.TagService;
import com.mobvista.apptag.utils.PageUtil;
import com.mobvista.apptag.utils.Query;
import com.mobvista.apptag.utils.R;

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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import net.sf.json.JSONArray;

/**
 * @author wangjf
 */
@Controller
@RequestMapping("/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    @Autowired
    private ResultService resultService;

    @Autowired
    private FeatService featService;

    @Autowired
    private TagDao tagDao;

    @Autowired
    private FeatDao featDao;

    public static final Logger logger = LoggerFactory.getLogger(TagController.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);
        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("rule", ruleFeat);
        List<Feat> styleFeat = featDao.firstList("03");
        model.addAttribute("style", styleFeat);
        List<Feat> themeFeat = featDao.firstList("04");
        model.addAttribute("theme", themeFeat);
        return "tag/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) {
        System.out.println("packageName=" + packageName + ",categoryCode=" + categoryCode);
        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 (tagService.update(packageName, userName) && resultService.save(packageName, userName, json)) {
            return R.ok();
        } else {
            return R.error(1, "保存失败！");
        }
    }

    @PostMapping("/list")
    @ResponseBody
    public PageUtil list(@RequestBody Query query,
                         @RequestParam(name = "tag", required = false, defaultValue = "0") int tag) {
        PageHelper.startPage(query.getOffset() / query.getLimit() + 1, query.getLimit());
        List<Tag> tags = tagDao.list(tag);
        int total = tagDao.count(tag);
        PageUtil pageUtil = new PageUtil(tags, total);
        return pageUtil;
    }


    /*
     * @GetMapping("/listAll")
     *
     * @ResponseBody public PageUtil
     * listAll(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String username,
     *
     * @RequestParam(value = "offset", defaultValue = "0") int pageNum,
     *
     * @RequestParam(value = "limit", defaultValue = "10") int pageSize,
     *
     * @RequestParam(name = "tag", required = false, defaultValue = "1") int tag) {
     * PageHelper.startPage(pageNum + 1, pageSize); List<Tag> tags =
     * tagDao.list(tag, username); int total = tagDao.count(tag, username); PageUtil
     * pageUtil = new PageUtil(tags, total); return pageUtil; }
     */

    @GetMapping("")
    String falseTag(Model model) {
        return "tag/list";
    }
}