package cn.com.ctop.kuaishou.modules.channel.service.impl;

import cn.com.ctop.common.module.mapper.ProjectMapper;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.kuaishou.modules.channel.entity.KuaishouChannelItems;
import cn.com.ctop.kuaishou.modules.channel.entity.KuaishouChannelItemsRel;
import cn.com.ctop.kuaishou.modules.channel.mapper.KuaishouChannelItemsMapper;
import cn.com.ctop.kuaishou.modules.channel.service.IKuaishouChannelItemsRelService;
import cn.com.ctop.kuaishou.modules.channel.service.IKuaishouChannelItemsService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 渠道号对应单品信息表
 *
 * @author jeecg-boot
 * 2021-08-30
 * @version V1.0
 */
@Service
public class KuaishouChannelItemsServiceImpl extends ServiceImpl<KuaishouChannelItemsMapper, KuaishouChannelItems> implements IKuaishouChannelItemsService {

    @Autowired
    private KuaishouChannelItemsMapper channelItemsMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private IKuaishouChannelItemsRelService channelItemsRelService;

    @Override
    public Result<Object> queryChannelItemList(KuaishouChannelItems kuaishouChannelItems) {
        List<JSONObject> list = channelItemsMapper.queryChannelItemList(kuaishouChannelItems);
        return Result.ok(new PageInfo<>(list));
    }

    @Override
    public Result<Object> queryAllChannelItemByProjectId(Long projectId) {
        List<JSONObject> list = channelItemsMapper.queryAllChannelItemByProjectId(projectId);
        return Result.ok(list);
    }

    @Override
    public Result<Object> addChannelItem(JSONArray request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = null;
        if (!Check.isNull(sysUser)) {
            userId = sysUser.getId();
        }
        List<KuaishouChannelItems> itemList = new ArrayList<>();
        for (int i = 0; i < request.size(); i++) {
            JSONObject jsonObject = request.getJSONObject(i);
            Long projectId = jsonObject.getLong("projectId");
            String itemName = jsonObject.getString("itemName");
            KuaishouChannelItems one = channelItemsMapper.queryByProjectIdAndName(projectId, itemName);
            if (Check.isNull(one)) {
                KuaishouChannelItems item = new KuaishouChannelItems();
                item.setProjectId(projectId);
                item.setProjectName(projectMapper.getNameByProjectId(projectId));
                item.setState(1);
                item.setItemName(itemName);
                item.setKeyword(jsonObject.getString("keyword"));
                item.setStateDate(DateUtils.getNowDate("yyyy-MM-dd"));
                item.setUserId(userId);
                itemList.add(item);
            }
        }
        if (!itemList.isEmpty()) {
            channelItemsMapper.replaceBatch(itemList);
        }
        return Result.ok("添加成功");
    }

    @Override
    public Result<Object> channelBindingItem(JSONArray request) {
        for (int i = 0; i < request.size(); i++) {
            JSONObject object = request.getJSONObject(i);
            if (Check.isNull(object.getLong("id")) || Check.isNull(object.getLong("channelId"))) {
                continue;
            }
            QueryWrapper<KuaishouChannelItemsRel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("channel_id", object.getLong("channelId")).last("limit 1");
            KuaishouChannelItemsRel one = channelItemsRelService.getOne(queryWrapper);
            if (Check.isNull(one)) {
                one = new KuaishouChannelItemsRel();
            }
            one.setItemId(object.getLong("id"));
            one.setChannelId(object.getLong("channelId"));
            channelItemsRelService.saveOrUpdate(one);
        }
        return Result.ok("绑定成功");
    }

    @Override
    public Result<Object> importItemExcel(MultipartFile file) throws Exception {
        JSONObject returnJson = new JSONObject();
        Workbook workbook = null;
        String fileName = file.getOriginalFilename();
        String substring = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
        if ("XLS".equals(substring)) {
            workbook = new HSSFWorkbook(file.getInputStream());
        } else if ("XLSX".equals(substring)) {
            workbook = new XSSFWorkbook(file.getInputStream());
        } else {
            throw new Exception("文件不是Excel文件");
        }
        Sheet sheet = workbook.getSheet("Sheet1");
        if (Check.isNull(sheet)) {
            throw new Exception("Sheet标题不是默认的Sheet1");
        }
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if (rows == 0) {
            throw new Exception("请填写数据");
        }
        ExportExcelUtils eeu = new ExportExcelUtils();
        JSONArray array = new JSONArray();
        for (int i = 1; i <= rows + 1; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                String projectId = eeu.getCellValue(row.getCell(0));
                String itemName = eeu.getCellValue(row.getCell(1));
                String keyword = eeu.getCellValue(row.getCell(2));
                if (Check.isNull(projectId)) {
                    return Result.error("解析数据失败，文档中项目列缺失数据");
                } else if (Check.isNull(itemName)) {
                    return Result.error("解析数据失败，文档中单品名称列缺失数据");
                } else if (Check.isNull(keyword)) {
                    return Result.error("解析数据失败，文档中素材关键词列缺失数据");
                }
                JSONObject obj = new JSONObject();
                obj.put("projectId", projectId);
                obj.put("itemName", itemName);
                obj.put("keyword", keyword);
                array.add(obj);
            }
        }
        if (!array.isEmpty()) {
            addChannelItem(array);
        }
        return Result.ok("添加成功");
    }

}
