package com.cftech.common.approver.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.common.approver.model.Approver;
import com.cftech.common.approver.service.ApproverService;
import com.cftech.common.commondept.model.CommonDepartment;
import com.cftech.common.commondept.service.CommonDepartmentService;
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.core.util.StringUtils;
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.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 APPROVER_VIEW = "qy:approver:view"
 * 查看:public static final String APPROVER_EDIT = "qy:approver:edit"
 *
 * @author faye
 * @date: 2019-08-14 17:05
 */
@Slf4j
@Controller
@RequestMapping("/a/approver")
public class ApproverController {

    public static final String APPROVER_VIEW = "qy:approver:view";
    public static final String APPROVER_EDIT = "qy:approver:edit";

    @Autowired
    private ApproverService approverService;

    @Autowired
    private CommonDepartmentService commonDepartmentService;


    //列表页面
    @RequiresPermissions(value = APPROVER_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model,String typeform) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        if(StringUtils.isEmpty(typeform)){
            typeform="1";
        }
        model.addAttribute("id", typeform);
        return "approver/approverlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = APPROVER_EDIT)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Approver approver = approverService.fetchById(id);
            if(approver.getDepartment()!=null){
                CommonDepartment commonDepartment = commonDepartmentService.fetchById(approver.getDepartment());
                model.addAttribute("departmentName",commonDepartment.getName());
            }

            model.addAttribute("data", approver);
        }
        return "approver/approverform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = APPROVER_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Approver approver, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (approver != null && approver.getId() != null) {
                if(approver.getDepartment()==null){
                    approver.setDepartment(0L);
                }
                approver.setUpdateBy(UserUtils.getUser().getId());
                approverService.update(approver);
                rtnJson.put("errorNo", 0);
            } else {
                approver.setAccountsId(accountsId);
                approver.setDelFlag(false);
                approver.setAccountsId(UserUtils.getmpaccounts(request));
                approver.setCreateBy(UserUtils.getUser().getId());
                approver.setUpdateBy(UserUtils.getUser().getId());
                approverService.save(approver);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = APPROVER_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Approver approver, 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(approver.getEmail())) {
            conds.like("t.email", approver.getEmail());
        }
        if(!StringUtils.isEmpty(approver.getDepartmentName())){
            conds.like("cd.name",approver.getDepartmentName());
        }
        if(approver.getTypeform()!=null){
            conds.equal("cd.typeform",approver.getTypeform());
        }
        if(!StringUtils.isEmpty(approver.getName())){
            conds.like("t.name",approver.getName());
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);

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

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = APPROVER_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response,Approver approver) {
        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(approver.getEmail())) {
            conds.like("t.email", approver.getEmail());
        }
        if(approver.getTypeform()!=null){
            conds.equal("cd.typeform",approver.getTypeform());
        }
        if(!StringUtils.isEmpty(approver.getDepartmentName())){
            conds.like("cd.name",approver.getDepartmentName());
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);
        List<Approver> list = approverService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Approver.class, response).toExcel(list, "促销品申请单审批人信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = APPROVER_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Approver.class, response).toExcel(null, "促销品申请单审批人信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = APPROVER_EDIT)
    @ResponseBody
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        JSONObject retJson = new JSONObject();
        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 -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    Approver approver = new Approver();
                    approver.setAccountsId(accountId);
                    approver.setName(rowData.get(0));
                    approver.setEmail(rowData.get(1));
                    if(StringUtils.isNotBlank(rowData.get(2))){
                        Conds conds = new Conds();
                        conds.equal("del_flag",0);
                        conds.equal("name",rowData.get(2));
                        CommonDepartment commonDepartment = commonDepartmentService.fetchSearchByConds(conds);
                        if(commonDepartment!=null){
                            approver.setDepartment(commonDepartment.getId());
                            approverService.save(approver);
                        }
                    }
                    approver.setSort(Integer.valueOf(rowData.get(3)));
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        retJson.put("errorNo", "0");
        retJson.put("errorMsg", "导入成功");
        return retJson;
    }

}
