package com.controller;

import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.model.BookPenalty;
import com.model.Org;
import com.model.ReaderWxmsg;
import com.service.BookPenaltyService;
import com.service.JieyueService;
import com.tools.JwtUtils;
import com.utils.CommonUtils;
import com.utils.ExcelExportUtil;
import com.utils.ExcelExportUtil_template;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * 图书丢失
 * 2018-10-23
 * wush
 */
@ControllerInterface(path="/bookPenalty")
public class BookPenaltyController extends BaseController {
    BookPenaltyService service = BookPenaltyService.me;
    JieyueService jieyueService = JieyueService.me;


    public void index() {
        render("/view/list-manage/bookPenaltyList.html");
    }

    public void bookPenaltyList(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String queryStr = this.getPara("queryStr");
        String starttime = this.getPara("startTime");
//        if(CommonUtils.isNotNullOrNotEmpty(starttime) && !"".equals(starttime)) {
//
//        }
        String endtime = this.getPara("endTime");
        String type = this.getPara("type");
        String penaltystatus = this.getPara("penaltystatus");
        success(service.bookPenaltyList(this.getParaToInt("pageNumber"),this.getParaToInt("pageSize"),orgid,queryStr,starttime,endtime,type,penaltystatus));
    }

    public void bookPenaltySumPrice(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String queryStr = this.getPara("queryStr");
        String starttime = this.getPara("startTime");
//        if(CommonUtils.isNotNullOrNotEmpty(starttime) && !"".equals(starttime)) {
//
//        }
        String endtime = this.getPara("endTime");
        String type = this.getPara("type");
        String penaltystatus = this.getPara("penaltystatus");
        success(service.bookPenaltySumPrice(orgid,queryStr,starttime,endtime,type,penaltystatus));
    }

    public void exportBookPenaltyList(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String orgname = new Org().dao().findById(orgid).getOrgname();
        String queryStr = this.getPara("queryStr");
        String starttime = this.getPara("startTime");
        String penaltystatus = this.getPara("penaltystatus");
//        if(CommonUtils.isNotNullOrNotEmpty(starttime) && !"".equals(starttime)) {
//
//        }
        String endtime = this.getPara("endTime");
        String type = this.getPara("type");
        List<Record> list = service.exportBookPenaltyList(orgid,queryStr,starttime,endtime,type,penaltystatus);


        List list1 = new ArrayList();
        for(Record record1:list) {
            if(CommonUtils.isNotNullOrNotEmpty(record1.get("jieyuetime"))){
                record1.set("jieyuetime",record1.getStr("jieyuetime").split(" ")[0]);
            }
            if(CommonUtils.isNotNullOrNotEmpty(record1.get("createtime"))){
                record1.set("createtime",record1.getStr("createtime").split(" ")[0]);
            }
            if(CommonUtils.isNotNullOrNotEmpty(record1.get("type"))){
                record1.set("type",record1.getInt("type")==0?"丢书":record1.getInt("type")==1?"损书":record1.getInt("type")==2?"超期":"");
            }
            if(CommonUtils.isNotNullOrNotEmpty(record1.get("penaltystatus"))){
                record1.set("penaltystatus",record1.getInt("penaltystatus")==0?"记账":record1.getInt("penaltystatus")==1?"已交":record1.getInt("penaltystatus")==2?"退还":record1.getInt("penaltystatus")==3?"记账退还":"");
            }
            list1.add(record1);
        }

        String fields[] = {"type","cardnumber","realname","deptname","barcode","title","price","jieyuetime","createtime","penaltyamount","penaltystatus"};
        ExcelExportUtil_template.exportExcel("图书流通费用记录.xls",this.getResponse(),orgname+"图书流通费用记录",list,fields,2);
        renderNull();
    }

    /**
     * 保存罚款记录
     */
    public void save(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
//            fail(3,"token错误");
//            return;
        }
        BookPenalty bean = getBean(BookPenalty.class,"");
        int jieyueid = bean.getJieyueid();
        Record record = Db.findById("t_jieyue",jieyueid);
        if (record.getInt("status") != 0) {
            success("statusError");
            return;
        }
        if(bean.getType() != 0) {
            bean.setStatus(null);
        }
        int penaltystatus = bean.getInt("penaltystatus");
        BigDecimal bigDecimal = new BigDecimal(bean.get("penaltyamount").toString());
        if(bigDecimal.compareTo(BigDecimal.ZERO) <= 0) { //如果金额为0 则将状态修改为已缴纳
            bean.set("penaltystatus",1);
        }
        bean.setCreatetime(new Date());
        bean.setOperatorid(operatorid);
        service.saveBookPenalty(bean);
        if(penaltystatus == 1 &&  new BigDecimal(bean.get("penaltyamount").toString()).compareTo(BigDecimal.ZERO) > 0) {
            ReaderWxmsg readerWxmsg = new ReaderWxmsg();
            readerWxmsg.setContent("您已成功缴费"+bean.get("penaltyamount").toString()+"元");
            readerWxmsg.setReaderid(bean.getReaderid());
            readerWxmsg.setRelevanceid(bean.getId());
            readerWxmsg.setMessagetype(3);
            readerWxmsg.setCreatetime(new Date());
            readerWxmsg.save();
        }
        int day = 0;
        if(CommonUtils.isNotNullOrNotEmpty(getPara("day"))) {
            day = getParaToInt("day");
        }

