package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.model.*;
import com.service.OrgService;
import com.service.ReaderService;
import com.service.UserService;
import com.tools.JwtUtils;
import com.utils.CommonUtils;
import com.utils.DateUtils;
import com.utils.ExcelUtil;
import com.validator.OrgValidator;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 机构
 * 2018-10-16
 * zj
 */
@ControllerInterface(path="/org")
public class OrgController extends BaseController {
    User userDao = new User().dao();
    Org dao = new Org().dao();
    OrgService service = OrgService.me;
    OrgSetting orgSettingDao = new OrgSetting().dao();
    UserService userService = UserService.me;

    //本单位信息
    public void thisUnit(){
        try{
            Integer orgid = this.getParaToInt("orgid");
            if(orgid == null){
                orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            }
            success(service.thisUnit(orgid));
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }


    public void getById(){
        int id =this.getParaToInt("bean.id", 0);
        if(id == 0){
            fail();
            return;
        }
        Org org = service.findById(id);
        org.put("banben",PropKit.get("banben"));
        success(org);
    }


    //删除
    public void delete(){

        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int id = getParaToInt("id");
        Org org = service.findById(id);

        User currentUser=userService.findById(operatorid);

        if(currentUser.getOrgid().intValue() != org.getParentid().intValue()) {
            fail(5,"没有权限注销用户");
            return;
        } else {
            service.deleteById(this.getParaToInt("id", 0));
            success();
        }
    }

    //密码重置，传入t_user表id，从列表中获取

    public void passWordReset(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int id = getParaToInt("fid");
        Org org = service.findById(id);
        //select ifnull(LOCATE((select orgid from t_user where id =3093 ),parentcodes),0) checkFlag from t_org o inner join t_user u on u.orgid = o.id where u.id = 318

        User currentUser=userService.findById(operatorid);
        if(currentUser.getOrgid().intValue() != org.getParentid().intValue()) { // 如果被重置密码的部门跟当前登录人的部门不一样 则不允许重置密码
            fail(5,"没有权限重置密码");
            return;
        } else {
            String password = CommonUtils.getMD5String(CommonUtils.getMD5String(PropKit.get("initPassword")));
            service.passWordReset(password,id);
            success(PropKit.get("initPassword"));
        }
    }
    //机构模糊查询
    public void fuzzyFindOrg(){
        try {
            Integer orgid = this.getParaToInt("orgid");
            String content = this.getPara("content");
            Integer schoolcategoryid = this.getParaToInt("schoolcategoryid");
            success(service.fuzzyFindOrg(orgid,content,schoolcategoryid));
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }
    //测试用
    public void getSchoolForSql(){
        String token = this.getPara("token");
        try {
            int operatorid = JwtUtils.validateJWTForUserId(token);
            success(service.getSchoolForSql(operatorid));
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }


    public void orgreport(){
        Integer orgid = this.getParaToInt("orgid");
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        success(service.orgreport(orgid));
    }

    public void uploadorginfopage(){
        render("/view/uploadorginfo/uploadorginfopage.html");
    }

    public void uploadorginfo(){
        UploadFile file = getFile();
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0) {
            fail(0,"权限异常");
            return;
        }
        User user = (User)getSession().getAttribute("userInfo");
        Integer parentorgid = user.getOrgid();
        if(CommonUtils.isNullOrEmpty(parentorgid)){
            fail(0,"父级机构id不能为空");
            return;
        }
        List<Map<String,String>> errorDataList = new ArrayList<Map<String,String>>();
        try {
            List<Map<String,String>> orgList= readExcel(new FileInputStream(file.getFile()));
            for(Map map : orgList) {
                if (CommonUtils.isNullOrEmpty(map.get("org"))){
                    map.put("未导入原因","org不能为空!");
                    errorDataList.add(map);
                    continue;
                }
                if (CommonUtils.isNullOrEmpty(map.get("school"))){
                    map.put("未导入原因","school不能为空!");
                    errorDataList.add(map);
                    continue;
                }
                if (CommonUtils.isNullOrEmpty(map.get("schoolcategoryid"))){
                    map.put("未导入原因","schoolcategoryid不能为空!");
                    errorDataList.add(map);
                    continue;
                }
                if (CommonUtils.isNullOrEmpty(map.get("areatypeid"))){
                    map.put("未导入原因","areatypeid不能为空!");
                    errorDataList.add(map);
                    continue;
                }
                List<Record> list = Db.find("select * from t_org where orgname = ? and parentid = ?",map.get("org")+"教育局",parentorgid);
                try{
                    if(list.size() > 0) {
                        Record record = list.get(0);
                        zuzhuang(record.getInt("id"),map.get("school").toString(),
                                Integer.parseInt(map.get("areatypeid").toString()),
                                Integer.parseInt(map.get("schoolcategoryid").toString()));
                    } else {
                        Org org = zuzhuang(parentorgid,map.get("org")+"教育局",
                                Integer.parseInt(map.get("areatypeid").toString()),
                                Integer.parseInt(map.get("schoolcategoryid").toString()));

                        zuzhuang(org.getId(),map.get("school").toString(),
                                Integer.parseInt(map.get("areatypeid").toString()),
                                Integer.parseInt(map.get("schoolcategoryid").toString()));
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    map.put("未导入原因",e.getMessage());
                    errorDataList.add(map);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String filename="";
        if (errorDataList.size()>0){
            filename="未导入列表"+ DateUtils.getNowTimeNo()+".xls";
            File targetFile =new File(getRequest().getRealPath("upload")+ File.separator+filename);
            ExcelUtil.writeExcel(targetFile,errorDataList,"未导入列表");
        }
        success(filename);
    }

    public Org zuzhuang(int uOrgid,String orgname,int areatypeid,int schoolcategoryid){
        Org bean = new Org();
        bean.setOrgname(orgname);
        Org o = dao.findById(uOrgid);
        if(CommonUtils.isNotNullOrNotEmpty(o)){
            String parentcodes = o.getParentcodes();
            String p = parentcodes+uOrgid+",";
            bean.setParentid(uOrgid).setParentcodes(p);

            if(o.getOrgtypeid() < 3){
                bean.setOrgtypeid(o.getOrgtypeid()+1);
            } else {
                bean.setOrgtypeid(5);
            }
        }else {
            bean.setParentid(0).setParentcodes("0");
        }
        bean.setStatus(1);
        if (bean.getOrgtypeid()==5) {
            bean.setAreatypeid(areatypeid).setSchoolcategoryid(schoolcategoryid);
        }
        bean.setCreatetime(new Date()).setOperatorid(99999).save();
        //创建一个新机构的同时，生成一个所创建机构的超级管理员账号 t_user
        User user = new User();
        //初始密码123456
        user.setIsadmin(1).setStatus(1).setRealname(bean.getOrgname()).setPhone(bean.getLinkphone()).setPassword(CommonUtils.getMD5String(CommonUtils.getMD5String(PropKit.get("initPassword")))).setOrgid(bean.getId()).setOperatorid(99999).setCreatetime(new Date()).save();

        RoleUser roleUser = new RoleUser();
        roleUser.setRoleid(bean.getOrgtypeid().equals(1)?2:bean.getOrgtypeid().equals(2)?3:bean.getOrgtypeid().equals(3)?4:bean.getOrgtypeid().equals(5)?5:-1);
        roleUser.setUserid(user.getId());
        roleUser.setCreatetime(new Date());
        roleUser.setOperatorid(99999);
        roleUser.save();

        String orgids = ReaderService.codeAddOne(bean.getId(),6);
        String cardnumber = (orgids+user.getId()).trim();
        Db.update("update t_user set code = ?,loginname = ? where id = ? ",cardnumber,cardnumber,user.getId());

        if (bean.getOrgtypeid()==5){
            new Library().setOrgid(bean.getId()).setOperatorid(bean.getOperatorid()).setLibrary("基本书库").setCreatetime(new Date()).save();
            new Library().setOrgid(bean.getId()).setOperatorid(bean.getOperatorid()).setLibrary("教师书库").setCreatetime(new Date()).save();
            new Library().setOrgid(bean.getId()).setOperatorid(bean.getOperatorid()).setLibrary("工具书库").setCreatetime(new Date()).save();

            new OrgSetting().setOrgid(bean.getId()).setTstiaoxinmaweishu(8).setQktiaoxingmaweishu(7).setJieshuzhengweishu(6).save();

            OrgBookField orgBookField = new OrgBookField();
            orgBookField.setOrgid(bean.getId()).setKeyword(0).setEdition(0).setOtherauthor(0).setNewsource(0)
                    .setBltitle(0).setSubtitle(0).setWorkmode(0).setGuobie(0).setSize(0).setLanguage(0).setBinding(0)
                    .setCongshuming(0).setCongshuauthor(0).save();
        }
        logger.info("创建机构完成 orgname:"+bean.getOrgname());
        return bean;
    }

    public List<Map<String,String>> readExcel(InputStream in){
        List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
        try{
            // 获得工作簿
            Workbook workbook = WorkbookFactory.create(in);
            // 获得工作表个数
            int sheetCount = workbook.getNumberOfSheets();
            // 遍历工作表
            for (int i = 0; i < sheetCount; i++)
            {
                Sheet sheet = workbook.getSheetAt(i);
                // 获得行数
                int rows = sheet.getLastRowNum() + 1;
                // 读取数据
                for (int rownum = 1; rownum < rows; rownum++)                {
                    Map<String,String> rowMap = new LinkedHashMap<String, String>();
                    Row r = sheet.getRow(rownum);
                    if(r ==null) continue;
                    boolean flag = false; //行数据全部为空，不继续读
                    for (int col = 0; col < sheet.getRow(2).getLastCellNum(); col++)
                    {
                        Cell cell = r.getCell(col);
                        if(cell !=null){
                            String value = getCellValue(cell);
                            if (!"".equals(value.trim())){
                                flag=true;
                            }
                            rowMap.put(getCellValue(sheet.getRow(0).getCell(col)),value);
                        }else {
                            rowMap.put(getCellValue(sheet.getRow(0).getCell(col)),"");
                        }

                    }
                    if (flag){
                        dataList.add(rowMap);
                    }
                }
            }
        }catch (Exception e) {
        }
        return dataList;
    }

    public String getCellValue(Cell cell){
        if(cell.getCellType() == CellType.NUMERIC){
            short format = cell.getCellStyle().getDataFormat();
            SimpleDateFormat sdf = null;
            if(format == 14 || format == 31 || format == 57 || format == 58){
                //日期
                sdf = new SimpleDateFormat("yyyy-MM-dd");
            }else if (format == 20 || format == 32) {
                //时间
                sdf = new SimpleDateFormat("HH:mm");
            }else { // 不是日期格式
                NumberFormat nf = NumberFormat.getInstance();
                String s = nf.format(cell.getNumericCellValue());
                if (s.indexOf(",") >= 0) {
                    s = s.replace(",", "");
                }
                return s;
            }
            double value = cell.getNumericCellValue();
            Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
            return sdf.format(date);
        } else if (cell.getCellType() == CellType.BOOLEAN){
            return cell.getBooleanCellValue()+"";
        }else {
            return cell.getStringCellValue();
        }

    }

    //用于单独同步机构信息
    @Clear
    public void sycorginfo(){
        List<Record> list = Db.find("select id from t_org where orgtypeid = 2 and status = 1");
        logger.info("开始同步机构信息"+list.size());
        for(Record record:list) {
            SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Org org = dao.findById(record.getInt("id"));
            logger.info("org:"+org.toJson());
            Map map = new HashMap();
            map.put("orgid",org.getId().toString());
            map.put("orgname",org.getOrgname());
            map.put("status",org.getStatus().toString());
            map.put("plattype","1");
            map.put("orgtypeid",org.getOrgtypeid().toString());
            map.put("parentid", org.getParentid().toString());
            map.put("parentcodes",org.getParentcodes());
            if(CommonUtils.isNotNullOrNotEmpty(org.getRffectivetime())){
                map.put("rffectivetime",format3.format(org.getRffectivetime()));
            }
            if(CommonUtils.isNotNullOrNotEmpty(org.getCreatetime())){
                map.put("orgcreatetime",format3.format(org.getCreatetime()));
            }
            HttpKit.get(PropKit.get("createOrgLogServiceUrl"), map);
        }
        success();
    }

}
