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

import cn.com.ctop.common.module.service.ISysRoleExtService;
import cn.com.ctop.common.module.service.ISysUserService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.kuaishou.modules.channel.entity.KuaishouChannel;
import cn.com.ctop.kuaishou.modules.channel.service.IKuaishouChannelService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.jeecg.modules.system.service.ISysRoleService;
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("/channel")
public class KuaishouChannelController {
    @Autowired
    private IKuaishouChannelService kuaishouChannelService;
    @Autowired
    private ISysRoleExtService sysRoleService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService roleService;

    /**
     * 查询渠道号管理首页数据
     */
    @GetMapping(value = "/channelManagementHome")
    public Result<Object> channelManagementHome(KuaishouChannel kuaishouChannel, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {

            String userId = kuaishouChannel.getUserId();
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            List<String> userIds = new ArrayList<>();
            if ("CompanyManager".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("bytedanceDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("kuaishouDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if (!Check.isNull(roleCode) && ("admin".equals(roleCode) || roleCode.contains("sale") || "meidaManager".equals(roleCode))) {
                kuaishouChannel.setRids(null);
            } else {
                sysUserService.getItsPersonnelIds(userIds, kuaishouChannel.getUserId());
                kuaishouChannel.setRids(userIds);
            }
            if (!Check.isNull(userIds)) {
                kuaishouChannel.setRids(userIds);
            }

            PageHelper.startPage(pageNo, pageSize);
            return kuaishouChannelService.channelManagementHome(kuaishouChannel);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询渠道号管理首页数据异常");
        }
    }


    /**
     * 渠道号详情
     */
    @GetMapping(value = "/channelNumberDetails")
    public Result<Object> channelNumberDetails(KuaishouChannel kuaishouChannel, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(kuaishouChannel.getAccountId())) {
                return Result.error("请选择账户");
            }
            return kuaishouChannelService.channelNumberDetails(kuaishouChannel, pageNo, pageSize);


        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询渠道号详情异常");
        }
    }


