package com.yizhi.application.enroll.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.context.TaskContext;
import com.yizhi.core.application.file.constant.FileConstant;
import com.yizhi.core.application.file.task.AbstractDefaultTask;
import com.yizhi.core.application.file.util.OssUpload;
import com.yizhi.enroll.application.feign.EnrollFeignClient;
import com.yizhi.enroll.application.vo.EnrollerParam;
import com.yizhi.enroll.application.vo.EnrollerVo;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.OrganizationClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: dingxiaowei
 * @Date: 2020/2/25 15:56
 * @Description:项目报名明细
 */
@Component
public class EnrollerListExport extends AbstractDefaultTask<String, Map<String, Object>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(EnrollerListExport.class);

    @Autowired
    TrainingProjectClient trainingProjectClient;

    @Autowired
    OrganizationClient organizationClient;

    @Autowired
    EnrollFeignClient enrollFeignClient;

    @Autowired
    AccountClient accountClient;


    @Override
    protected String execute(Map<String, Object> map) {


        String uploadUrl = null;
        RequestContext res = (RequestContext) map.get("res");
        Long accountId1 = res.getAccountId();
        Long siteId = res.getSiteId();
        Long companyId = res.getCompanyId();
        Date comitTime = (Date) map.get("comitTime");;
        Long taskId = (Long) map.get("taskId");
        String serialNo = (String) map.get("serialNo");
        String taskName = (String) map.get("taskName");
        String userName = (String) map.get("userName");
        String key = (String) map.get("key");
        Long trainningProjectId = (Long) map.get("trainningProjectId");
        Integer state = (Integer) map.get("state");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId1, comitTime, siteId, companyId);
        working(taskContext);


        // 根据用户关键字获取用户ID集合
        List<Long> userIdList = null;
        List<Long> orgIdList = null;
        //根据项目Id获得是否需要审核
        int enableEnroll;
        try {
            enableEnroll = trainingProjectClient.getOne(trainningProjectId).getEnableEnroll();
        } catch (Exception e) {
            e.printStackTrace();
            enableEnroll = 1;
        }
        List<AccountVO> userList = null;
        if (StringUtils.isNotBlank(userName)) {
            try {
                userList = accountClient.fuzzySearchAccountByName(userName, companyId);
                if (!CollectionUtils.isEmpty(userList)) {
                    userIdList = new ArrayList<>();
                    for (AccountVO a : userList) {
                        userIdList.add(a.getId());
                    }
                } else {
                    success(taskContext, "执行成功,未查找到数据", uploadUrl);
                }

            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        if (StringUtils.isNotBlank(key)) {
            orgIdList = organizationClient.findOrgIdByName(key, companyId);
            if (CollectionUtils.isEmpty(orgIdList)) {
                success(taskContext, "执行成功,未查找到数据", uploadUrl);
            }
        }
        EnrollerParam enrollerParam = new EnrollerParam();
        if (!CollectionUtils.isEmpty(userIdList)) {
            enrollerParam.setUserIdList(userIdList);
        }
        if (!CollectionUtils.isEmpty(orgIdList)) {
            enrollerParam.setOrgIds(orgIdList);
        }
        enrollerParam.setPageNo(1);
        enrollerParam.setPageSize(Integer.MAX_VALUE);
        enrollerParam.setTrainningProjectId(trainningProjectId);
        enrollerParam.setEnableEnroll(enableEnroll);
        enrollerParam.setState(state);
        Page<EnrollerVo> page = enrollFeignClient.listEnroll(enrollerParam);
        List<EnrollerVo> list = null;

        if (null != page) {
            list = page.getRecords();
        }

        if (CollectionUtils.isEmpty(list)) {
            success(taskContext, "执行成功,未查找到数据", uploadUrl);
        }

        Map<Long, Object> accountMap = new HashMap<Long, Object>();
        Map<Long, Object> orgMap = new HashMap<Long, Object>();
        EnrollerVo vo = null;
        AccountVO account = null;
        List<String> orgs = null;
        for (EnrollerVo item : list) {
            Long orgId = item.getOrgId();
            Long accountId = item.getAccountId();
            //根据accountId 获取 用户name,userName
            String name = null;
            String fullName = null;
            //根据orgId 获取 部门名称 orgName
            String orgName = null;
            String orgNames = null;
            if (accountMap.containsKey(accountId)) {
                vo = (EnrollerVo) accountMap.get(accountId);
                name = vo.getUserName();
                fullName = vo.getName();
            } else {
                try {
                    account = accountClient.findById(accountId);
                    fullName = account.getFullName();
                    name = account.getName();
                    vo = new EnrollerVo();
                    vo.setUserName(name);
                    vo.setName(fullName);
                    accountMap.put(accountId, vo);
                } catch (Exception e) {
                    name = "--";
                }
            }
            if (orgMap.containsKey(orgId)) {
                vo = (EnrollerVo) orgMap.get(orgId);
                orgName = vo.getOrgName();
                orgNames = vo.getOrgNames();
            } else {
                try {
                    orgs = organizationClient.getChiefOrgNames(orgId, companyId);
                    if (orgs != null && orgs.size() == 1) {
                        orgName = orgs.get(0);
                    } else if (orgs != null && orgs.size() > 1) {
                        orgName = orgs.get(orgs.size() - 1);
                        orgNames = orgs.get(orgs.size() - 2);
                        vo = new EnrollerVo();
                        vo.setOrgNames(orgNames);
                        vo.setOrgName(orgName);
                        orgMap.put(orgId, vo);
                    }
                } catch (Exception e) {
                    orgName = "--";
                }
            }
            item.setName(fullName);
            item.setUserName(name);
            item.setOrgName(orgName);
            item.setOrgNames(orgNames);
        }


        try {
            XSSFWorkbook wb = new XSSFWorkbook();
            XSSFSheet sheet = wb.createSheet("项目报名明细");
            XSSFRow row = sheet.createRow(0);

            row = sheet.createRow(0);
            row.createCell(0).setCellValue("用户名");
            row.createCell(1).setCellValue("姓名");
            row.createCell(2).setCellValue("上级部门");
            row.createCell(3).setCellValue("所在部门");
            row.createCell(4).setCellValue("报名时间");
            row.createCell(5).setCellValue("报名状态");
            row.createCell(6).setCellValue("审核结果");
            row.createCell(7).setCellValue("报名花费");

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    EnrollerVo enrollerVo = list.get(i);
                    row = sheet.createRow(i + 1);
                    row.createCell(0).setCellValue(enrollerVo.getUserName());
                    row.createCell(1).setCellValue(enrollerVo.getName());
                    row.createCell(2).setCellValue(enrollerVo.getOrgNames());
                    row.createCell(3).setCellValue(enrollerVo.getOrgName());
                    row.createCell(4).setCellValue(sdf.format(enrollerVo.getApplyTime()));

                    row.createCell(5).setCellValue("已报名");

                    if (enrollerVo.getAuditResult() == 1) {
                        row.createCell(6).setCellValue("待审核");
                    } else if (enrollerVo.getAuditResult() == 2) {
                        row.createCell(6).setCellValue("审核通过");
                    } else if (enrollerVo.getAuditResult() == 3) {
                        row.createCell(6).setCellValue("审核不通过");
                    } else if (enrollerVo.getAuditResult() == 0) {
                        row.createCell(6).setCellValue("不需要审核");
                    }
                    //报名花费报表列
                    Integer expenditure = enrollerVo.getExpenditure();
                    if (null == expenditure){
                        row.createCell(7).setCellValue("");
                    }else {
                        row.createCell(7).setCellValue(expenditure);
                    }

                }
            }

            TrainingProjectVo trainingProject = trainingProjectClient.getOne(trainningProjectId);

            String fileName = trainingProject.getName() + "报名明细" + sdf2.format(comitTime) + ".xlsx";
//            String requestPath = "/Users/dingxiaowei/aaa";
            String requestPath = FileConstant.SAVE_PATH;
            File fileDir = new File(requestPath);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            map.put("fileName",fileName);
            String path = requestPath + "/" + fileName;
            FileOutputStream os = null;
            File file = null;
            try {
                os = new FileOutputStream(path);
                wb.write(os);
                uploadUrl = OssUpload.upload(path, fileName);
                file = new File(path);
                success(taskContext, "成功", uploadUrl);
            } catch (Exception e1) {
                e1.printStackTrace();
                fail(taskContext, "项目报名明细下载写入过程发生错误");
                LOGGER.error("项目报名明细下载写入过程发生错误");
            } finally {
                if (os != null) {
                    os.close();
                }
                if (wb != null) {
                    wb.close();
                }
                if (file != null) {
                    file.delete();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            fail(taskContext, "项目报名明细下载出现错误");
            LOGGER.error("项目报名明细下载出现错误");
        }

        return uploadUrl;
    }
}
