package com.cftech.common.grantitems.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.common.grantitems.model.Grantitems;
import com.cftech.common.grantitems.service.GrantitemsService;
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.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.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 GRANTITEMS_VIEW = "qy:grantitems:view"
 * 查看:public static final String GRANTITEMS_EDIT = "qy:grantitems:edit"
 *
 * @author faye
 * @date: 2019-08-19 09:45
 */
@Slf4j
@Controller
@RequestMapping("/a/grantitems")
public class GrantitemsController {

    public static final String GRANTITEMS_VIEW = "qy:grantitems:view";
    public static final String GRANTITEMS_EDIT = "qy:grantitems:edit";

    @Autowired
    private GrantitemsService grantitemsService;
    @Autowired
    private CodingruleUtils codingruleUtils;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = GRANTITEMS_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Grantitems grantitems = grantitemsService.fetchById(id);
            model.addAttribute("data", grantitems);
        }
        return "grantitems/grantitemsform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = GRANTITEMS_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Grantitems grantitems, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (grantitems != null && grantitems.getId() != null) {
                grantitems.setUpdateBy(UserUtils.getUser().getId());
                grantitemsService.update(grantitems);
                rtnJson.put("errorNo", 0);
            } else {
                grantitems.setNumber(codingruleUtils.getNumber(accountsId, Grantitems.class.getName()));
                grantitems.setAccountsId(accountsId);
                grantitems.setDelFlag(false);
                grantitems.setAccountsId(UserUtils.getmpaccounts(request));
                grantitems.setCreateBy(UserUtils.getUser().getId());
                grantitems.setUpdateBy(UserUtils.getUser().getId());
                grantitemsService.save(grantitems);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = GRANTITEMS_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Grantitems grantitems,String reservationDateStr, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("cg.del_flag", Constants.DEL_FLAG_0);
        conds.equal("cg.accounts_id", accountsId);
        String dateBegin = null;
        String dateEnd = null;
        if (!org.springframework.util.StringUtils.isEmpty(reservationDateStr)) {
            dateBegin = reservationDateStr.split(" - ")[0];
            dateEnd = reservationDateStr.split(" - ")[1];
        }

        if(grantitems.getAppform()!=null){
            conds.equal("cg.appform",grantitems.getAppform());
        }
        if(StringUtils.isNotBlank(grantitems.getFormNumber())){
            conds.like("cap.number", grantitems.getFormNumber());
        }
        if(StringUtils.isNotBlank(dateBegin)){
            conds.greatEqual("cg.grant_time",dateBegin);
        }
        if(StringUtils.isNotBlank(dateEnd)){
            conds.lessEqual("cg.grant_time",dateEnd);
        }
        if (!StringUtils.isEmpty(grantitems.getNumber())) {
            conds.like("cg.number", grantitems.getNumber());
        }
        if (!StringUtils.isEmpty(grantitems.getItemname())) {
            conds.like("cg.itemname", grantitems.getItemname());
        }
        Sort sort = new Sort("cg.create_time", OrderType.DESC);

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

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = GRANTITEMS_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response ,Grantitems grantitems,String reservationDateStr) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("cg.create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("cg.del_flag", 0);
        conds.equal("cg.accounts_id", accountId);
        String dateBegin = null;
        String dateEnd = null;
        if (!org.springframework.util.StringUtils.isEmpty(reservationDateStr)) {
            dateBegin = reservationDateStr.split(" - ")[0];
            dateEnd = reservationDateStr.split(" - ")[1];
        }
        if(grantitems.getAppform()!=null){
            conds.equal("cg.appform",grantitems.getAppform());
        }
        if(StringUtils.isNotBlank(dateBegin)){
            conds.greatEqual("cg.grant_time",dateBegin);
        }
        if(StringUtils.isNotBlank(dateEnd)){
            conds.lessEqual("cg.grant_time",dateEnd);
        }
        List<Grantitems> list = grantitemsService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Grantitems.class, response).toExcel(list, "发放物品详细信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = GRANTITEMS_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Grantitems.class, response).toExcel(null, "发放物品详细信息");
    }



}
