package com.crunii.micro.service.sysmgr.jdbc;

import com.alibaba.fastjson.JSONObject;
import com.crunii.micro.common.dto.PageReq;
import com.crunii.micro.common.dto.PageRsp;
import com.crunii.micro.common.utils.SqlUtil;
import com.crunii.micro.domain.common.jdbc.BaseJdbcTemplate;
import com.crunii.micro.domain.common.jdbc.BaseNPJdbcTemplate;
import com.crunii.micro.domain.dto.Worker;
import com.crunii.micro.domain.entity.main.YcqRollPic;
import com.crunii.micro.domain.util.CurrWorkerUtil;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqPageRollPicDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqRollPicDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqRollPicUrl;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqRollPicVO;
import com.crunii.micro.service.sysmgr.dto.sysmgr.AccessPageVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Repository
public class YcqRollPicDao {

    @Resource(name = "mainJT")
    protected BaseJdbcTemplate JT;

    @Resource(name = "mainNPJT")
    protected BaseNPJdbcTemplate NPJT;

    private static final String COUNT_BY_CONDITION_SQL = "select count(*) from YCQ_ROLL_PIC where del_flag = 0 and  LOCATION = ? and SECOND_LOCATION = ? ";
    private static final String QUERY_BY_CONDITION_SQL = "select * from YCQ_ROLL_PIC where del_flag = 0 and status = 2 and system_id = ? and location_id = ?";

    private static final String PAGE_BASE_QUERY = "select * from YCQ_ROLL_PIC where del_flag = 0 ";
    private static final String PAGE_BASE_COUNT_QUERY = "select count(*) from YCQ_ROLL_PIC where del_flag = 0 ";


    private static final String TYPE_SQL = "select distinct e.app_id,app_code, e.app_name " +
            "from TSM_WORKER a,TSM_ROLE b,TSM_WORKER_ROLE c,TSM_ROLE_APP d,ycq_app_config_url e " +
            "where c.login_id=a.login_id " +
            "  and c.role_id=b.role_id " +
            "  and a.login_id= ? " +
            "  and d.role_id=b.role_id " +
            "  and e.app_id=d.app_id ";

    private static final String HAVA_ABILITY_SQL = "select count(*) from TSM_WORKER a,TSM_ROLE b,TSM_WORKER_ROLE c " +
            "where c.login_id=a.login_id " +
            "  and c.role_id=b.role_id " +
            "  and a.login_id= ? " +
            "  and role_name='app首页轮播图'";

    public int exist( String location, String secondLocation) {
        return JT.queryForInt(COUNT_BY_CONDITION_SQL, location, secondLocation);
    }

    public YcqRollPic queryByCondition(Integer systemId, Integer locationId) {
        return JT.queryForBean(YcqRollPic.class, QUERY_BY_CONDITION_SQL, systemId, locationId);
    }

    public PageRsp<YcqRollPicVO> pageQuery(PageReq<YcqPageRollPicDTO> pageRequest) {
        String pageSql = "select * " +
                "from ( " +
                "         [str] " +
                "         select * from YCQ_ROLL_PIC where del_flag = 0 and SECOND_LOCATION is not null [secondLocation]" +
                "     ) where 1=1 ";
        String pageCountSql = "select count(*) " +
                "from ( " +
                "         [str] " +
                "         select * from YCQ_ROLL_PIC where del_flag = 0 and SECOND_LOCATION is not null [secondLocation] " +
                "     ) where 1=1 ";
        List<Object> typeParams = new ArrayList<>();
        Worker currWorker = CurrWorkerUtil.getCurrWorker();
//        Worker currWorker = new Worker();
//        currWorker.setLoginId(10763);
//        currWorker.setWorkerName("test");
        typeParams.add(currWorker.getLoginId());
        int num = JT.queryForInt(HAVA_ABILITY_SQL, typeParams.toArray());
        if (num > 0) {
            pageSql = pageSql.replace("[str]", "select * from YCQ_ROLL_PIC where del_flag = 0 and  SECOND_LOCATION is null union all ");
            pageCountSql = pageCountSql.replace("[str]", "select * from YCQ_ROLL_PIC where del_flag = 0 and  SECOND_LOCATION is null union all ");
        } else {
            pageSql = pageSql.replace("[str]", "");
            pageCountSql = pageCountSql.replace("[str]", "");
        }

        StringBuilder typeStr = new StringBuilder(TYPE_SQL);
        List<AccessPageVo> types = JT.queryForBeans(AccessPageVo.class, typeStr.toString(), typeParams.toArray());
        if (types != null && types.size() > 0) {
            String str = "";
            for (AccessPageVo accessPageVo : types) {
                str += "'" + accessPageVo.getAppCode() + "' , ";
            }
            int lastIndex = str.lastIndexOf(",");
            if (lastIndex != -1) { // 如果字符串中存在逗号
                str = str.substring(0, lastIndex) + str.substring(lastIndex + 1);
            }
            str = " and LOCATION in ( " + str + " ) ";
            pageSql = pageSql.replace("[secondLocation]", str);
            pageCountSql = pageCountSql.replace("[secondLocation]", str);
        }else {
            if (num>0){
                pageSql = pageSql.replace("[secondLocation]", "  and id < 0 ");
                pageCountSql = pageCountSql.replace("[secondLocation]", " and id < 0 ");
            }else {
                PageRsp<YcqRollPicVO> page = new PageRsp<>();
                page.setPageNo(pageRequest.getPageNo());
                page.setPageSize(pageRequest.getPageSize());
                page.setTotalNum(0);
                page.setResult(new ArrayList<>());
                page.next();
                return page;
            }

        }
        StringBuilder base = new StringBuilder(pageSql);
        StringBuilder countStr = new StringBuilder(pageCountSql);
        YcqPageRollPicDTO query = pageRequest.getQuery();
        List<Object> params = new ArrayList<>();
        String location = query.getLocation();
        String secondLocation = query.getSecondLocation();
        if (StringUtils.isNotBlank(location)) {
            base.append(" and location like concat('%',?,'%') ");
            countStr.append(" and location like concat('%',?,'%') ");
            params.add(location);
        }
        if (StringUtils.isNotBlank(secondLocation)) {
            base.append(" and SECOND_LOCATION = ?  ");
            countStr.append(" and SECOND_LOCATION = ?  ");
            params.add(secondLocation);
        }
        Integer status = query.getStatus();
        if (null != status && status == 0) {
            base.append(" and status in(2, 1)");
            countStr.append(" and status in(2, 1)");
        } else if (null != status) {
            base.append(" and status = ?");
            countStr.append(" and status = ?");
            params.add(status);
        }
        Integer systemId = query.getSystemId();
        if (null != systemId) {
            base.append(" and system_id = ?");
            countStr.append(" and system_id = ?");
            params.add(systemId);
        }
        int total = JT.queryForInt(countStr.toString(), params.toArray());
        List<YcqRollPicVO> values = new ArrayList<>(pageRequest.getPageSize());
        String dbType = JT.getDbType();
        if (total > 0) {
            //根据数据库类型设置limit
            SqlUtil.appendLimit(dbType, params, base, pageRequest);
            List<YcqRollPic> ycqRollPicList = JT.queryForBeans(YcqRollPic.class, base.toString(), params.toArray());
            ycqRollPicList.forEach(item -> {
                YcqRollPicVO ycqRollPicVO = new YcqRollPicVO();
                BeanUtils.copyProperties(item, ycqRollPicVO);
                ycqRollPicVO.setPicUrls(this.convertPic(item.getPicUrls()));
                values.add(ycqRollPicVO);
            });
        }
        PageRsp<YcqRollPicVO> page = new PageRsp<>();
        page.setPageNo(pageRequest.getPageNo());
        page.setPageSize(pageRequest.getPageSize());
        page.setTotalNum(total);
        page.setResult(values);
        page.next();
        return page;
    }

