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

import cn.com.ctop.common.module.service.ISysRoleExtService;
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.service.IKuaishouChannelItemsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
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.ResponseBody;
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 2021-08-30
 */
@Slf4j
@Api(tags = "渠道号对应单品信息表")
@RestController
@RequestMapping("/channelItem")
public class KuaishouChannelItemsController {
    @Autowired
    private IKuaishouChannelItemsService kuaishouChannelItemsService;
    @Autowired
    private ISysRoleExtService sysRoleService;

    /**
     * 查询单品列表
     */
    @GetMapping(value = "/queryChannelItemList")
    public Result<Object> queryChannelItemList(KuaishouChannelItems kuaishouChannelItems, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            String roleCode = sysRoleService.getRoleCodeByUserId(kuaishouChannelItems.getUserId());
            if ("admin".equals(roleCode) || "sale".contains(roleCode) || "meidaManager".equals(roleCode)) {
                kuaishouChannelItems.setUserId(null);
            }
            PageHelper.startPage(pageNo, pageSize);
            return kuaishouChannelItemsService.queryChannelItemList(kuaishouChannelItems);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询单品列表异常");
        }
    }

    /**
     * 根据项目查询单品集合
     */
    @GetMapping(value = "/queryAllChannelItemByProjectId")
    public Result<Object> queryAllChannelItemByProjectId(Long projectId) {
        try {
            if (Check.isNull(projectId)) {
                return Result.error("请选择项目");
            }
            return kuaishouChannelItemsService.queryAllChannelItemByProjectId(projectId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("根据项目查询单品集合异常");
        }
    }

    /**
     * 新增单品
     *
     * @return
     */
    @PostMapping(value = "/addChannelItem")
    public Result<Object> addChannelItem(@RequestBody JSONArray request) {
        try {
            if (request.isEmpty()) {
                return Result.error("请添加信息");
            }
            return kuaishouChannelItemsService.addChannelItem(request);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("新增单品异常");
        }
    }

    /**
     * 修改渠道号
     */
    @GetMapping(value = "/updateChannelItems")
    public Result<Object> updateChannelItems(KuaishouChannelItems item) {
        try {
            if (Check.isNull(item.getId())) {
                return Result.error("缺失参数");
            }
            KuaishouChannelItems itemEntity = kuaishouChannelItemsService.getById(item.getId());
            if (itemEntity == null) {
                return Result.error("未找到对应实体");
            } else {
                kuaishouChannelItemsService.updateById(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改渠道号异常");
        }
        return Result.ok("修改成功");
    }

    /**
     * 渠道号绑定单品
     */
    @PostMapping(value = "/channelBindingItem")
    public Result<Object> channelBindingItem(@RequestBody JSONArray request) {
        try {
            if (request.isEmpty()) {
                return Result.error("请选择信息");
            }
            return kuaishouChannelItemsService.channelBindingItem(request);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改渠道号异常");
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "渠道号对应单品信息表-通过id删除", notes = "渠道号对应单品信息表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            kuaishouChannelItemsService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "渠道号对应单品信息表-批量删除", notes = "渠道号对应单品信息表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<KuaishouChannelItems> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<KuaishouChannelItems> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.kuaishouChannelItemsService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "渠道号对应单品信息表-通过id查询", notes = "渠道号对应单品信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<KuaishouChannelItems> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<KuaishouChannelItems> result = new Result<>();
        KuaishouChannelItems kuaishouChannelItems = kuaishouChannelItemsService.getById(id);
        if (kuaishouChannelItems == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(kuaishouChannelItems);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出单品模板
     */
    @GetMapping("/exportItemTemplate")
    public Result<Object> getExcel(HttpServletResponse response, Long projectId) {
        try {
            if (Check.isNull(projectId)) {
                return Result.error("请选择项目");
            }
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            String[] titles = {"项目", "单品名称", "素材关键词"};
            List<List<Object>> list = new ArrayList<>();
            List<Object> ids = new ArrayList<>();
            ids.add(projectId);
            list.add(ids);
            eeu.exportExcelForAttendance(workbook, 0, "Sheet1", titles, list);
            eeu.putResponseHeader(response, "单品模板.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return Result.ok("success");
    }

    /**
     * 导入单品EXCEL批量创建
     */
    @PostMapping(value = "/importItemExcel")
    @ResponseBody
    public Result<Object> importItemExcel(HttpServletResponse response, @RequestParam("file") MultipartFile file) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            if (Check.isNull(file)) {
                return Result.error("执行失败，请上传应用Excel文件");
            }
            return kuaishouChannelItemsService.importItemExcel(file);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("excel批量添加单品异常", e);
            return Result.error("excel批量添加单品失败，" + e.getMessage());
        }
    }


    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<KuaishouChannelItems> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                KuaishouChannelItems kuaishouChannelItems = JSON.parseObject(deString, KuaishouChannelItems.class);
                queryWrapper = QueryGenerator.initQueryWrapper(kuaishouChannelItems, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<KuaishouChannelItems> pageList = kuaishouChannelItemsService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "渠道号对应单品信息表列表");
        mv.addObject(NormalExcelConstants.CLASS, KuaishouChannelItems.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("渠道号对应单品信息表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @returnexportAppTemplate
     */
    @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<KuaishouChannelItems> listKuaishouChannelItemss = ExcelImportUtil.importExcel(file.getInputStream(), KuaishouChannelItems.class, params);
                kuaishouChannelItemsService.saveBatch(listKuaishouChannelItemss);
                return Result.ok("文件导入成功！数据行数:" + listKuaishouChannelItemss.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("文件导入失败！");
    }

}