        BigDecimal amount = new BigDecimal(BigInteger.ZERO);
        if(CommonUtils.isNotNullOrNotEmpty(getPara("amount"))) {
            amount = new BigDecimal(getPara("amount"));
        }
        if(bean.getType() != 2 && day > 0 && amount.compareTo(BigDecimal.ZERO) > 0) {
            bean.set("penaltystatus", penaltystatus);
            bean.setId(null);
            bean.setPenaltyamount(amount);
            bean.setType(2);
            bean.setStatus(null);
            bean.setRemarks("超期" + day + "天罚款");
            service.saveBookPenalty(bean);
        }
        jieyueService.findOverdueInfo(bean.getReaderid());
        success();
    }


    /**
     * 补交
     */
    public void bujiao(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String cardnumber = this.getPara("cardnumber");
        Map map = jieyueService.findReaderInfoAndJieyueListByCardnumber(cardnumber,orgid,true);
        if(CommonUtils.isNullOrEmpty(map.get("userInfo"))) {
            success("查询不到读者信息");
            return;
        }
        //查询读者信息
        if(null != map.get("userInfo")) {
            Record readerRecord = (Record) map.get("userInfo");
            if(null != readerRecord.get("id")) {
                int readerid = readerRecord.getInt("id");
                Record fakuanRecord = Db.findFirst("select (select sum(penaltyamount) from t_book_penalty where readerid=? and penaltystatus=0 and penaltyamount > 0) allamount,\n" +
                        "(select sum(penaltyamount) allamount from t_book_penalty where readerid=? and penaltystatus=0 and type=0 and penaltyamount > 0) diushu,\n" +
                        "(select sum(penaltyamount) allamount from t_book_penalty where readerid=? and penaltystatus=0 and type=1 and penaltyamount > 0) sunshu,\n" +
                        "(select sum(penaltyamount) allamount from t_book_penalty where readerid=? and penaltystatus=0 and type=2 and penaltyamount > 0) chaoqi",readerid,readerid,readerid,readerid);
                map.put("fakuanRecord",fakuanRecord);
                success(map);
                return;
            }
        }
        success("noinfo");
    }

    public void saveBujiao(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        String cardnumber = getPara("cardnumber");
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        List<Record> list = Db.find("select p.* from t_book_penalty p INNER JOIN t_reader t on p.readerid = t.id where p.penaltystatus =0 and t.cardnumber =?  and t.orgid = ? ",cardnumber,orgid);
        batchSave(list);
        success();
    }

    public void saveBuhuan(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int lostpenaltyid = getParaToInt("lostpenaltyid");
        int chaoqistatus = getParaToInt("chaoqistatus");
        String amount = getPara("amount");
        int penaltystatus = getParaToInt("penaltystatus");
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        BigDecimal enaltyamount = null;
        try{
            enaltyamount = new BigDecimal(amount);
        } catch (Exception e) {
            fail(1,"金额异常!");
            return;
        }
        BookPenalty bookPenalty = service.findByid(lostpenaltyid);
        service.saveBuhuan(bookPenalty,chaoqistatus,penaltystatus,enaltyamount);
        jieyueService.findOverdueInfo(bookPenalty.getReaderid());
        success();
    }

    /**
     * 缴纳罚款
     */
    public void jiaona(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String cardnumber = this.getPara("cardnumber");
        //查询读者信息
        Record readerRecord = Db.findFirst("select * from t_reader where cardnumber = ? and orgid=?",cardnumber,orgid);
        int readerid = readerRecord.get("id");
        List<Record> list = Db.find("select * from t_book_penalty where readerid=? and penaltystatus =0",readerid);
        batchSave(list);
    }

    public void batchSave(List<Record> list){
        for(Record record : list) {
            Db.update("update t_book_penalty set penaltystatus = 1 WHERE id = ?",record.getInt("id"));
            ReaderWxmsg readerWxmsg = new ReaderWxmsg();
            readerWxmsg.setContent("您已补交罚款"+record.getStr("penaltyamount")+"元");
            readerWxmsg.setReaderid(record.getInt("readerid"));
            readerWxmsg.setRelevanceid(record.getInt("id"));
            readerWxmsg.setMessagetype(3);
            readerWxmsg.setCreatetime(new Date());
            readerWxmsg.save();
        }
    }
}
