package com.iformall.controller.mem;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.impl.ExcelDataHandlerDefaultImpl;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.domain.po.WxTags;
import com.iformall.domain.vo.CUserBaseInfoT;
import com.iformall.service.WxCUserBasicInfoService;
import com.iformall.service.WxTagsService;
import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AsyncTask {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @Autowired
    private WxTagsService wxTagsService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private class UserExcelHandler extends ExcelDataHandlerDefaultImpl<CUserBaseInfoT> {
        @Override
        public Object importHandler(CUserBaseInfoT obj, String name, Object value) {
            if (value == null) {
                value = "";
            }
            System.out.println(name + " + " + value.toString());
            return super.importHandler(obj, name, value);
        }

    }

    private void set_redis_value(String importKey, String allCount, String allSuccessCount, String processCount, String failCount, boolean fail) {
        stringRedisTemplate.opsForHash().put(importKey, "allCount", allCount);
        stringRedisTemplate.opsForHash().put(importKey, "allSuccessCount", allSuccessCount);
        stringRedisTemplate.opsForHash().put(importKey, "processCount", processCount);
        stringRedisTemplate.opsForHash().put(importKey, "failCount", failCount);
        if(fail) {
            stringRedisTemplate.expire(importKey,10, TimeUnit.SECONDS);
        }
    }

    @Async
    public void importExcelData(File file, MallUserInfo user, String importKey, String tenantId) {
        ImportParams params = new ImportParams();
        // 需要验证
        params.setImportFields(new String[]{"姓名", "性别", "手机号*", "微信昵称", "学历", "生日", "地址", "上次活跃时间", "注册时间", "标签", "成长值", "积分"});
        IExcelDataHandler<CUserBaseInfoT> handler = new AsyncTask.UserExcelHandler();
        handler.setNeedHandlerFields(new String[]{"手机号*"});
        params.setNeedVerify(true);

        ExcelImportResult<CUserBaseInfoT> datalist = null;

        try {
            datalist = ExcelImportUtil.importExcelMore(file, CUserBaseInfoT.class, params);
        } catch (Exception e) {
            set_redis_value(importKey, "1", "0", "0", "1", true);
            logger.error(e.getMessage());
            // 删除缓存文件
            file.delete();
            return;
        }
        // 删除缓存文件
        file.delete();

        if(datalist == null) {
            logger.error("导入模板失败: 模板数据解析失败");
            set_redis_value(importKey, "1", "0", "0", "1", true);
            return;
        }

        List<CUserBaseInfoT> successList = datalist.getList();
        List<CUserBaseInfoT> failList = datalist.getFailList();

        logger.info("验证通过的数量: " + successList.size());
        logger.info("验证未通过的数量: " + failList.size());

        int total = successList.size() + failList.size();
        int all_success = successList.size();
        int all_fail = failList.size();

        //添加到redis里
        set_redis_value(importKey, "" + total, "" + all_success, "0", "" + all_fail, total == all_fail);

        if(successList.size() > 0) {
            WxTags wxTagsQ = new WxTags();
            List<WxTags> tagList = wxTagsService.findList(wxTagsQ);

            try {
                successList.parallelStream().forEach(uBase -> {
                    try {
                        wxCUserBasicInfoService.importOneMem(tenantId, importKey, tagList, uBase,user);
                    } catch (UnknownSessionException ue) {
                        logger.error("session :"+ue.getMessage());
                    }
                });
            } catch (Exception e) {
                set_redis_value(importKey, "1", "0", "0", "1", true);
                e.printStackTrace();
                logger.error("导入模板失败:"+e.getMessage());
            }
        }
    }
}
