package com.controller.api;


import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.model.OrgDept;
import com.model.Reader;
import com.tools.ISBNTools;
import com.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.*;

@Clear
@ControllerInterface(path="/api/reader")
public class ReaderApiController extends BaseController {
    @Before(POST.class)
    public void createReader(){
        getFile();
        String secret = getPara("secret");
        if(CommonUtils.isNullOrEmpty(secret)){
            fail(0,"secret不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_org where orgsecret=?",secret);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(0,"secret错误");
            return;
        }
        Reader reader = new Reader();
        Integer readertypeid = getParaToInt("readertypeid",62);//读者权限： 62 学生 63 老师 64 其他
        reader.setReadertypeid(readertypeid);
        String cardnumber = getPara("cardnumber");
        if(CommonUtils.isNullOrEmpty(cardnumber)){
            fail(0,"cardnumber不能为空");
            return;
        }
        Record readerRecord = Db.findFirst("select * from t_reader where orgid = ? and cardnumber = ?",record.getInt("id"),cardnumber);
        if(CommonUtils.isNotNullOrNotEmpty(readerRecord)){
            fail(0,"读者证号重复");
            return;
        }
        reader.setCardnumber(cardnumber);
        reader.setOrgid(record.getInt("id"));
        String orgdeptname = getPara("orgdeptname"); //所属班级/部门名称
        if(CommonUtils.isNullOrEmpty(orgdeptname)){
            fail(0,"orgdeptname不能为空");
            return;
        }
        try {
            orgdeptname = URLDecoder.decode(orgdeptname, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Record orgdeptRecord = Db.findFirst("select id from t_org_dept where orgid = ? and deptname = ? ",record.getInt("id"),orgdeptname);
        if(CommonUtils.isNullOrEmpty(orgdeptRecord)){
            Record readAuthRecord = Db.findFirst("select id from t_reader_auth where orgid = ? order by jieyuetianshu asc limit 1",record.getInt("id"));
            if(CommonUtils.isNullOrEmpty(readAuthRecord)){
                fail(0,"该学校没有创建借阅权限");
                return;
            }
            OrgDept orgDept = new OrgDept();
            orgDept.setMemo("第三方系统同步数据创建").setReaderauthid(readAuthRecord.getInt("id")).setDeptname(orgdeptname).setOrgid(record.getInt("id")).setCreatetime(new Date()).save();
            orgdeptRecord = orgDept.toRecord();
        }
        reader.setOrgdeptid(orgdeptRecord.getInt("id"));
        String realname = getPara("realname");
        if(CommonUtils.isNullOrEmpty(realname)){
            fail(0,"realname不能为空");
            return;
        }
        try {
            realname = URLDecoder.decode(realname, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        reader.setRealname(realname);
        String sex = getPara("sex");
        if(CommonUtils.isNullOrEmpty(sex)){
            fail(0,"sex不能为空");
            return;
        }
        try {
            sex = URLDecoder.decode(sex, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (!sex.equals("男") && !sex.equals("女")){
            fail(0,"性别错误");
            return;
        }
        reader.setSex(sex);
        String authname = getPara("authname");
        if(CommonUtils.isNullOrEmpty(authname)){
            fail(0,"authname不能为空");
            return;
        }
        try {
            authname = URLDecoder.decode(authname, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Record authRecord = Db.findFirst("select id from t_reader_auth where orgid = ? and name = ? ",record.getInt("id"),authname);
        if(CommonUtils.isNullOrEmpty(authRecord)){
            fail(0,"查询不到权限信息");
            return;
        }
        reader.setReaderauthid(authRecord.getInt("id"));
        Integer certificatetype = getParaToInt("certificatetype");//证件类型 58 身份证 59 驾驶证 60 学生证 61 护照
        if(CommonUtils.isNotNullOrNotEmpty(certificatetype)){
            if(certificatetype != 58 && certificatetype != 59 && certificatetype != 60 && certificatetype != 61){
                fail(0,"证件类型错误");
                return;
            }
            reader.setCertificatetypeid(certificatetype);
        }
        String certificate = getPara("certificate");
        if(CommonUtils.isNotNullOrNotEmpty(certificate)){
            reader.setCertificate(certificate);
        }
        Calendar calendar = Calendar.getInstance();

        String memo = getPara("memo");
        if(CommonUtils.isNotNullOrNotEmpty(memo)){
            reader.setMemo(memo);
        }
        String createtime = getPara("createtime");
        if(CommonUtils.isNotNullOrNotEmpty(createtime)){
            try {
                Date createdate = format1.parse(createtime);
                reader.setCreatetime(createdate);
            } catch (ParseException e) {
                fail(0,"办证时间格式错误，正确格式：yyyy-MM-dd");
                e.printStackTrace();
                return;
            }
        } else {
            reader.setCreatetime(new Date());
        }
        String losedatestr = getPara("losedate");
        if(CommonUtils.isNotNullOrNotEmpty(losedatestr)){
            try {
                Date losedate = format1.parse(losedatestr);
                reader.setLosedate(losedate);
            } catch (ParseException e) {
                fail(0,"失效时间格式错误，正确格式：yyyy-MM-dd");
                e.printStackTrace();
                return;
            }
        } else {
            calendar.add(Calendar.YEAR,3);
            reader.setLosedate(calendar.getTime());
        }
        reader.setStatus(1);
        reader.save();

        Map dateplatMap = new HashMap();
        dateplatMap.put("orgid",reader.getOrgid()+"");
        dateplatMap.put("realname",reader.getRealname());
        dateplatMap.put("sex",reader.getSex());
        if(CommonUtils.isNotNullOrNotEmpty(reader.getBirthday())){
            dateplatMap.put("birthday",format3.format(reader.getBirthday()));
        }
        dateplatMap.put("readertypeid",reader.getReadertypeid()+"");
        dateplatMap.put("createtime",format3.format(reader.getCreatetime()));
        Thread t = new Thread() {
            public void run() {
                HttpKit.get(PropKit.get("addReaderServiceUrl"), dateplatMap);
            }
        };
        t.start();
        success();
    }

    /**
     * 查询读者信息
     */
    public void findReaderInfo(){
        String secret = getPara("secret");
        if(CommonUtils.isNullOrEmpty(secret)){
            fail(0,"secret不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_org where orgsecret=?",secret);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(0,"secret错误");
            return;
        }
        String cardnumber = getPara("cardnumber");
        if(CommonUtils.isNullOrEmpty(cardnumber)){
            fail(0,"cardnumber不能为空");
            return;
        }
        Record  readerRecord = Db.findFirst("select r.realname,r.cardnumber,r.sex,o.orgname,d.deptname from t_reader r left join t_org o on r.orgid = o.id left join t_org_dept d on r.orgdeptid = d.id where r.cardnumber = ? and r.orgid = ?",cardnumber,record.getInt("id"));
        success(readerRecord);
    }

    /**
     * 查询读者借阅记录
     */
    public void libraryRecords(){
        String secret = getPara("secret");
        if(CommonUtils.isNullOrEmpty(secret)){
            fail(0,"secret不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_org where orgsecret=?",secret);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(0,"secret错误");
            return;
        }
        String cardnumber = getPara("cardnumber");
        if(CommonUtils.isNullOrEmpty(cardnumber)){
            fail(0,"cardnumber不能为空");
            return;
        }
        String title = getPara("title");
        String starttimestamp = getPara("starttimestamp");
        String starttime = "";
        String endtime = "";
        if(CommonUtils.isNotNullOrNotEmpty(starttimestamp)){
            starttime = format1.format(new Date(Long.parseLong(starttimestamp)));
        }
        String endtimestamp = getPara("endtimestamp");
        if(CommonUtils.isNotNullOrNotEmpty(endtimestamp)){
            endtime = format1.format(new Date(Long.parseLong(endtimestamp)));
        }
        String select = "select b.title,b.author,b.publisher,b.isbn,b.typecode,j.status,DATE_FORMAT(j.createtime,'%Y-%m-%d') AS createtime ,DATE_FORMAT(j.returntime,'%Y-%m-%d') AS returntime,j.isoverdue ";
        StringBuffer where = new StringBuffer("from t_jieyue j left join t_reader r on j.readerid = r.id left join t_book_detail d on j.bookdetailid = d.id left join t_book b on d.bookid = b.id where r.orgid = ? and r.cardnumber = ? and j.status in (0,1,2) and j.flag = 0");
        List param = new ArrayList();
        param.add(record.getInt("id"));
        param.add(cardnumber);
        if(CommonUtils.isNotNullOrNotEmpty(title)){
            try {
                title = URLDecoder.decode(title,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                fail(0,"参数错误");
                return;
            }
            where.append(" and b.title like ?");
            param.add("%"+title+"%");
        }
        if(CommonUtils.isNotNullOrNotEmpty(starttime)){
            where.append(" and j.createtime >= ?");
            param.add(starttime);
        }
        if(CommonUtils.isNotNullOrNotEmpty(endtime)){
            where.append(" and j.createtime <= ?");
            param.add(endtime);
        }
        where.append(" order by createtime desc");
        Page page = Db.paginate(this.getParaToInt("pageNumber",1),this.getParaToInt("pageSize",10),select,where.toString(),CommonUtils.listToArray(param));
        success(page);
    }

    /**
     * 查询读者当前再借记录
     */
    public void borrowingRecords(){
        String secret = getPara("secret");
        if(CommonUtils.isNullOrEmpty(secret)){
            fail(0,"secret不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_org where orgsecret=?",secret);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(0,"secret错误");
            return;
        }
        String cardnumber = getPara("cardnumber");
        if(CommonUtils.isNullOrEmpty(cardnumber)){
            fail(0,"cardnumber不能为空");
            return;
        }
        String title = getPara("title");
        String starttimestamp = getPara("starttimestamp");
        String starttime = "";
        String endtime = "";
        if(CommonUtils.isNotNullOrNotEmpty(starttimestamp)){
            starttime = format1.format(new Date(Long.parseLong(starttimestamp)));
        }
        String endtimestamp = getPara("endtimestamp");
        if(CommonUtils.isNotNullOrNotEmpty(endtimestamp)){
            endtime = format1.format(new Date(Long.parseLong(endtimestamp)));
        }
        String select = "select b.title,b.author,b.publisher,b.isbn,b.typecode,DATE_FORMAT(j.createtime,'%Y-%m-%d') AS createtime ,DATE_FORMAT(j.returntime,'%Y-%m-%d') AS returntime,j.isoverdue ";
        StringBuffer where = new StringBuffer("from t_jieyue j left join t_reader r on j.readerid = r.id left join t_book_detail d on j.bookdetailid = d.id left join t_book b on d.bookid = b.id where r.orgid = ? and r.cardnumber = ? and j.status =0 and j.flag = 0");
        List param = new ArrayList();
        param.add(record.getInt("id"));
        param.add(cardnumber);
        if(CommonUtils.isNotNullOrNotEmpty(title)){
            try {
                title = URLDecoder.decode(title,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                fail(0,"参数错误");
                return;
            }
            where.append(" and b.title like ?");
            param.add("%"+title+"%");
        }
        if(CommonUtils.isNotNullOrNotEmpty(starttime)){
            where.append(" and j.createtime >= ?");
            param.add(starttime);
        }
        if(CommonUtils.isNotNullOrNotEmpty(endtime)){
            where.append(" and j.createtime <= ?");
            param.add(endtime);
        }
        where.append(" order by j.createtime desc");
        Page page = Db.paginate(this.getParaToInt("pageNumber",1),this.getParaToInt("pageSize",10),select,where.toString(),CommonUtils.listToArray(param));
        success(page);
    }

    /**
     * 借阅权限
     */
    public void findReaderAuth(){
        String secret = getPara("secret");
        if(CommonUtils.isNullOrEmpty(secret)){
            fail(0,"secret不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_org where orgsecret=?",secret);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(0,"secret错误");
            return;
        }
        String cardnumber = getPara("cardnumber");
        if(CommonUtils.isNullOrEmpty(cardnumber)){
            fail(0,"cardnumber不能为空");
            return;
        }
        Record readerAuthRecord = Db.findFirst("select name,jieyuetianshu,jieyueshuliang,xujiecishu,a.xujietianshu from t_reader_auth a left join t_reader r on a.id = r.readerauthid where r.orgid = ? and r.cardnumber = ?",record.getInt("id"),cardnumber);
        success(readerAuthRecord);
    }

    /**
     * 馆藏查询
     */
    public void queryBookInfo(){
        String secret = getPara("secret");
        if(CommonUtils.isNullOrEmpty(secret)){
            fail(0,"secret不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_org where orgsecret=?",secret);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(0,"secret错误");
            return;
        }
        int orgid = record.getInt("id");
        String isbn = getPara("isbn");
        String title = getPara("title");
        String publisher = getPara("publisher");
        String author = getPara("author");

        String select = "SELECT   a.bookno, typecode,    isbn, title, publisher, edition, author, " +
                "publishdate,  publishaddress,  barcode, status, bookstatus,otherauthor, totalpages, d.library ";
        StringBuilder where = new StringBuilder(" from t_book a left JOIN t_book_plus b ON a.id = b.bookid " +
                " inner JOIN t_book_detail c on a.id=c.bookid" +
                " inner JOIN t_library d  ON c.libraryid = d.id " +
                " where a.orgid =? ");

        List<Object> paramList =new ArrayList<Object>();
        paramList.add(orgid);
        if(CommonUtils.isNotNullOrNotEmpty(title)){
            try {
                title = URLDecoder.decode(title,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                fail(0,"参数错误");
                return;
            }
            where.append(" and title like ? ");
            paramList.add("%"+title+"%");
        }
        if(CommonUtils.isNotNullOrNotEmpty(publisher)){
            try {
                publisher = URLDecoder.decode(publisher,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                fail(0,"参数错误");
                return;
            }
            where.append(" and publisher like ? ");
            paramList.add("%"+publisher+"%");
        }
        if(CommonUtils.isNotNullOrNotEmpty(author)){
            try {
                author = URLDecoder.decode(author,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                fail(0,"参数错误");
                return;
            }
            where.append(" and author like ? ");
            paramList.add("%"+author+"%");
        }

        if (CommonUtils.isNotNullOrNotEmpty(isbn)){
            where.append(" and isbn =? ");
            paramList.add(ISBNTools.fmtisbn(isbn));
        }

        Page page =  Db.paginate(this.getParaToInt("pageNumber",1),this.getParaToInt("pageSize",10),select,where.toString(),paramList.toArray(new Object[0]));
        success(page);
    }

    public void hotTop100(){
        String secret = getPara("secret");
        if(CommonUtils.isNullOrEmpty(secret)){
            fail(0,"secret不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_org where orgsecret=?",secret);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(0,"secret错误");
            return;
        }
        int orgid = record.getInt("id");
        List list = Db.find("SELECT   bookno, typecode,    isbn, title, publisher, edition, author,publishdate,  publishaddress,  barcode, status, bookstatus,jieyuenums from t_book_detail d left join t_book b on d.bookid = b.id where orgid = ? order by jieyuenums desc limit 100",orgid);
        success(list);
    }


    public void updateCardNumber(){
        String secret = getPara("secret");
        if(CommonUtils.isNullOrEmpty(secret)){
            fail(0,"secret不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_org where orgsecret=?",secret);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(0,"secret错误");
            return;
        }
        String oldCardNumber = getPara("oldCardNumber");
        if(CommonUtils.isNullOrEmpty(oldCardNumber)){
            fail(0,"oldCardNumber不能为空");
            return;
        }
        String cardNumber = getPara("cardNumber");
        if(CommonUtils.isNullOrEmpty(cardNumber)){
            fail(0,"cardNumber不能为空");
            return;
        }
        Record checkRecord = Db.findFirst("select count(*) ct from t_reader where  (cardnumber = ? or readcardcode = ?) and orgid = ?",cardNumber,cardNumber,record.getInt("id"));
        if(checkRecord.getInt("ct")>0) {
            fail(0,"新的读者证号重复");
            return;
        }
        int count = Db.update("update t_reader set cardnumber = ?,readcardcode = ? where (cardnumber = ? or readcardcode = ?) and orgid = ?",cardNumber,cardNumber,oldCardNumber,oldCardNumber,record.getInt("id"));
        if(count == 0) {
            fail(0,"修改失败，查询不到读者信息");
        } else {
            success();
        }
    }
}