    public List<AccessPageVo> getTypeList() {
        List<Object> typeParams = new ArrayList<>();
        List<AccessPageVo> result=new ArrayList<>();
        AccessPageVo one=new AccessPageVo();
        one.setAppCode("1");
        one.setAppName("APP");
        AccessPageVo two=new AccessPageVo();
        two.setAppCode("2");
        two.setAppName("Web");
        result.add(one);
        result.add(two);
//        Worker currWorker = CurrWorkerUtil.getCurrWorker();
        Worker currWorker = new Worker();
        currWorker.setLoginId(9999);
        currWorker.setWorkerName("test");
        typeParams.add(currWorker.getLoginId());
        StringBuilder typeStr = new StringBuilder(TYPE_SQL);
        List<AccessPageVo> types = JT.queryForBeans(AccessPageVo.class, typeStr.toString(), typeParams.toArray());
        if (types!=null&&types.size()>0){
            result.addAll(types);
        }

        return result;
    }

    private List<YcqRollPicUrl> convertPic(String picUrls) {
        if (StringUtils.isBlank(picUrls)) {
            return Collections.emptyList();
        }
        return JSONObject.parseArray(picUrls, YcqRollPicUrl.class);
    }

    public YcqRollPic getYcqRollPicByType(YcqRollPicDTO query) {

        StringBuilder base = new StringBuilder(PAGE_BASE_QUERY);
        StringBuilder countStr = new StringBuilder(PAGE_BASE_COUNT_QUERY);
        List<Object> params = new ArrayList<>();
        String location = query.getLocation();
        String secondLocation = query.getSecondLocation();

        if (StringUtils.isNotBlank(location)) {
            base.append(" and location like concat('%',?,'%') ");
            countStr.append(" and location like concat('%',?,'%') ");
            params.add(location);
        }

        if (StringUtils.isNotBlank(secondLocation)) {
            base.append(" and SECOND_LOCATION like concat('%',?,'%') ");
            countStr.append(" and SECOND_LOCATION like concat('%',?,'%') ");
            params.add(secondLocation);
        }

        Integer systemId = query.getSystemId();
        if (null != systemId) {
            if (null != systemId) {
                base.append(" and system_id = ?");
                countStr.append(" and system_id = ?");
                params.add(systemId);
            }
        }

        List<YcqRollPicVO> values = new ArrayList<>();
        List<YcqRollPic> ycqRollPicList = JT.queryForBeans(YcqRollPic.class, base.toString(), params.toArray());
        if (ycqRollPicList != null && ycqRollPicList.size() > 0) {
            ycqRollPicList.forEach(item -> {
                YcqRollPicVO ycqRollPicVO = new YcqRollPicVO();
                BeanUtils.copyProperties(item, ycqRollPicVO);
                ycqRollPicVO.setPicUrls(this.convertPic(item.getPicUrls()));
                values.add(ycqRollPicVO);
            });
            return ycqRollPicList.get(0);
        }

        return null;
    }
}
