package cn.com.ctop.kuaishou.modules.material.controller;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.kuaishou.modules.material.entity.ProductMaterial;
import cn.com.ctop.kuaishou.modules.material.service.IProductMaterialService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 选品库——产品与商品信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2022-04-19
 */
@Slf4j
@Api(tags = "选品库——产品与商品信息")
@RestController
@RequestMapping("/product/material")
public class ProductMaterialController {
    @Autowired
    private IProductMaterialService productMaterialService;

    /**
     * 分页列表查询
     */
    @GetMapping(value = "/materialList")
    public Result<Object> materialList(Long productId, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        return productMaterialService.materialList(productId, pageNo, pageSize);
    }

    /**
     * 分页列表查询
     */
    @GetMapping(value = "/list")
    public Result<Object> queryPageList(ProductMaterial productMaterial,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        return productMaterialService.queryPageList(productMaterial, pageNo, pageSize);
    }

    /**
     * 分页列表查询
     */
    @GetMapping(value = "/videoList")
    public Result<Object> videoList(ProductMaterial productMaterial,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        if (Check.isNull(productMaterial.getProductId()) || Check.isNull(productMaterial.getProductId()) || Check.isNull(productMaterial.getTradeName()) || Check.isNull(productMaterial.getStartMonth())) {
            return Result.error("缺少参数");
        }

        return productMaterialService.videoList(productMaterial, pageNo, pageSize);
    }

    /**
     * 添加
     */
    @PostMapping(value = "/add")
    public Result<Object> add(@RequestBody JSONObject data) {
        try {
            return productMaterialService.add(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    /**
     * 编辑
     */
    @PostMapping(value = "/edit")
    public Result<ProductMaterial> edit(@RequestBody ProductMaterial productMaterial) {
        Result<ProductMaterial> result = new Result<ProductMaterial>();
        Long productId = productMaterial.getProductId();
        String tradeName = productMaterial.getTradeName();
        if (Check.isNull(productId) || Check.isNull(tradeName)) {
            return result.error500("缺少参数");
        }
        QueryWrapper<ProductMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("trade_name", tradeName);
        boolean ok = productMaterialService.update(productMaterial, queryWrapper);
        if (ok) {
            result.success("修改成功!");
        }
        return result;
    }

    /**
     * 通过id删除
     */
    @GetMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            if (Check.isNull(id)) {
                return Result.error("缺少参数!");
            }
            productMaterialService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "选品库——产品与商品信息-通过id查询", notes = "选品库——产品与商品信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ProductMaterial> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ProductMaterial> result = new Result<>();
        ProductMaterial productMaterial = productMaterialService.getById(id);
        if (productMaterial == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(productMaterial);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 下载视频详情报表
     */
    @GetMapping(value = "/getVideoDetailsReportExcel")
    public void getVideoDetailsReportExcel(HttpServletResponse response, ProductMaterial productMaterial) {
        try {

            List<JSONObject> list = productMaterialService.getVideoDetailsReportList(productMaterial);
            List<List<Object>> excelList = new ArrayList<>();
            if (!list.isEmpty()) {
                list.forEach(data -> {
                    String endMonth = data.getString("endMonth");
                    if(Check.isNull(endMonth)){
                        endMonth= "-";
                    }
                    List<Object> temp = new ArrayList<>();
                    temp.add(data.getString("productName"));
                    temp.add(data.getString("tradeName"));
                    temp.add(data.getString("startMonth")+" ~ " +endMonth);
                    temp.add(data.getString("videoUrl"));
                    temp.add(data.getString("charge"));
                    temp.add(data.getString("itemRun"));
                    temp.add(data.getString("user"));
                    excelList.add(temp);
                });
            }
            List<String> titles = new ArrayList<>();
            titles.add(0, "产品名称");
            titles.add(1, "商品名称");
            titles.add(2, "时间");
            titles.add(3, "视频链接");
            titles.add(4, "消耗");
            titles.add(5, "是否跑量");
            titles.add(6, "上传人");

            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            String[] headers = titles.toArray(new String[titles.size()]);
            eeu.exportExcelForAttendance(workbook, 0, "选品视频", headers, excelList);
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询失败", e.getMessage());
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ProductMaterial> listProductMaterials = ExcelImportUtil.importExcel(file.getInputStream(), ProductMaterial.class, params);
                productMaterialService.saveBatch(listProductMaterials);
                return Result.ok("文件导入成功！数据行数:" + listProductMaterials.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
