package com.bohuikeji.frame.module.admin.base;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bohuikeji.frame.module.admin.easypdf.util.PdfUtil;
import com.bohuikeji.frame.module.admin.entity.configure.PageConf;
import com.bohuikeji.frame.module.admin.entity.sys.SysMenu;
import com.bohuikeji.frame.module.admin.entity.sys.SysPage;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.entity.vo.TableDataVo;
import com.bohuikeji.frame.module.admin.entity.web.TableInit;
import com.bohuikeji.frame.module.admin.entity.web.TableSearsh;
import com.bohuikeji.frame.module.admin.entity.web.block.ButtonBlock;
import com.bohuikeji.frame.module.admin.entity.web.template.TableTemplate;
import com.bohuikeji.frame.module.admin.service.ISysPageService;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 处理表格组件的查询、搜索、分页等
 * @author 10552
 */
@Slf4j
public class PageTemplateControllerBase extends ControllerBase{
    @Autowired
    ISysPageService pageService;
    /**
     * 创建页面模板
     * @param clazz
     * @return
     */
    protected PageTemplateBase createPage(Class<? extends PageTemplateBase> clazz){
        SysMenu menu=(SysMenu)session.getAttribute("activeMenu");
        if (menu.getPageId()!=null){
            SysPage sysPage=pageService.getById(menu.getPageId());
            session.setAttribute("activePage",sysPage);
            log.info("使用配置文件模式，配置项名称：[{}]，配置项id:[{}]",sysPage.getPageName(),sysPage.getPageId());
            return sysPage.getPageConf().createTemplate();
        }
        else{
            session.setAttribute("activePage",null);
            TableTemplate page;
            page=new TableTemplate();
            EntityBase entity= crateEntityByName(menu.getModel());
            if (entity==null){
                new RuntimeException("无法创建页面模板");
            }
            page.setBatchButton(ButtonBlock.createButtons());
            page.setTableHeads(entity.forTableHeadAndConfig());

            TableInit tableInit=TableInit.getDefaultStyle();
            tableInit.setDataIdField(entity.forIdField().getName());
            page.setTableInit(tableInit.forParamStr());

            page.setTableQuery(entity.forTableQueryBlocks());
            page.setTableSearch(entity.foeTableSearch());
            page.setTableModel(entity.forTableModel());
            return page;
        }

    }

    protected PageTemplateBase byteCreatePage(Class<? extends PageTemplateBase> clazz){
        SysMenu menu=(SysMenu)session.getAttribute("activeMenu");
        if (menu.getPageId()!=null){
            SysPage sysPage=pageService.getById(menu.getPageId());
            session.setAttribute("activePage",sysPage);
            log.info("使用配置文件模式，配置项名称：[{}]，配置项id:[{}]",sysPage.getPageName(),sysPage.getPageId());
            return sysPage.getPageConf().createTemplate();
        }
        else{
            session.setAttribute("activePage",null);
            TableTemplate page;
            page=new TableTemplate();
            EntityBase entity= crateEntityByName(menu.getModel());
            if (entity==null){
                new RuntimeException("无法创建页面模板");
            }
            page.setBatchButton(ButtonBlock.createButtons());
            page.setTableHeads(entity.forTableHeadAndConfig());

            TableInit tableInit=TableInit.getDouyinStyle();
            tableInit.setDataIdField(entity.forIdField().getName());
            page.setTableInit(tableInit.forParamStr());

            page.setTableQuery(entity.forTableQueryBlocks());
            page.setTableSearch(entity.foeTableSearch());
            page.setTableModel(entity.forTableModel());
            return page;
        }

    }

