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.Feat;
import com.mobvista.apptag.entity.Storage;
import com.mobvista.apptag.entity.Tag;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.FeatDao;
import com.mobvista.apptag.mapper.ResultDao;
import com.mobvista.apptag.mapper.TagDao;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.FeatService;
import com.mobvista.apptag.service.StorageService;
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("/storage")
public class StorageController {

    @Autowired
    private ResultDao resultDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TagDao tagDao;
    @Autowired
    private FeatDao featDao;
    @Autowired
    private FeatService featService;
    @Autowired
    private StorageService storageService;

    public static final Logger logger = LoggerFactory.getLogger(StorageController.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);

        Storage result = storageService.find(packageName);
        model.addAttribute("resultCategory", JSONObject.fromObject(result.getTag()));
        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 "storage/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 (storageService.update(packageName, userName, json)) {
            return R.ok();
        } else {
            return R.error(1, "保存失败！");
        }
    }

    @PostMapping("/list")
    @ResponseBody
    public PageUtil list(@RequestBody Query query, Model model) {
        //  PageHelper.startPage(query.getOffset() / query.getLimit() + 1, query.getLimit());
        List<Storage> results = storageService.list(query);
        String search = query.getSearch();
        int total = storageService.count(search);
        PageUtil pageUtil = new PageUtil(results, total);
        return pageUtil;
    }

    @GetMapping("")
    String storageTag(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String username, Model model) {
        User user = userDao.find(username);
        model.addAttribute("userRole", user.getRole());
        return "storage/list";
    }
}