package com.cftech.brand.material.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.brand.category.model.BrandCategory;
import com.cftech.brand.category.service.BrandCategoryService;
import com.cftech.brand.department.model.BrandDepartment;
import com.cftech.brand.department.service.BrandDepartmentService;
import com.cftech.brand.material.model.BrandMaterial;
import com.cftech.brand.material.service.BrandMaterialService;
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.model.User;
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
 *
 * 权限字符串说明:
 * 查看:public static final String BRANDMATERIAL_VIEW = "qy:brandMaterial:view"
 * 查看:public static final String BRANDMATERIAL_EDIT = "qy:brandMaterial:edit"
 *
 * @author faye
 * @date 2020/01/14
 */
@Slf4j
@Controller
@RequestMapping("/a/brandMaterial")
public class BrandMaterialController {

    public static final String BRANDMATERIAL_VIEW = "qy:brandMaterial:view";
    public static final String BRANDMATERIAL_EDIT = "qy:brandMaterial:edit";

    @Autowired
    private BrandMaterialService brandMaterialService;
    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private BrandCategoryService brandCategoryService;

    @Autowired
    private BrandDepartmentService brandDepartmentService;

    /**
     * 列表页面
     *
     * @param request
     * @param model
     * @return
     */
    @RequiresPermissions(value = BRANDMATERIAL_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "brandMaterial/brandMateriallist";
    }

    /**
     * 编辑页面（新增、修改）
     *
     * @param request
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions(value = BRANDMATERIAL_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            BrandMaterial brandMaterial = brandMaterialService.fetchById(id);
            model.addAttribute("data", brandMaterial);
            if(brandMaterial.getCategoryId()!=null){
                BrandCategory brandCategory=brandCategoryService.fetchById(brandMaterial.getCategoryId());
                model.addAttribute("categoryName",brandCategory.getName());
            }
        }
        return "brandMaterial/brandMaterialform";
    }

    /**
     * 提交数据（新增、修改）
     *
     * @param brandMaterial
     * @param model
     * @param request
     * @return
     */
    @RequiresPermissions(value = BRANDMATERIAL_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(BrandMaterial brandMaterial, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            brandMaterial.setUpdateBy(UserUtils.getUser().getId());
            if (brandMaterial != null && brandMaterial.getId() != null) {
                brandMaterialService.update(brandMaterial);
                rtnJson.put("errorNo", 0);
            } else {
                brandMaterial.setNumber(codingruleUtils.getNumber(accountsId, BrandMaterial.class.getName()));
                brandMaterial.setAccountsId(accountsId);
                brandMaterial.setDelFlag(false);
                brandMaterial.setAccountsId(UserUtils.getmpaccounts(request));
                brandMaterial.setCreateBy(UserUtils.getUser().getId());
                brandMaterialService.save(brandMaterial);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            log.error("保存类别异常:"+e.getMessage());
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    /**
     * 获取列表数据
     *
     * @param iDisplayStart
     * @param iDisplayLength
     * @param brandMaterial
     * @param request
     * @return
     */

    @RequiresPermissions(value = BRANDMATERIAL_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, BrandMaterial brandMaterial, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if (!StringUtils.isEmpty(brandMaterial.getNumber())) {
            conds.like("t.number", brandMaterial.getNumber());
        }
        if (!StringUtils.isEmpty(brandMaterial.getName())) {
            conds.like("t.name", brandMaterial.getName());
        }
        Sort sort = new Sort("t.number", OrderType.ASC);

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

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

    /**
     * 导出
     *
     * @param request
     * @param response
     */
    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = BRANDMATERIAL_VIEW)
    public void exportExcel(HttpServletRequest request,BrandMaterial brandMaterial, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountId);
        if (!StringUtils.isEmpty(brandMaterial.getNumber())) {
            conds.like("t.number", brandMaterial.getNumber());
        }
        if (!StringUtils.isEmpty(brandMaterial.getName())) {
            conds.like("t.name", brandMaterial.getName());
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);

        List<BrandMaterial> list = brandMaterialService.fetchSearchByPageVo(conds, sort, 0, 0);
        ExcelKit.$Export(BrandMaterial.class, response).toExcel(list, "类别信息");
    }

    /**
     * 模板下载
     *
     * @param request
     * @param response
     */
    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = BRANDMATERIAL_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(BrandMaterial.class, response).toExcel(null, "类别信息");
    }

    /**
     * 导入
     *
     * @param request
     * @param file
     * @param model
     * @return
     */
    @RequestMapping("/importExcel")
    @RequiresPermissions(value = BRANDMATERIAL_EDIT)
    @ResponseBody
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        JSONObject retJson = new JSONObject();
        retJson.put("errorNo", "1");
        if (file == null) {
            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().setEmptyCellValue("").readExcel(storeFile, rowData -> {
                BrandMaterial brandMaterial = new BrandMaterial();
                brandMaterial.setAccountsId(accountId);
                brandMaterial.setName(rowData.get(1));

                String categoryNumber=rowData.get(2);
                if(!StringUtils.isEmpty(categoryNumber)){
                    Conds conds=new Conds();
                    conds.equal("del_flag","0");
                    conds.equal("number",categoryNumber);
                    BrandCategory brandCategory=brandCategoryService.fetchSearchByConds(conds);
                    if(brandCategory!=null){
                        brandMaterial.setCategoryId(brandCategory.getId());
                    }
                }

            /*    String departmentNumber=rowData.get(2);
                if(!StringUtils.isEmpty(departmentNumber)){
                    Conds conds=new Conds();
                    conds.equal("del_flag","0");
                    conds.equal("number",departmentNumber);
                    BrandDepartment brandDepartment=brandDepartmentService.fetchSearchByConds(conds);
                    if(brandDepartment!=null){
                        brandMaterial.setDepartementId(brandDepartment.getId());
                    }
                }*/
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    brandMaterial.setNumber(rowData.get(0));
                    Conds conds=new Conds();
                    conds.equal("del_flag","0");
                    conds.equal("number",brandMaterial.getNumber());
                    BrandMaterial oldData=brandMaterialService.fetchSearchByConds(conds);
                    if (oldData != null) {
                        brandMaterial.setId(oldData.getId());
                        brandMaterialService.update(brandMaterial);
                    }else{
                        brandMaterial.setCreateBy(UserUtils.getUser().getId());
                        brandMaterialService.save(brandMaterial);
                    }
                }else {
                    brandMaterial.setNumber(codingruleUtils.getNumber(accountId,BrandMaterial.class.getName()));
                    brandMaterial.setCreateBy(UserUtils.getUser().getId());
                    brandMaterialService.save(brandMaterial);
                }
            });
            retJson.put("errorNo","0");
            retJson.put("errorMsg","导入成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            retJson.put("errorMsg","导入失败:"+e.getMessage());
        }

        return retJson ;
    }

}
