package com.service;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.model.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class API_HistoryDataUploadService {

    static Logger logger = Logger.getLogger(API_HistoryDataUploadService.class);
    public static final API_HistoryDataUploadService me = new API_HistoryDataUploadService();
    private Org orgDao = new Org().dao();
    private Book bookDao = new Book();
    private BookDetail bookDetailDao = new BookDetail();

    /**
     * 馆藏
     * 2018-11-15
     * @param orgid
     * @param content
     */
    public void guancang(int orgid,String content){
        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                List contents = JSON.parseArray(content);
                for(int i=0;i<contents.size();i++){
                    Map map = (Map)contents.get(i);
                    String typecode = (String) map.get("typecode");
                    //根据分类号获取所属22大类typeid
                    String typeid = typecode.substring(0,1);
                    //TODO 著作方式存入字典表，book表存入著作方式id workmodeid
                    String workmode = (String) map.get("workmode");
                    Record dict_workmode = Db.findFirst("SELECT * FROM t_dict WHERE type = 0 AND `name` = ?",workmode);
                    int workmodeid = 0;
                    if(dict_workmode!=null){
                        int id = dict_workmode.getInt("id");
                        workmodeid = id;
                    }
                    //TODO 国别朝代
                    String guobie = (String) map.get("guobie");
                    Record dict_guobie = Db.findFirst("SELECT * FROM t_dict WHERE type = 1 AND `name` = ?",guobie);
                    int guobieid = 0;
                    if(dict_guobie!=null){
                        int id = dict_guobie.getInt("id");
                        guobieid = id;
                    }
                    //TODO 尺寸
                    String size = (String) map.get("size");
                    Record dict_size = Db.findFirst("SELECT * FROM t_dict WHERE type = 3 AND `name` = ?",size);
                    int sizeid = 0;
                    if(dict_size!=null){
                        int id = dict_size.getInt("id");
                        sizeid = id;
                    }
                    //TODO 语种
                    String language = (String) map.get("language");
                    Record dict_language = Db.findFirst("SELECT * FROM t_dict WHERE type = 4 AND `name` = ?",language);
                    int languageid = 0;
                    if(dict_language!=null){
                        int id = dict_language.getInt("id");
                        languageid = id;
                    }
                    //TODO 装订形式
                    String binding = (String) map.get("binding");
                    Record dict_binding = Db.findFirst("SELECT * FROM t_dict WHERE type = 5 AND `name` = ?",binding);
                    int bindingid = 0;
                    if(dict_binding!=null){
                        int id = dict_binding.getInt("id");
                        bindingid = id;
                    }
                    //TODO 批次
                    String pici = (String) map.get("pici");
                    Record r_pici = Db.findFirst("SELECT * FROM t_bookpici WHERE batchname = ? AND orgid = ?",pici,orgid);
                    int piciid = 0;
                    if(r_pici!=null){
                        int id = r_pici.getInt("id");
                        piciid = id;
                    }else {
                        //如果t_bookpici不存在该批次信息，则创建一条批次信息
                        Record piciBean = new Record();
                        piciBean.set("batchname",pici).set("orgid",orgid);
                        Db.save("t_bookpici",piciBean);
                        piciid = piciBean.getInt("id");
                    }
                    //book信息
                    Record bookBean = new Record();
                    bookBean.set("orgid",orgid).set("typeid",typeid).set("typecode",typecode).set("title",map.get("title")).set("flag",0)
                            .set("isbn",map.get("isbn")).set("publisher",map.get("publisher")).set("keyword",map.get("keyword")).set("edition",map.get("edition"))
                            .set("author",map.get("author")).set("otherauthor",map.get("otherauthor")).set("publishdate",map.get("publishdate")).set("bookno",map.get("bookno"))
                            .set("publishaddress",map.get("publishaddress")).set("price",map.get("price")).set("moneysource",map.get("moneysource"))
                            .set("createtime",map.get("createtime")).set("operatorid",map.get("operatorid")).set("updatetime",map.get("updatetime"))
                            .set("updateuserid",map.get("updateuserid")).set("createtime",new Date());
                    Db.save("t_book",bookBean);

                    //插入book附加信息
                    Record bookPlusBean = new Record();
                    int bookid = bookBean.getInt("id");
                    bookPlusBean.set("bookid",bookid).set("workmodeid",workmodeid).set("guobieid",guobieid).set("sizeid",sizeid)
                            .set("languageid",languageid).set("bindingid",bindingid).set("subtitle",map.get("subtitle")).set("congshuming",map.get("congshuming"))
                            .set("congshuauthor",map.get("congshuauthor")).set("shucihao",map.get("shucihao")).set("juanci",map.get("juanci"))
                            .set("ceci",map.get("ceci")).set("piciid",piciid).set("createtime",map.get("createtime"));
                    Db.save("t_book_plus",bookPlusBean);

                    //book明细信息
                    List guangcangdi = (List)map.get("mxlist");
                    for(int j=0;j<guangcangdi.size();j++){
                        Map mx = (Map)guangcangdi.get(j);
                        //获取馆藏地 存入t_library
                        String gcd = (String) mx.get("gcd");
                        Record isLibrarys  = Db.findFirst("SELECT id from t_library WHERE library = ? AND orgid = ?",gcd,orgid);
                        Integer islibrary = null;
                        if(isLibrarys!=null){
                            islibrary = isLibrarys.get("id");
                        }
                        //如果传入数据的馆藏地已经拥有，那么获取这条数据的馆藏地id，如果该馆藏地不存在则创建一条馆藏地记录
                        int libraryid = 0;
                        if(islibrary != null){
                            libraryid = islibrary;
                        }else{
                            //创建一条新馆藏记录，并获取新纪录的馆藏地id
                            Library libraryBean = new Library();
                            libraryBean.setOrgid(orgid).setLibrary(gcd).save();
                            libraryid = libraryBean.getId();
                        }
                        //插入t_bookdetail记录
                        Record bookDetailBean = new Record();
                        bookDetailBean.set("bookid",bookid).set("libraryid",libraryid).set("barcode",mx.get("barcode")).set("status",mx.get("status"))
                                .set("bookno",mx.get("bookno")).set("putindate",mx.get("putindate")).set("destroyreason",mx.get("destroyreason")).set("createtime",map.get("createtime"));
                        Db.save("t_book_detail",bookDetailBean);
                    }
                }
                return true;
            }
        });

    }
    //读者
    public void reader(int orgid,String content){
        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                List contents = JSON.parseArray(content);
                for(int i=0;i<contents.size();i++){
                    Map map = (Map) contents.get(i);
                    //部门 如果存在部门记录，则存入部门id，否则创建新部门，并获取新部门id
                    String orgdept = (String) map.get("orgdept");
                    int orgdeptid = 0;
                    if(StringUtils.isNotBlank(orgdept)) {
                        Record r_orgdept = Db.findFirst("SELECT id,deptname,orgid FROM t_org_dept WHERE orgid = ? AND deptname = ?", orgid, orgdept);

                        if (r_orgdept != null) {
                            int id = r_orgdept.getInt("id");
                            orgdeptid = id;
                        } else {
                            OrgDept orgDeptBean = new OrgDept();
                            orgDeptBean.setDeptname(orgdept).setOrgid(orgid).setCreatetime(new Date()).save();
                            orgdeptid = orgDeptBean.getId();
                        }
                    }
                    //借书证类型
                    String cardtype = (String) map.get("cardtype");
                    int cardtypeid = 0;
                    if(StringUtils.isNotBlank(cardtype)) {
                        Record r_cardtype = Db.findFirst("SELECT id,cardtype,orgid FROM t_cardtype WHERE orgid = ? AND cardtype = ?", orgid, cardtype);
                        if (r_cardtype != null) {
                            int id = r_cardtype.getInt("id");
                            cardtypeid = id;
                        } else {
                            Cardtype cardTypeBean = new Cardtype();
                            cardTypeBean.setCardtype(cardtype).setOrgid(orgid).setCreatetime(new Date()).save();
                            cardtypeid = cardTypeBean.getId();
                        }
                    }
                    //证件类型
                    String certificatetype = (String)map.get("certificatetype");
                    int certificatetypeid = 0;
                    if(StringUtils.isNotBlank(certificatetype)) {
                        Record r_certificatetype = Db.findFirst("SELECT * FROM t_dict WHERE type = 7 AND `name` = ?", certificatetype);
                        if (r_certificatetype != null) {
                            int id = r_certificatetype.getInt("id");
                            certificatetypeid = id;
                        }
                    }
                    Record readerBean = new Record();
                    readerBean.set("orgid",orgid).set("orgdeptid",orgdeptid).set("cardtypeid",cardtypeid).set("cardnumber",map.get("cardnumber"))
                            .set("realname",map.get("realname")).set("password",map.get("password")).set("sex",map.get("sex")).set("birthday",map.get("birthday"))
                            .set("certificatetypeid",certificatetypeid).set("certificate",map.get("certificate")).set("phone",map.get("phone")).set("email",map.get("email"))
                            .set("deposit",map.get("deposit")).set("balance",map.get("balance")).set("losedate",map.get("losedate")).set("status",map.get("status"))
                            .set("createtime",map.get("createtime"));

                    Db.save("t_reader",readerBean);
                }
                return true;
            }
        });
    }
    //流通
    public void jieyue(int orgid,String content){
        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                List contents = JSON.parseArray(content);
                for(int i=0;i<contents.size();i++){
                    Map map = (Map) contents.get(i);
                    //借书证号
                    String reader = (String) map.get("reader");
                    Record r_reader = Db.findFirst("SELECT id FROM t_reader WHERE cardnumber = ?",reader);
                    int readerid = 0;
                    if(r_reader!=null){
                        int id = r_reader.getInt("id");
                        readerid = id;
                    }
                    //条形码，根据条形码获取book明细id
                    String barcode = (String) map.get("barcode");
                    Record r_bookDetail = Db.findFirst("SELECT id FROM t_book_detail WHERE barcode = ?",barcode);
                    int detailid = 0;
                    if(r_bookDetail!=null){
                        int id = r_bookDetail.getInt("id");
                        detailid = id;
                    }
                    Record jieyueBean = new Record();
                    jieyueBean.set("readerid",readerid).set("bookdetailid",detailid).set("flag",0).set("status",map.get("status"))
                            .set("createtime",map.get("createtime"));
                    Db.save("t_jieyue",jieyueBean);
                }
                return true;
            }
        });
    }

    public static void main(String[] args) {


//        Map map = new HashMap();
//        Record bookBean = new Record();
//        bookBean.set("orgid",orgid).set("typeid",typeid).set("typecode",typecode).set("title",map.get("Ztm")).set("flag",0)
//                .set("isbn",map.get("isbn")).set("publisher",map.get("publisher")).set("keyword",map.get("keyword")).set("edition",map.get("edition"))
//                .set("author",map.get("author")).set("otherauthor",map.get("otherauthor")).set("publishdate",map.get("publishdate")).set("bookno",map.get("bookno"))
//                .set("publishaddress",map.get("publishaddress")).set("price",map.get("price")).set("moneysource",map.get("moneysource"))
//                .set("createtime",map.get("createtime")).set("operatorid",map.get("operatorid")).set("updatetime",map.get("updatetime"))
//                .set("updateuserid",map.get("updateuserid")).set("createtime",new Date());
//        Db.save("t_book",bookBean);
    }
}
