package com.cftech.common.manager.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.common.manager.model.Manager;
import com.cftech.common.manager.model.ManagerDto;
import com.cftech.common.manager.service.ManagerService;
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 MANAGER_VIEW = "qy:manager:view"
 * 查看:public static final String MANAGER_EDIT = "qy:manager:edit"
 *
 * @author faye
 * @date: 2019-08-14 17:21
 */
@Slf4j
@Controller
@RequestMapping("/a/manager")
public class ManagerController {

    public static final String MANAGER_VIEW = "qy:manager:view";
    public static final String MANAGER_EDIT = "qy:manager:edit";

    @Autowired
    private ManagerService managerService;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = MANAGER_EDIT)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model,Long typeform) {
            Manager manager = managerService.fetchById(id);
            model.addAttribute("data", manager);
        if(StringUtils.isEmpty(typeform)){
            typeform=1L;
        }
        model.addAttribute("typeform", typeform);
            List<ManagerDto> managerDtos = managerService.fetchOpenidNickName(typeform);
            if(managerDtos!=null && managerDtos.size()>0){
                String openIds = "";
                String nickNames = "";
                for(ManagerDto managerDto : managerDtos){
                    openIds+=managerDto.getOpenid()+",";
                    nickNames+=managerDto.getNickname()+",";
                }
                model.addAttribute("nickNames",nickNames);
                model.addAttribute("openids",openIds);
                model.addAttribute("fanssArray",managerDtos);
            }

        return "manager/managerform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = MANAGER_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Manager manager, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo", 0);
        try {
            String [] ids = null;
            if(manager!=null && !StringUtils.isEmpty(manager.getOpenid())){
                ids = manager.getOpenid().split(",");
            }
            managerService.emptyTable(ids,UserUtils.getUser().getId(),accountsId,manager.getTypeform());
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = MANAGER_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Manager manager, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = MANAGER_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<Manager> list = managerService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Manager.class, response).toExcel(list, "促销品申请单管理员配置信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = MANAGER_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Manager.class, response).toExcel(null, "促销品申请单管理员配置信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = MANAGER_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().readExcel(storeFile, rowData -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    Manager manager = new Manager();
                    manager.setAccountsId(accountId);

                    manager.setOpenid(rowData.get(0));

                    managerService.save(manager);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return list(request, model);
    }

}
