package com.cftech.productclassify.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.productclassify.model.Productclassify;
import com.cftech.productclassify.service.ProductclassifyService;
import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * 产品分类Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String PRODUCTCLASSIFY_VIEW = "qy:productclassify:view"
 * 查看:public static final String PRODUCTCLASSIFY_EDIT = "qy:productclassify:edit"
 *
 * @author Buyj
 * @date: 2020-09-22 18:06
 */
@Slf4j
@Controller
@RequestMapping("/a/productclassify")
public class ProductclassifyController {

    public static final String PRODUCTCLASSIFY_VIEW = "qy:productclassify:view";
    public static final String PRODUCTCLASSIFY_EDIT = "qy:productclassify:edit";

    @Autowired
    private ProductclassifyService productclassifyService;

    @Autowired
    private CodingruleUtils codingruleUtils;

    private static final String fatherName = SystemConfig.p.getProperty("PRODUCT_CLASSIFY_FATHER_NAME");

    //列表页面
    @RequiresPermissions(value = PRODUCTCLASSIFY_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "productclassify/productclassifylist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = PRODUCTCLASSIFY_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Productclassify productclassify = productclassifyService.fetchById(id);
            if(productclassify!=null && productclassify.getParentId().equals("0")){
                productclassify.setParentName(fatherName);
            }else{
                productclassify.setParentName(productclassifyService.fetchById(productclassify.getParentId()).getClassifyName());
            }

            model.addAttribute("data", productclassify);
        }
        return "productclassify/productclassifyform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = PRODUCTCLASSIFY_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Productclassify productclassify, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (productclassify != null && productclassify.getId() != null) {
                productclassify.setUpdateBy(UserUtils.getUser().getId());
                productclassifyService.update(productclassify);
                rtnJson.put("errorNo", 0);
            } else {
                productclassify.setClassifyNumber(codingruleUtils.getNumber(accountsId,Productclassify.class.getName()));
                productclassify.setAccountsId(accountsId);
                productclassify.setDelFlag(false);
                productclassify.setAccountsId(UserUtils.getmpaccounts(request));
                productclassify.setCreateBy(UserUtils.getUser().getId());
                productclassify.setUpdateBy(UserUtils.getUser().getId());
                productclassifyService.save(productclassify);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = PRODUCTCLASSIFY_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Productclassify productclassify, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("a.del_flag", Constants.DEL_FLAG_0);
        conds.equal("a.accounts_id", accountsId);
        if (!StringUtils.isEmpty(productclassify.getClassifyName())) {
            conds.like("a.classify_name",productclassify.getClassifyName());
        }
        Sort sort = new Sort("a.sort", OrderType.DESC);

        List<Productclassify> list = productclassifyService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = productclassifyService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = PRODUCTCLASSIFY_EDIT)
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            productclassifyService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = PRODUCTCLASSIFY_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        List<Productclassify> list = productclassifyService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Productclassify.class, response).toExcel(list, "产品分类信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = PRODUCTCLASSIFY_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Productclassify.class, response).toExcel(null, "产品分类信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = PRODUCTCLASSIFY_EDIT)
    @ResponseBody
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        JSONObject retJson = new JSONObject();
        Long accountId = UserUtils.getmpaccounts(request);
        StringBuffer classifyNumber = new StringBuffer();
        StringBuffer classifyParent = new StringBuffer();
        if (file == null) {
            retJson.put("errorNo", "1");
            retJson.put("errorMsg", "未选择导入文件");
            return retJson;
        }
        // 构造临时路径来存储上传的文件
        String uploadPath = System.getProperty("java.io.tmpdir");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String fileName = file.getOriginalFilename();
        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);
        try {
            file.transferTo(storeFile);

            ExcelKit.$Import().readExcel(storeFile, rowData -> {
                Conds conds = null;
                Productclassify productclassify = new Productclassify();
                if(!StringUtils.isEmpty(rowData.get(1))){
                    //获取产品分类编码 查看编码是否重复
                    conds = new Conds();
                    conds.equal("a.classify_number",rowData.get(1));
                    conds.equal("a.del_flag","0");
                    Productclassify productClassfyStr = productclassifyService.fetchSearchByConds(conds);

                    //不为空则产品分类编码已存在
                    if(productClassfyStr != null){
                        classifyNumber.append(" '"+rowData.get(1)+"', ");
                        return;
                    }else{
                        productclassify.setClassifyNumber(rowData.get(1));
                    }
                }

                if(!StringUtils.isEmpty(rowData.get(4))){
                    conds = new Conds();
                    conds.equal("a.classify_number",rowData.get(4));
                    conds.equal("a.del_flag","0");
                    Productclassify productClassifyParent = productclassifyService.fetchSearchByConds(conds);
                    if(productClassifyParent == null){
                        //父级编码不存在
                        classifyParent.append(" '"+rowData.get(4)+"', ");
                        return;
                    }else{
                        productclassify.setParentId(String.valueOf(productClassifyParent.getId()));
                    }
                }else{
                    productclassify.setParentId("0");
                }
                //productclassify.setClassifyNumber(codingruleUtils.getNumber(accountId,Productclassify.class.getName()));
                productclassify.setAccountsId(accountId);
                productclassify.setClassifyName(rowData.get(0));
                productclassify.setSort(rowData.get(2));
                productclassify.setWhetherRecommend(rowData.get(3));
                productclassifyService.save(productclassify);
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        retJson.put("errorNo", "0");
        if(classifyNumber.length() > 0){
            retJson.put("errorMsg","部分产品分类导入失败，原因：产品分类编码重复："+classifyNumber.toString());
        }else if(classifyParent.length() > 0){
            retJson.put("errorMsg","部分产品分类导入失败，原因：产品分类父级编码不存在："+classifyParent.toString());
        }else {
            retJson.put("errorMsg","导入成功");
        }
        return retJson;
    }

    @RequestMapping("treeData")
    @ResponseBody
    public JSONObject getTreeData(HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        JSONArray array = new JSONArray();
        Sort sort = new Sort("parent_id", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", UserUtils.getmpaccounts(request));
        conds.equal("parent_id",0);
        List<Productclassify> papercategories = productclassifyService.fetchTreeByPage(conds, sort, 0, 0);
        JSONObject t = new JSONObject();
        t.put("id", 0);
        t.put("pId", -1);
        t.put("name", "产品分类");
        t.put("open", true);
        array.add(t);
        for (Productclassify productclassify : papercategories) {
            JSONObject tmp = new JSONObject();
            tmp.put("id", productclassify.getId());
            tmp.put("pId", productclassify.getParentId());
            tmp.put("name", productclassify.getClassifyName());
            array.add(tmp);
        }
        rtnJson.put("aaData", array);
        return rtnJson;
    }

}
