package com.cftech.brand.manager.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.brand.manager.model.BrandManager;
import com.cftech.brand.manager.service.BrandManagerService;
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.mp.fans.model.MpFanssEntity;
import com.cftech.mp.fans.service.MpFanssService;
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 BRANDMANAGER_VIEW = "qy:brandManager:view"
 * 查看:public static final String BRANDMANAGER_EDIT = "qy:brandManager:edit"
 *
 * @author faye
 * @date 2020/01/14
 */
@Slf4j
@Controller
@RequestMapping("/a/brandManager")
public class BrandManagerController {

    public static final String BRANDMANAGER_VIEW = "qy:brandManager:view";
    public static final String BRANDMANAGER_EDIT = "qy:brandManager:edit";

    @Autowired
    private BrandManagerService brandManagerService;
    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private MpFanssService mpFanssService;

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

    /**
     * 编辑页面（新增、修改）
     *
     * @param request
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions(value = BRANDMANAGER_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            BrandManager brandManager = brandManagerService.fetchById(id);
            model.addAttribute("data", brandManager);
            if(!StringUtils.isEmpty(brandManager.getOpenId())){
                MpFanssEntity mpFanssEntity=mpFanssService.getWxUser(brandManager.getOpenId());
                if(mpFanssEntity!=null){
                    model.addAttribute("nickName",mpFanssEntity.getNickname());
                }
            }
        }
        return "brandManager/brandManagerform";
    }

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

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

    @RequiresPermissions(value = BRANDMANAGER_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, BrandManager brandManager, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(brandManager.getNumber())) {
            conds.like("number", brandManager.getNumber());
        }
        if (!StringUtils.isEmpty(brandManager.getNumber())) {
            conds.like("number", brandManager.getNumber());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

        List<BrandManager> list = brandManagerService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = brandManagerService.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 = BRANDMANAGER_EDIT)
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            brandManagerService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    /**
     * 导出
     *
     * @param request
     * @param response
     */
    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = BRANDMANAGER_VIEW)
    public void exportExcel(HttpServletRequest request,BrandManager brandManager, 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);
        if (!StringUtils.isEmpty(brandManager.getNumber())) {
            conds.like("number", brandManager.getNumber());
        }
        List<BrandManager> list = brandManagerService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(BrandManager.class, response).toExcel(list, "管理员配置信息");
    }

    /**
     * 模板下载
     *
     * @param request
     * @param response
     */
    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = BRANDMANAGER_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(BrandManager.class, response).toExcel(null, "管理员配置信息");
    }

    /**
     * 导入
     *
     * @param request
     * @param file
     * @param model
     * @return
     */
    @RequestMapping("/importExcel")
    @RequiresPermissions(value = BRANDMANAGER_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return list(request, model);
        }
// 构造临时路径来存储上传的文件
        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 -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    BrandManager brandManager = new BrandManager();
                    brandManager.setAccountsId(accountId);

                    brandManager.setNumber(rowData.get(0));


                    brandManager.setName(rowData.get(1));


                    brandManager.setEmail(rowData.get(2));


                    brandManager.setOpenId(rowData.get(3));

                    brandManagerService.save(brandManager);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return list(request, model);
    }

}