    /**
     * 测试方法
     * @return
     */
    /*protected PageTemplateBase createPageTest(PageConf conf){
        TableTemplate page=new TableTemplate();
        page.setBatchButton(ButtonBlock.createButtons());
        page.setTableHeads(entity.forTableHeadAndConfig());


    }*/
    /**
     * 创建实体查询对象
     * @return
     */
        protected <T extends EntityBase<T>> QueryWrapper<T> createQueryAndSearchByParam(Map<String,String> queryParam,Map<String,String> searchParam){
        /**
         * 此写的有问题，没有实现模板的解耦，后续修改
         * 从session中获取的对象必须克隆一份,由于session存储对象引用，修改对象本身同时改变session中对象属性
         */
        QueryWrapper<T> query=(((TableTemplate<T>)session.getAttribute("pageTemplate")).getQueryWrapper()).clone();
        if(queryParam==null){
            return query;
        }
        for (Map.Entry<String, String> entry : queryParam.entrySet()) {
            if (StringUtils.isBlank(entry.getValue().toString()))continue;
            String[] dateGroup=StringUtils.getDateGroupByStr(entry.getValue().toString());
            if (dateGroup!=null){
                query.between("DATE_FORMAT("+entry.getKey()+",'%Y-%m-%d')",dateGroup[0],dateGroup[1]);
                continue;
            }
            query.eq(entry.getKey(),entry.getValue().toString());
        }
        EntityBase<T> entity=crateActiveEntity();
        if (entity==null){
            return query;
        }
        if (StringUtils.isBlank(searchParam.get("name"))){
            return query;
        }
        query.and(i ->{
            if (StringUtils.isBlank(searchParam.get("key"))){
                List<TableSearsh> list=entity.foeTableSearch();
                for (TableSearsh searsh:list){
                    i.like(searsh.getKey(),searchParam.get("name")).or();
                }
                return i;
            }
            i.like(searchParam.get("key"),searchParam.get("name"));
            return i;
        });
        return query;
    }

    /**
     * 获取分页对象
     * 该方法已废弃，请使用getPage(TableDataVo)
     * @param json
     * @return
     */
    @Deprecated
    protected Page getPageByJson(JSONObject json){
        //创建分页对象
        Page page=new Page(((json.getInteger("offset"))/json.getInteger("pageSize")+1),json.getInteger("pageSize"));
        String sortColumn=json.getString("sort");
        //如果未设置排序对象则默认为ID倒叙
        if(StringUtils.isBlank(sortColumn)){
            page.setDesc(crateActiveEntity().forIdColumn());
            return page;
        }
        EntityBase activeEntity=crateActiveEntity();
        if("desc".equals(json.getString("sortOrder"))){
            page.setDesc(activeEntity.forColumnByFieldName(sortColumn));
        }
        else{
            //page.setDesc(activeEntity.forIdColumn());
            page.setAsc(activeEntity.forColumnByFieldName(sortColumn));
        }
        return page;
    }

    /**
     * 获取分页对象
     * @param dataVo
     * @return
     */
    protected Page getPage(TableDataVo dataVo){
        Page page=new Page((dataVo.getOffset()/(dataVo.getPageSize())+1),dataVo.getPageSize());
        String sortColumn=dataVo.getSort();
        if(StringUtils.isBlank(sortColumn)){
            page.setDesc(crateActiveEntity().forIdColumn());
            return page;
        }
        EntityBase activeEntity=crateActiveEntity();
        if("desc".equals(dataVo.getSortOrder())){
            page.setDesc(activeEntity.forColumnByFieldName(sortColumn));
        }
        else{
            page.setAsc(activeEntity.forColumnByFieldName(sortColumn));
        }
        return page;
    }

    /**
     * 导出Excel
     * @param ids
     * @param response
     * @throws IOException
     */
    protected void exportExcel(Integer[] ids, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(System.currentTimeMillis()+".xlsx","UTF-8"));
        EntityBase entityBase=crateActiveEntity();
        List<EntityBase> list=ids.length<1?entityBase.selectAll():entityBase.selectList(new QueryWrapper<EntityBase>().in(entityBase.forIdColumn(),ids));
        List<List<String>> rowList=new ArrayList<>(list.size());
        for (EntityBase t:list){
            rowList.add(t.forExcelFields());
        }
        EasyExcel.write(response.getOutputStream()).head(entityBase.forExcelHeads()).sheet("数据导出").doWrite(rowList);
    }


}
