package cn.palmte.work.controller.backend;

import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.model.*;
import cn.palmte.work.service.DeptService;
import cn.palmte.work.service.ProcurementTypeService;
import cn.palmte.work.utils.Utils;
import cn.palmte.work.utils.excel.ExportUtils;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import top.jfunc.common.db.bean.Page;
import top.jfunc.common.utils.CollectionUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/department")
public class DepartmentController extends BaseController{

    @Autowired
    private DeptService deptService;

    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private AdminRepository adminRepository;

    /**
     * 列表查询
     * @param keywords
     * @param pageNumber
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(@RequestParam(value = "keywords",required = false) String keywords,
                       @RequestParam(value = PAGE_NUMBER, defaultValue = DEFAULT_PAGE_NUMBER) int pageNumber,
                       @RequestParam(value = PAGE_SIZE, defaultValue = DEFAULT_PAGE_SIZE) int pageSize,
                       Map<String, Object> model) {
        model.put("keywords",keywords);
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo(keywords,model);
        Page<Dept> page = deptService.list(searchInfo, pageNumber, pageSize);
        List<Dept> list = page.getList();
        if(CollectionUtil.isNotEmpty(list)){

            int offset = (pageNumber - 1) * pageSize;
            for (int i = 0 , size = list.size(); i < size; i++) {
                list.get(i).setTempId(i+1 + offset);
            }
        }
        model.put("pager", page);
        List<Dept> deptList = deptRepository.findEnableParent();
        model.put("parentList", deptList);
        return "/admin/department_list";
    }

    /**
     * 跳转新增页面
     * @param model
     * @return
     */
    @GetMapping(value = "/add")
    public String add( Map<String, Object> model){
        Dept department = new Dept();
        model.put("deptId",-1);
        model.put("department",department);
        List<Admin> adminList = adminRepository.getAllEnableWoAdmin();
        model.put("userList", adminList);
        List<Dept> deptList = deptRepository.findEnableParent();
        model.put("parentList", deptList);
        return "/admin/department_input";
    }

    /**
     * 跳转编辑页面
     * @param model
     * @return
     */
    @GetMapping(value = "/edit")
    public String edit( Map<String, Object> model, @RequestParam("id") int id){
        Dept dept = deptRepository.findOne(id);
        model.put("deptId", id);
        model.put("department", dept);
        List<Admin> adminList = adminRepository.getAllEnableWoAdmin();
        model.put("userList", adminList);
        List<Dept> deptList = deptRepository.findEnableParent();
        model.put("parentList", deptList);
        return "/admin/department_input";
    }

    /**
     * 保存
     * @param deptId
     * @param dept
     * @param model
     * @return
     */
    @PostMapping(value = "/save")
    public String save(@RequestParam("deptId") int deptId,
                       Dept dept, Map<String, Object> model){

        deptService.saveOtUpdate(deptId,dept);
        return "redirect:/department/list";
    }

    /**
     * 启用 禁用
     */
    @RequestMapping("/enableOrDisable")
    @ResponseBody
    public ResponseMsg enableOrDisable(@RequestParam("id") int id,
                                       @RequestParam("status") int status, RedirectAttributes attr) {
        boolean isSuccess = false;
        try {
            isSuccess = deptService.enableOrDisable(status, id);
        } catch (Exception e) {
            e.getMessage();
        }
        if (isSuccess) {
            return ResponseMsg.buildSuccessMsg("操作成功");
        } else {
            return ResponseMsg.buildSuccessMsg("操作失败");
        }
    }

    /**
     * 启用 禁用
     */
    @RequestMapping("/checkName")
    @ResponseBody
    public ResponseMsg checkName(@RequestParam("id") int id,
                                       @RequestParam("name") String name, RedirectAttributes attr) {
        Dept dept = deptRepository.findByNameEquals(name);
        if (dept != null && id != dept.getId()) {
            return ResponseMsg.buildFailedMsg("失败");
        }
        return ResponseMsg.buildSuccessMsg("成功");
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    public void export(@RequestParam(value = "keywords",required = false) String keywords, HttpServletResponse httpServletResponse) throws IOException {
        Map<String, String> searchInfo = getSearchInfo(keywords);
        downloadHeader(httpServletResponse , Utils.generateExcelName("部门表"), "application/octet-stream");
        String[] headers = {"部门名称", "部门领导", "所属上级", "创建人","创建时间", "状态"};
        String[] exportColumns = {"name", "realName", "parentName", "createdBy","createdTime", "status"};
        ExportUtils.exportToExcel(headers, exportColumns, 1, 10000,
                httpServletResponse.getOutputStream(), (pN, pS) -> deptService.list(searchInfo, pN, pS).getList());
    }
}