    /**
     * 渠道号使用详情列表
     */
    @GetMapping(value = "/channelNumberUsageDetailsList")
    public Result<Object> channelNumberUsageDetailsList(KuaishouChannel kuaishouChannel, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(kuaishouChannel.getAccountId()) || Check.isNull(kuaishouChannel.getChannelCode())) {
                return Result.error("缺失参数");
            }
            return kuaishouChannelService.channelNumberUsageDetailsList(kuaishouChannel, pageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询渠道号详情异常");
        }
    }


    /**
     * 渠道号绑定单品列表页
     */
    @PostMapping(value = "/channelNumberBindingItemInfo")
    public Result<Object> channelNumberBindingItemInfo(@RequestBody JSONObject request) {
        try {
            if (request.isEmpty()) {
                return Result.error("请选择信息");
            }
            JSONArray ids = request.getJSONArray("ids");
            return kuaishouChannelService.channelNumberBindingItemInfo(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询渠道号绑定单品列表异常");
        }
    }


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

    /**
     * 修改首页账户渠道号状态
     */
    @GetMapping(value = "/updateAccountChannelState")
    public Result<Object> updateAccountChannelState(KuaishouChannel channel) {
        try {
            if (Check.isNull(channel.getAccountId())) {
                return Result.error("缺失参数");
            }
            QueryWrapper<KuaishouChannel> wrapper = new QueryWrapper<>();
            wrapper.eq("account_id", channel.getAccountId());
            kuaishouChannelService.update(channel, wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改渠道号异常");
        }
        return Result.ok("修改成功");
    }

    /**
     * 修改渠道号
     */
    @GetMapping(value = "/updateChannels")
    public Result<Object> updateChannels(KuaishouChannel channel) {
        try {
            if (Check.isNull(channel.getAccountId()) || Check.isNull(channel.getUserId())) {
                return Result.error("缺失参数");
            }
            return kuaishouChannelService.updateChannels(channel);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改渠道号异常");
        }
    }

    /**
     * 导出单品模板
     */
    @GetMapping("/exportChannelTemplate")
    public Result<Object> getExcel(HttpServletResponse response, Long projectId, Long productId, String userId) {
        try {
            if (Check.isNull(projectId) || Check.isNull(productId)) {
                return Result.error("缺少参数");
            }
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            String[] titles = {
                    "产品（固定项，勿修改）",
                    "项目（固定项，勿修改）",
                    "渠道号创建人（固定项，勿修改）",
                    "使用范围（1代表账户，2代表项目）",
                    "账户ID（和项目对应）",
                    "渠道号（如：数字加字母）",
                    "渠道号名称",
                    "下载链接",
                    "应用包名",
                    "应用名称",
                    "应用标记",
                    "隐私政策链接",
                    "第三方点击监测链接",
                    "是否关联单品（0代表不关联，1代表关联）",
                    "关联单品名称",
                    "使用层级（账户：account，计划：plan,组：group）",
                    "是否循环（0代表不循环，1代表循环）",
                    "调起链接（选填）",
                    "第三方actionBar监测链接（选填）"
            };
            List<List<Object>> list = new ArrayList<>();
            List<Object> ids = new ArrayList<>();
            ids.add(productId);//产品
            ids.add(projectId);//项目
            ids.add(userId);//渠道号创建人
            ids.add(1);//使用范围（1项目，2账户）
            ids.add(23212);//账户ID
            ids.add("KS_0001");//渠道号（数字加字母）
            ids.add("快手0001");//渠道号名称
            ids.add("http://test.com.cn");//下载链接
            ids.add("com.test.hcst");//应用包名
            ids.add("示例包_HCST");//应用名称
            ids.add("hcst");//应用标记
            ids.add("http://test123.com.cn");//隐私政策链接
            ids.add("http://test123456.com.cn");//第三方点击监测链接
            ids.add(0);//是否关联单品（0否，1是）
            ids.add("");//关联单品名称
            ids.add("plan");//使用层级（账户：account，计划：plan,组：group）
            ids.add(1);//是否循环（0否，1是）
            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");
    }

    /**
     * 系统批量创建渠道号
     */
    @PostMapping(value = "/systemBatchCreation")
    public Result<Object> systemBatchCreation(@RequestBody JSONObject request) {
        try {
            return kuaishouChannelService.systemBatchCreation(request);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("系统批量创建渠道号异常", e);
            return Result.error("系统批量创建渠道号失败，" + e.getMessage());
        }
    }


    /**
     * 导入渠道号EXCEL批量创建
     */
    @PostMapping(value = "/importChannelExcel")
    @ResponseBody
    public Result<Object> importChannelExcel(HttpServletResponse response, @RequestParam("file") MultipartFile file, @RequestParam("imageUrl") String imageUrl) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            if (Check.isNull(file) || Check.isNull(imageUrl)) {
                return Result.error("请上传图标和文档");
            }
            return kuaishouChannelService.importChannelExcel(file, imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("excel批量添加渠道号异常", e);
            return Result.error("excel批量添加渠道号失败，" + e.getMessage());
        }
    }

    /**
     * 通过账户查询渠道号接口
     */
    @PostMapping(value = "/queryChannel")
    public Result<Object> queryChannel(Long accountId, String usageLevel, String appName, String photoName) {
        try {
            if (Check.isNull(accountId) || Check.isNull(usageLevel) || Check.isNull(appName)) {
                return Result.error("缺失参数");
            }
            return kuaishouChannelService.queryChannel(accountId, usageLevel, appName, photoName);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("通过账户查询渠道号异常", e);
            return Result.error("通过账户查询渠道号失败，" + e.getMessage());
        }
    }

    /**
     * 通过账户查询渠道号接口
     */
    @GetMapping(value = "/queryChannelList")
    public Result<Object> queryChannelList(Long accountId, String appName,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(accountId) || Check.isNull(appName)) {
                return Result.error("缺失参数");
            }
            PageHelper.startPage(pageNo, pageSize);
            return kuaishouChannelService.queryChannelList(accountId, appName);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("通过账户查询渠道号异常", e);
            return Result.error("通过账户查询渠道号失败，" + e.getMessage());
        }
    }

    /**
     * 通过账户查询渠道号级别
     */
    @PostMapping(value = "/queryChannelLevel")
    public Result<Object> queryChannelLevel(@RequestBody JSONObject request) {
        try {
            if (Check.isNull(request.getLong("accountId")) || Check.isNull(request.getJSONArray("appNameArray"))) {
                return Result.error("缺失参数");
            }
            return kuaishouChannelService.queryChannelLevel(request);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("通过账户查询渠道号级别异常", e);
            return Result.error("通过账户查询渠道号级别失败，" + e.getMessage());
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "渠道号信息表-通过id删除", notes = "渠道号信息表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            kuaishouChannelService.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<KuaishouChannel> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<KuaishouChannel> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.kuaishouChannelService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

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

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

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

    /**
     * 通过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<KuaishouChannel> listKuaishouChannels = ExcelImportUtil.importExcel(file.getInputStream(), KuaishouChannel.class, params);
                kuaishouChannelService.saveBatch(listKuaishouChannels);
                return Result.ok("文件导入成功！数据行数:" + listKuaishouChannels.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("文件导入失败！");
    }

}
