package com.cftech.common.cancelitems.web;

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

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

    @Autowired
    private CancelitemsService cancelitemsService;
    @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 "cancelitems/cancelitemslist";
    }

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

    //提交数据（新增、修改）
    @RequiresPermissions(value = GRANTITEMS_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Cancelitems cancelitems, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (cancelitems != null && cancelitems.getId() != null) {
                cancelitems.setUpdateBy(UserUtils.getUser().getId());
                cancelitemsService.update(cancelitems);
                rtnJson.put("errorNo", 0);
            } else {
                cancelitems.setNumber(codingruleUtils.getNumber(accountsId, Cancelitems.class.getName()));
                cancelitems.setAccountsId(accountsId);
                cancelitems.setDelFlag(false);
                cancelitems.setAccountsId(UserUtils.getmpaccounts(request));
                cancelitems.setCreateBy(UserUtils.getUser().getId());
                cancelitems.setUpdateBy(UserUtils.getUser().getId());
                cancelitemsService.save(cancelitems);
                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, Cancelitems cancelitems,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(StringUtils.isNotBlank(cancelitems.getFormNumber())){
            conds.like("cap.number", cancelitems.getFormNumber());
        }
        if(cancelitems.getAppform()!=null){
            conds.equal("cg.appform",cancelitems.getAppform());
        }
        if(StringUtils.isNotBlank(dateBegin)){
            conds.greatEqual("cg.cancel_time",dateBegin);
        }
        if(StringUtils.isNotBlank(dateEnd)){
            conds.lessEqual("cg.cancel_time",dateEnd);
        }
        if (!StringUtils.isEmpty(cancelitems.getNumber())) {
            conds.like("cg.number", cancelitems.getNumber());
        }
        if (!StringUtils.isEmpty(cancelitems.getItemname())) {
            conds.like("cg.itemname", cancelitems.getItemname());
        }
        Sort sort = new Sort("cg.create_time", OrderType.DESC);

        List<Cancelitems> list = cancelitemsService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = cancelitemsService.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 {
            cancelitemsService.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 ,Cancelitems cancelitems,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(cancelitems.getAppform()!=null){
            conds.equal("cg.appform",cancelitems.getAppform());
        }
        if(StringUtils.isNotBlank(dateBegin)){
            conds.greatEqual("cg.cancel_time",dateBegin);
        }
        if(StringUtils.isNotBlank(dateEnd)){
            conds.lessEqual("cg.cancel_time",dateEnd);
        }
        List<Cancelitems> list = cancelitemsService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Cancelitems.class, response).toExcel(list, "退库物品详细信息");
    }

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



}
