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.ECStorage;
import com.mobvista.apptag.entity.ECTag;
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.ECStorageService;
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_storage")
public class ECStorageController {

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

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

    @GetMapping("/edit")
    String edit(@RequestParam(name = "urlMd5") String urlMd5, Model model) {
        ECTag tag = ecTagService.find(urlMd5);
        model.addAttribute("ecTag", tag);

        ECStorage result = ecStorageService.find(urlMd5);
        model.addAttribute("resultECTag", JSONObject.fromObject(result.getTag()));
        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_storage/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 (ecStorageService.update(urlMd5, 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<ECStorage> results = ecStorageService.list(query);
        String search = query.getSearch();
        int total = ecStorageService.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 "ec_storage/list";
    }
}