package com.gree.mall.manager.logic.comlist;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.es.CommonListES;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.es.EsLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.utils.oss.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WorkerComListLogic {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    OSSUtil ossUtil;
    @Autowired
    EsLogic esLogic;
    @Autowired
    WorkerComListService workerComListService;
    @Autowired
    WorkerComListWorkerService workerComListWorkerService;
    @Autowired
    WorkerComListWebsitService workerComListWebsitService;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    WebsitUserService websitUserService;


    /**
     * 列表
     */
    public IPage<WorkerComList> list(String workerNumber, String title, Boolean status, String remark, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> comListIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(workerNumber)) {
            //师傅编号不为空以师傅为准
            List<WorkerComListWorker> worker = workerComListWorkerService.lambdaQuery()
                    .eq(WorkerComListWorker::getWorkerComListWorkerNumber, workerNumber).list();
            if (CollectionUtils.isEmpty(worker)) {
                return new Page<>(pageNum, pageSize);
            }
            comListIds = worker.stream().map(WorkerComListWorker::getWorkerComListId).distinct().collect(Collectors.toList());
        } else {
            //以登录人为准
            List<WebsitUser> websitUsers = websitUserService.lambdaQuery()
                    .in(!CollectionUtils.isEmpty(adminUser.getAdminWebsitIds()),WebsitUser::getWebsitId, adminUser.getAdminWebsitIds())
                    .isNotNull(WebsitUser::getWorkerNumber)
                    .select(WebsitUser::getWorkerNumber).list();
            List<String> collect = websitUsers.stream().map(WebsitUser::getWorkerNumber).collect(Collectors.toList());

            List<WorkerComListWebsit> websit = workerComListWebsitService.lambdaQuery()
                    .in(!CollectionUtils.isEmpty(collect),WorkerComListWebsit::getWebsitId,collect)
                    .list();
            if (CollectionUtils.isEmpty(websit)) {
                return new Page<>(pageNum, pageSize);
            }
            comListIds = websit.stream().map(WorkerComListWebsit::getWorkerComListId).distinct().collect(Collectors.toList());
        }
        IPage<WorkerComList> page = workerComListService.lambdaQuery()
                .like(StringUtils.isNotEmpty(title), WorkerComList::getTitle, title)
                .eq(status != null, WorkerComList::getStatus, status)
                .like(StringUtils.isNotEmpty(remark), WorkerComList::getRemark, remark)
                .in(!CollectionUtils.isEmpty(comListIds), WorkerComList::getId, comListIds)
                .orderByDesc(WorkerComList::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
        return page;
    }

    /**
     * 删除
     */
    public void delete(String id) {
        workerComListService.removeById(id);
    }

    /**
     * 修改状态
     */
    public void updateStatus(String id, Boolean status) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WorkerComList workerComList = new WorkerComList();
        workerComList.setId(id);
        workerComList.setStatus(status);
        workerComList.setUpdateBy(adminUser.getNickName());
        workerComList.setUpdateTime(new Date());
        workerComList.updateById();
    }

    /**
     * 保存师傅通用列表
     */
    @Transactional
    public void save(String title, String remark, String fileUrl) throws NoSuchFieldException, IllegalAccessException {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        WorkerComList workerComList = new WorkerComList();
        workerComList.setTitle(title);
        workerComList.setRemark(remark);
        workerComList.setFileUrl(fileUrl);
        workerComList.setCreateTime(new Date());
        workerComList.setUpdateTime(new Date());
        workerComList.setCompanyWechatId(adminUser.getCompanyWechatId());
        workerComList.setCompanyWechatName(adminUser.getCompanyName());
        workerComList.insert();

       // String url = ossUtil.getUrl(fileUrl);
        InputStream inputStream = commonLogic.getFileInputStreamByUrl(fileUrl);
        List<Object> objects = ExcelUtils.importExcel(inputStream);
        //添加师傅
        List<WorkerComListWorker> workerComListWorkers = new ArrayList<>();
        for (Object o : objects) {
            List<Object> row = (List<Object>) o;
            String workerNumber = (String) row.get(0);
            if (StringUtils.isEmpty(workerNumber)) {
                continue;
            }
            WorkerComListWorker workerComListWorker = new WorkerComListWorker();
            workerComListWorker.setCreateBy(workerComList.getCreateBy());
            workerComListWorker.setCreateTime(new Date());
            workerComListWorker.setWebsitId(workerNumber);
            workerComListWorker.setWorkerComListId(workerComList.getId());
            workerComListWorker.setWorkerComListWorkerNumber(workerNumber);
            workerComListWorkers.add(workerComListWorker);
        }
        workerComListWorkerService.saveBatch(workerComListWorkers);
        //添加网点
        List<WorkerComListWebsit> workerComListWebsits = new ArrayList<>();
        List<String> websitNumbers = workerComListWorkers.stream()
                .map(WorkerComListWorker::getWebsitId).distinct().collect(Collectors.toList());
        for (String websitNumber : websitNumbers) {
            WorkerComListWebsit workerComListWebsit = new WorkerComListWebsit();
            workerComListWebsit.setWorkerComListId(workerComList.getId());
            workerComListWebsit.setWebsitId(websitNumber);
            workerComListWebsit.setCreateBy(workerComList.getCreateBy());
            workerComListWebsit.setCreateTime(workerComList.getCreateTime());
            workerComListWebsits.add(workerComListWebsit);
        }
        workerComListWebsitService.saveBatch(workerComListWebsits);

        //按2w/次添加到es
        List<List<Object>> partition = Lists.partition(objects, 20000);
        for (List<Object> datas : partition) {
            //添加到es
            esLogic.add(workerComList.getId(), remark, datas);
        }
    }


    /**
     * 通用列表明细
     *
     * @param comListId
     * @param workerNumber
     */
    public List<CommonListES> record(String comListId, String workerNumber) {
        List<CommonListES> list = esLogic.list(Arrays.asList(workerNumber), workerNumber, comListId);
        return list;
    }


    public void download(String id, String websitNumber, HttpServletRequest request, HttpServletResponse response) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (StringUtils.isNotEmpty(websitNumber)) {
            adminUser.setAdminWebsitIds(new ArrayList<String>() {{ this.add(websitNumber); }});
        }
        WorkerComList workerComList = workerComListService.getById(id);

        if (adminUser.getType() == 1 || adminUser.getNickName().equals(workerComList.getCreateBy())) {
            log.info("【中心文件下发下载】:{}", JSONObject.toJSONString(adminUser));
            CommonUtils.downloadFile(workerComList.getFileUrl(),workerComList.getTitle()+".xlsx" , response);
        } else {
            List<AdminWebsit> websitList = adminWebsitService.lambdaQuery().in(AdminWebsit::getWebsitId, adminUser.getCompanyWechatIds()).list();
            List<String> websitNumbers = websitList.stream().map(AdminWebsit::getWebsitId).collect(Collectors.toList());
            List<CommonListES> list = esLogic.list(websitNumbers, null, id.toString());
            if (CollectionUtils.isEmpty(list)) {
                throw new RemoteServiceException("暂无可下载的内容");
            }
            List<String> titles = new ArrayList<>();
            List<List<Object>> datas = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {

                CommonListES bean = list.get(i);
                List<Object> data = new ArrayList<>();

                for (int x = 1; x <= 50; x++) {
                    String field = "field" + x;
                    Field declaredField = bean.getClass().getDeclaredField(field);
                    declaredField.setAccessible(true);
                    String value = (String) declaredField.get(bean);
                    if (i == 0) {
                        if (StringUtils.isNotEmpty(value)) {
                            titles.add(value);
                        }
                    } else {
                        if (StringUtils.isNotEmpty(value)) {
                            data.add(value);
                        }
                    }
                }

                if (i > 0) {
                    datas.add(data);
                }
            }
            ExcelData excelData = new ExcelData();
            excelData.setTitles(titles);
            excelData.setRows(datas);
            ExcelUtils.exportExcel(request, response, "info.xlsx", excelData);
        }
    }


}
