package kr.co.jinwoosi.clfd.conts.prod.web;

import kr.co.jinwoosi.clfd.conts.prod.model.Prod;
import kr.co.jinwoosi.clfd.conts.prod.model.ProdSearch;
import kr.co.jinwoosi.clfd.conts.prod.service.ProdService;
import kr.co.jinwoosi.clfd.framework.base.web.BaseController;
import kr.co.jinwoosi.clfd.framework.cd.model.CdDtl;
import kr.co.jinwoosi.clfd.framework.cd.service.CdDtlService;
import kr.co.jinwoosi.clfd.framework.security.model.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class ProdController extends BaseController {

    @Value("#{prop['AppConf.filePath.image']}")
    private String imgUrl;

    @Resource(name = "prodService")
    private ProdService prodService;

    @Resource(name = "cdDtlService")
    private CdDtlService cdDtlService;

    @RequestMapping (value = "/system/prod/list.mng", method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        model.addAttribute("user", user);
        model.addAttribute("prodTyList", cdDtlService.selectList(new CdDtl("prodTy")));
        return "system/prod/prodlist";
    }

    @RequestMapping (value = "/system/prod/list.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(HttpServletRequest request, ProdSearch prodSearch) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String sort = request.getParameter("columns[" + request.getParameter("order[0][column]") + "][name]");
            String sortOder = request.getParameter("order[0][dir]");
            prodSearch.setSort(sort);
            prodSearch.setSortOrd(sortOder);
            prodSearch.setPagingYn(true);

            int totalCount = prodService.count(prodSearch);
            result.put("recordsTotal", totalCount);
            result.put("recordsFiltered", totalCount);

            result.put("data", prodService.selectList(prodSearch));
            result.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping (value = "/system/prod/detail.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> detail(ProdSearch prodSearch) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            result.put("data", prodService.select(prodSearch));
            result.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/system/prod/insert.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> insert(@RequestParam(required = false, value = "uploadFile") MultipartFile multipartFile, Prod prod){
        Map<String, Object> result = new HashMap<>();
        try {
            if(multipartFile == null || multipartFile.isEmpty()){
            } else {
                File dirPath = new File(imgUrl);
                if(!dirPath.isDirectory()){
                    dirPath.mkdir();
                }
                String uuidPath = UUID.randomUUID().toString();
                String fileName = multipartFile.getOriginalFilename().replaceAll(" ", "_");
                prod.setImageDir(uuidPath);
                prod.setProdImage(fileName);

                File file = new File(imgUrl + uuidPath + '_' + fileName);
                try {
                    multipartFile.transferTo(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            prod.setRegId(getUserId());
            prodService.insert(prod);
            result.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/system/prod/update.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> update(@RequestParam(required = false, value = "uploadFile") MultipartFile multipartFile, Prod prod, ProdSearch prodSearch) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (multipartFile == null || multipartFile.isEmpty()) {
            } else {
                File dirPath = new File(imgUrl);
                if (!dirPath.isDirectory()) {
                    dirPath.mkdir();
                }
                Prod fileInfo = prodService.select(prodSearch);
                if (fileInfo.getImageDir() != null && fileInfo.getProdImage() != null) {
                    String filePath = imgUrl + fileInfo.getImageDir() + '_' + fileInfo.getProdImage();
                    File deleteFile = new File(filePath);
                    deleteFile.delete();
                }
                String uuidPath = UUID.randomUUID().toString();
                String fileName = multipartFile.getOriginalFilename().replaceAll(" ", "_");
                prod.setImageDir(uuidPath);
                prod.setProdImage(fileName);

                File file = new File(imgUrl + uuidPath + '_' + fileName);
                try {
                    multipartFile.transferTo(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            prod.setUpdId(getUserId());
            prodService.update(prod);
            result.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("message", e.getMessage());
        }
        return result;
    }

}
