package com.ym.mec.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ym.mec.biz.dal.dao.TempLiveTeacherCardDao;
import com.ym.mec.biz.dal.entity.Goods;
import com.ym.mec.biz.dal.entity.TempLiveTeacherCard;
import com.ym.mec.biz.dal.enums.*;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.entity.UploadReturnBean;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.util.excel.POIUtil;
import com.ym.mec.util.ini.IniFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.PictureData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.biz.dal.entity.TempBuyFreeLiveTheoryCourse;
import com.ym.mec.biz.service.TempBuyFreeLiveTheoryCourseService;
import com.ym.mec.biz.dal.dao.TempBuyFreeLiveTheoryCourseDao;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

@Service
public class TempBuyFreeLiveTheoryCourseServiceImpl extends BaseServiceImpl<Integer, TempBuyFreeLiveTheoryCourse> implements TempBuyFreeLiveTheoryCourseService {
    private final static Logger log = LoggerFactory.getLogger(TempBuyFreeLiveTheoryCourseServiceImpl.class);

    @Autowired
    private TempBuyFreeLiveTheoryCourseDao tempBuyFreeLiveTheoryCourseDao;

    @Resource
    private TempLiveTeacherCardDao tempLiveTeacherCardDao;

    @Override
    public BaseDAO<Integer, TempBuyFreeLiveTheoryCourse> getDAO() {
        return tempBuyFreeLiveTheoryCourseDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public List<String> importBuyFreeLiveTheoryCourse(MultipartFile file, Integer id) throws Exception {
        Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(new ByteArrayInputStream(file.getBytes()), 2, file.getOriginalFilename());
        InputStream inputStream = new ClassPathResource("columnMapper.ini").getInputStream();
        Map<String, String> columns = IniFileUtil.readIniFile(inputStream, TemplateTypeEnum.BUY_FREE_LIVE_THEORY_COURSE.getMsg());
        List<TempBuyFreeLiveTheoryCourse> tempList = new ArrayList<>();

        List<String> errMsg = new ArrayList();
        List<Map<String, Object>> sheet = sheetsListMap.get("Sheet0");

        for (int i = 0; i < sheet.size(); i++) {
            Map<String, Object> row = sheet.get(i);
            if (row.size() == 0) {
                continue;
            }
            JSONObject objectMap = new JSONObject();
            for (String s : row.keySet()) {
                String columnValue = columns.get(s);
                if (StringUtils.isEmpty(columnValue)) {
                    continue;
                }
                if (null == row.get(s)) {
                    continue;
                }
                objectMap.put(columnValue, row.get(s));
            }
            String err = "";
            //校验
            Integer tempId = objectMap.getInteger("id");
            if (null == tempId) {
                err += "ID不能为空/";
            }
            String recommendLevel = objectMap.getString("recommendLevel");
            if (StringUtils.isNotEmpty(recommendLevel) && null == LevelEnum.getByName(recommendLevel.trim())) {
                err += "老师推荐级别列，数据异常（可选值：一级 二级 三级）/";
            }
            if (StringUtils.isNotEmpty(err)) {
                err = "第" + (i + 1) + "行数据异常：" + err.substring(0, err.length() - 1);
                errMsg.add(err);
            }

            try {
                TempBuyFreeLiveTheoryCourse course = JSONObject.parseObject(objectMap.toJSONString(), TempBuyFreeLiveTheoryCourse.class);
                tempList.add(course);
            } catch (Exception ex) {
                throw new BizException("导入数据出错", ex);
            }
        }
        if (!CollectionUtils.isEmpty(errMsg)) {
            return errMsg;
        }
        //导入数据库
        for (TempBuyFreeLiveTheoryCourse temp : tempList) {
            if (null == temp.getId()) {
                continue;
            }
            TempBuyFreeLiveTheoryCourse course = tempBuyFreeLiveTheoryCourseDao.get(temp.getId());
            LevelEnum byName = LevelEnum.getByName(temp.getRecommendLevel());
            if(null != byName){
                course.setRecommendLevel(byName.getCode());
            }
            tempBuyFreeLiveTheoryCourseDao.update(course);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public List<String> importLiveTeacherCard(MultipartFile file, Integer id) throws Exception {
        Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(new ByteArrayInputStream(file.getBytes()), 2, file.getOriginalFilename());
        InputStream inputStream = new ClassPathResource("columnMapper.ini").getInputStream();
        Map<String, String> columns = IniFileUtil.readIniFile(inputStream, TemplateTypeEnum.LIVE_TEACHER_CARD.getMsg());
        List<TempLiveTeacherCard> tempList = new ArrayList<>();

        List<String> errMsg = new ArrayList();
        List<Map<String, Object>> sheet = sheetsListMap.get("录入数据");
        for (int i = 0; i < sheet.size(); i++) {
            Map<String, Object> row = sheet.get(i);
            if (row.size() == 0) {
                continue;
            }
            JSONObject objectMap = new JSONObject();
            for (String s : row.keySet()) {
                String columnValue = columns.get(s);
                if (StringUtils.isEmpty(columnValue)) {
                    continue;
                }
                if (null == row.get(s)) {
                    continue;
                }
                objectMap.put(columnValue, row.get(s));
            }
            String err = "";
            //校验
            Integer subjectId = objectMap.getInteger("subjectId");
            if (null == subjectId) {
                err += "声部id不能为空/";
            }
            String level = objectMap.getString("level");
            if (StringUtils.isNotEmpty(level) && null == LevelEnum.getByName(level.trim())) {
                err += "老师推荐级别列，数据异常（可选值：一级 二级 三级）/";
            }
            if (StringUtils.isNotEmpty(err)) {
                err = "第" + (i + 1) + "行数据异常：" + err.substring(0, err.length() - 1);
                errMsg.add(err);
            }

            try {
                TempLiveTeacherCard course = JSONObject.parseObject(objectMap.toJSONString(), TempLiveTeacherCard.class);
                tempList.add(course);
            } catch (Exception ex) {
                throw new BizException("导入数据出错", ex);
            }
        }
        if (!CollectionUtils.isEmpty(errMsg)) {
            return errMsg;
        }
        //导入数据库
        for (TempLiveTeacherCard temp : tempList) {
            LevelEnum byName = LevelEnum.getByName(temp.getLevel());
            if (null == byName) {
                continue;
            }
            TempLiveTeacherCard card = tempLiveTeacherCardDao.getBySubjectIdAndLevel(temp.getSubjectId(), byName.getCode());
            if (null == card) {
                continue;
            }
            card.setUsername(temp.getUsername());
            card.setAvatar(temp.getAvatar());
            card.setIntroduction(temp.getIntroduction());

            //处理曲目内容json
            String json = getMusicContent(temp.getMusicContent());
            card.setMusicContent(json);
            tempLiveTeacherCardDao.update(card);
        }
        return null;
    }

    private String getMusicContent(String musicContent) {
        if (StringUtils.isEmpty(musicContent)) {
            return null;
        }
        musicContent = musicContent.trim();
        List<String> musicList = Arrays.asList(musicContent.split("\\|"));
        List<Map<String, String>> mapList = new ArrayList<>();
        for (String musicStr : musicList) {
            Map<String, String> musicMap = new HashMap<>();
            try {
                String[] split = musicStr.split(",");
                String coourseDay = split[0];
                coourseDay = coourseDay.replace("月",".").replace("日","")
                        .replace("（","(").replace("）",")");
                musicMap.put("coourseDay", coourseDay);
                musicMap.put("coourseTime", split[1]);
                musicMap.put("musicName", split[2]);




                mapList.add(musicMap);
            } catch (Exception e) {
                log.error("数据转换失败 data is {}", musicContent);
                e.printStackTrace();
            }
        }
        return JSONObject.toJSONString(mapList);
    }
}