package com.ruixuan.isc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.Subscribe;
import com.kuaidi100.sdk.contant.ApiInfoConstant;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.request.SubscribeParam;
import com.kuaidi100.sdk.request.SubscribeParameters;
import com.kuaidi100.sdk.request.SubscribeReq;
import com.kuaidi100.sdk.response.SubscribeResp;
import com.ruixuan.common.core.controller.BaseController;
import com.ruixuan.common.core.domain.AjaxResult;
import com.ruixuan.common.core.domain.entity.SysUser;
import com.ruixuan.common.core.page.TableDataInfo;
import com.ruixuan.common.utils.Check;
import com.ruixuan.data.utils.ExportExcelUtils;
import com.ruixuan.isc.entity.*;
import com.ruixuan.isc.enums.CompanyEnum;
import com.ruixuan.isc.service.IKuaishouItemCollectSamplesService;
import com.ruixuan.isc.service.IKuaishouItemListService;
import com.ruixuan.isc.service.IKuaishouPromoterService;
import com.ruixuan.system.service.ISysDeptService;
import com.ruixuan.system.service.ISysRoleService;
import com.ruixuan.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 【商品领样】Controller
 *
 * @author ruoyi
 * @date 2023-02-08
 */
@Api(tags = "商品领样")
@RestController
@Slf4j
@RequestMapping("/itemCollectSamples")
public class KuaishouItemCollectSamplesController extends BaseController {
    @Autowired
    private IKuaishouItemCollectSamplesService kuaishouItemCollectSamplesService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IKuaishouItemListService itemListService;
    @Autowired
    private IKuaishouPromoterService promoterService;

    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Long itemId, String promoterId, Long userId, Integer collectSampleStatus, String itemTitle, String promoterNickName, String promoterPhone,
                              String consignee, Long itemCreateId, Long collectSampleId, String courierNumber, String collectSampleDesc, String fieId, String sort, Integer mediaId) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        try {
            Map<String, Object> requestMap = new HashMap<>();
            if (!Check.isNull(userId)) {
                String roleId = sysRoleService.getRoleBYUserId(userId);
                if (!Check.isNull(collectSampleStatus)) {
                    if (roleId.equals("courtshipManager") || roleId.equals("bdManager") || roleId.equals("associationManager")) { // 经理层级查看部门下所有数据
                        Long deptId = sysDeptService.getDeptIdByUserId(userId);
                        List<Long> userIds = sysDeptService.getDeptUserListByDeptId(deptId);
                        if (roleId.equals("bdManager") || roleId.equals("associationManager")) {
                            requestMap.put("collectSampleIds", userIds);
                        } else {
                            requestMap.put("itemCreateIds", userIds);
                        }
                    } else if (roleId.equals("association") || roleId.equals("bd")) { // 社群和bd查看申请人为自己的领样信息
                        requestMap.put("collectSampleId", userId);
                    } else if (roleId.equals("courtship")) { // 招商查看创建人为自己的领样信息
                        requestMap.put("itemCreateId", userId);
                    }
                } else {
                    if (roleId.equals("courtshipManager") || roleId.equals("bdManager")) { // 经理层级查看部门下所有数据
                        Long deptId = sysDeptService.getDeptIdByUserId(userId);
                        List<Long> userIds = sysDeptService.getDeptUserListByDeptId(deptId);
                        if (roleId.equals("bdManager")) {
                            requestMap.put("collectSampleIds", userIds);
                        } else {
                            requestMap.put("itemCreateIds", userIds);
                        }
                    } else if (roleId.equals("bd")) { // 社群和bd查看申请人为自己的领样信息
                        requestMap.put("collectSampleId", userId);
                    } else if (roleId.equals("courtship")) { // 招商查看创建人为自己的领样信息
                        requestMap.put("itemCreateId", userId);
                    }
                }
            }
            if (!Check.isNull(itemId)) {
                requestMap.put("itemId", itemId);
            }
            if (!Check.isNull(promoterId)) {
                requestMap.put("promoterId", promoterId);
            }
            if (!Check.isNull(collectSampleStatus)) {
                requestMap.put("collectSampleStatus", collectSampleStatus);
            }
            if (!Check.isNull(itemTitle)) {
                requestMap.put("itemTitle", itemTitle);
            }
            if (!Check.isNull(promoterNickName)) {
                requestMap.put("promoterNickName", promoterNickName);
            }
            if (!Check.isNull(promoterPhone)) {
                requestMap.put("promoterPhone", promoterPhone);
            }
            if (!Check.isNull(consignee)) {
                requestMap.put("consignee", consignee);
            }
            if (!Check.isNull(itemCreateId)) {
                requestMap.put("itemCreateId", itemCreateId);
            }
            if (!Check.isNull(collectSampleId)) {
                requestMap.put("collectSampleId", collectSampleId);
            }
            if (!Check.isNull(courierNumber)) {
                requestMap.put("courierNumber", courierNumber);
            }
            if (!Check.isNull(collectSampleDesc)) {
                requestMap.put("collectSampleDesc", collectSampleDesc);
            }
            if (!Check.isNull(fieId)) {
                requestMap.put("fieId", fieId);
            }
            if (!Check.isNull(sort)) {
                requestMap.put("sort", sort);
            }
            if (!Check.isNull(mediaId)) {
                requestMap.put("mediaId", mediaId);
            }
            startPage();
            List<KuaishouItemCollectSamples> list = kuaishouItemCollectSamplesService.selectKuaishouItemCollectSamplesList(requestMap);
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
            tableDataInfo.setCode(500);
            tableDataInfo.setMsg(e.getMessage());
        }
        return tableDataInfo;
    }


    @GetMapping("/getUserList")
    public JSONObject getUserList(Long userId) {
        JSONObject returnJson = new JSONObject();
        Long deptId = sysDeptService.getDeptIdByUserId(userId);
        List<JSONObject> userIds = sysDeptService.getUserListByDeptId(deptId);
        returnJson.put("code", 0);
        returnJson.put("message", "查询成功");
        returnJson.put("data", userIds);
        return returnJson;
    }


    /**
     * 领样预览
     */

    @PostMapping("/preview")
    public JSONObject preview(@RequestBody JSONObject requestJson) {
        JSONObject returnJson = new JSONObject();
        try {
            Long userId = requestJson.getLong("userId");
            if (Check.isNull(userId)) {
                throw new Exception("请传入当前登录人ID");
            }
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (Check.isNull(sysUser)) {
                throw new Exception("未获取到登录人信息");
            }
            JSONArray itemIds = requestJson.getJSONArray("itemIds");
            if (Check.isNull(itemIds)) {
                throw new Exception("请传入需要申请的商品列表");
            }
            JSONArray ids = requestJson.getJSONArray("ids");
            if (Check.isNull(ids)) {
                throw new Exception("请传入需要申请的达人列表");
            }
            JSONObject previewJson = kuaishouItemCollectSamplesService.preview(userId, sysUser.getNickName(), itemIds, ids);
            returnJson.put("code", 0);
            returnJson.put("message", "success");
            returnJson.put("preview", previewJson);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    /**
     * 新增【请填写功能名称】
     */

    @PostMapping("/add")
    public JSONObject add(@RequestBody JSONObject requestJson) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参不能为空");
            }
            JSONArray temCollectSamples = requestJson.getJSONArray("temCollectSamples");
            if (Check.isNull(temCollectSamples)) {
                throw new Exception("认领信息不能为空");
            }
            kuaishouItemCollectSamplesService.batchAdd(temCollectSamples);
            returnJson.put("code", 0);
            returnJson.put("message", "领样信息增加成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/getCompany")
    public List<JSONObject> getCompany() {
        return CompanyEnum.companyList();
    }


    /**
     * 修改【请填写功能名称】
     */

    @PutMapping("/edit")
    public JSONObject edit(@RequestBody KuaishouItemCollectSamples kuaishouItemCollectSamples) {
        JSONObject returnJson = new JSONObject();
        try {
            Long id = kuaishouItemCollectSamples.getId();
            if (Check.isNull(id)) {
                throw new Exception("id不能为空");
            }
            KuaishouItemCollectSampleLog sampleLog = new KuaishouItemCollectSampleLog();
            sampleLog.setUserId(kuaishouItemCollectSamples.getUserId());
            sampleLog.setUserName(kuaishouItemCollectSamples.getUserName());
            sampleLog.setSampleId(id);
            Integer collectSampleStatus = kuaishouItemCollectSamples.getCollectSampleStatus();
            if (!Check.isNull(collectSampleStatus)) {
                sampleLog.setCollectSampleStatus(collectSampleStatus);
                if (collectSampleStatus == 2) {
                    String collectSampleDesc = kuaishouItemCollectSamples.getCollectSampleDesc();
                    if (Check.isNull(collectSampleDesc)) {
                        kuaishouItemCollectSamples.setCollectSampleDesc("领样审核拒绝");
                        kuaishouItemCollectSamplesService.cleanLogs(kuaishouItemCollectSamples.getId(), collectSampleStatus);
                    }
                }
                if (collectSampleStatus == 3) {
                    kuaishouItemCollectSamples.setCollectSampleDesc("待录入订单号");
                }
                if (collectSampleStatus == 5) { // 招商审核作业拒绝
                    String collectSampleDesc = kuaishouItemCollectSamples.getCollectSampleDesc();
                    if (Check.isNull(collectSampleDesc)) {
                        kuaishouItemCollectSamples.setCollectSampleDesc("招商审核作业拒绝，请重新提交");
                    }
                    kuaishouItemCollectSamplesService.cleanLogs(kuaishouItemCollectSamples.getId(), collectSampleStatus);
                }
                if (collectSampleStatus == 7) { // 作业完成
                    kuaishouItemCollectSamples.setCollectSampleDesc("作业已完成");
                }
            }
            String courierNumber = kuaishouItemCollectSamples.getCourierNumber();
            if (!Check.isNull(courierNumber)) {
                if (courierNumber.contains(" ") || courierNumber.contains(".") || courierNumber.contains("、") || courierNumber.contains("，") || courierNumber.contains("@") || courierNumber.contains("#")) {
                    throw new Exception("快递单号不能包含空格及特殊字符");
                }
                sampleLog.setCollectSampleStatus(4);
                kuaishouItemCollectSamples.setCollectSampleStatus(4);
                kuaishouItemCollectSamples.setCollectSampleDesc("商品已发货");
                kuaishouItemCollectSamples.setCourierNumberTime(new Date());
                // 调用快递接口
                kuaishouItemCollectSamplesService.subscribe(id, courierNumber, kuaishouItemCollectSamples.getCompanyCode());
            }
            String taskFileUrl = kuaishouItemCollectSamples.getTaskFileUrl();
            if (!Check.isNull(taskFileUrl)) { // 作业上传成功
                sampleLog.setCollectSampleStatus(6);
                kuaishouItemCollectSamples.setCollectSampleStatus(6);
                kuaishouItemCollectSamples.setCollectSampleDesc("作业上传成功，待招商审核");
            }
            int i = kuaishouItemCollectSamplesService.updateKuaishouItemCollectSamples(kuaishouItemCollectSamples);
            if (i > 0) {
                sampleLog.setCreateTime(new Date());
                sampleLog.setUpdateTime(new Date());
                kuaishouItemCollectSamplesService.insertLog(sampleLog);
                Long itemId = kuaishouItemCollectSamplesService.getItemIdById(id);
                if (!Check.isNull(itemId)) {
                    JSONObject info = kuaishouItemCollectSamplesService.getCollectSampleInfo(itemId);
                    itemListService.updateCount(itemId, info.getInteger("sampleCount"), info.getInteger("userCount"));
                }
            }
            returnJson.put("code", 0);
            returnJson.put("message", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @PutMapping("/update")
    public JSONObject update(@RequestBody KuaishouItemCollectSamples kuaishouItemCollectSamples) {
        JSONObject returnJson = new JSONObject();
        try {
            Long id = kuaishouItemCollectSamples.getId();
            if (Check.isNull(id)) {
                throw new Exception("id不能为空");
            }

            int i = kuaishouItemCollectSamplesService.updateKuaishouItemCollectSamples(kuaishouItemCollectSamples);
            returnJson.put("code", 0);
            returnJson.put("message", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @PutMapping("/updateTask")
    public JSONObject updateTask(@RequestBody KuaishouItemCollectSamples kuaishouItemCollectSamples) {
        JSONObject returnJson = new JSONObject();
        try {
            Long id = kuaishouItemCollectSamples.getId();
            if (Check.isNull(id)) {
                throw new Exception("id不能为空");
            }

            String collectSampleDesc = kuaishouItemCollectSamples.getCollectSampleDesc();
            if (Check.isNull(collectSampleDesc)) {
                kuaishouItemCollectSamples.setCollectSampleDesc("转审上传作业");
            }
            int i = kuaishouItemCollectSamplesService.updateKuaishouItemCollectSamples(kuaishouItemCollectSamples);
            if (i > 0) {
                List<Integer> statusList = new ArrayList<>();
                statusList.add(4);
                statusList.add(5);
                for (int j = 0; j < statusList.size(); j++) {
                    Integer status = statusList.get(j);
                    KuaishouItemCollectSampleLog sampleLog = new KuaishouItemCollectSampleLog();
                    sampleLog.setUserId(kuaishouItemCollectSamples.getUserId());
                    sampleLog.setUserName(kuaishouItemCollectSamples.getUserName());
                    sampleLog.setSampleId(id);
                    sampleLog.setCollectSampleStatus(status);
                    sampleLog.setCreateTime(new Date());
                    sampleLog.setUpdateTime(new Date());
                    kuaishouItemCollectSamplesService.insertLog(sampleLog);
                }
            }
            returnJson.put("code", 0);
            returnJson.put("message", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }

    @GetMapping("/updateCourierNumber")
    public JSONObject updateCourierNumber(Long id, String courierNumber, String companyCode) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(id)) {
                throw new Exception("id不能为空");
            }
            if (Check.isNull(courierNumber)) {
                throw new Exception("快递单号不能为空");
            }
            if (Check.isNull(companyCode)) {
                throw new Exception("公司编号不能为空");
            }

            if (courierNumber.contains(" ") || courierNumber.contains(".") || courierNumber.contains("、") || courierNumber.contains("，") || courierNumber.contains("@") || courierNumber.contains("#")) {
                throw new Exception("快递单号不能包含空格及特殊字符");
            }
            KuaishouItemCollectSamples kuaishouItemCollectSamples = new KuaishouItemCollectSamples();
            kuaishouItemCollectSamples.setId(id);
            kuaishouItemCollectSamples.setCollectSampleDesc("商品已发货");
            kuaishouItemCollectSamples.setCourierNumber(courierNumber);
            kuaishouItemCollectSamples.setCourierNumberTime(new Date());
            int i = kuaishouItemCollectSamplesService.updateKuaishouItemCollectSamples(kuaishouItemCollectSamples);
            if (i > 0) {
                kuaishouItemCollectSamplesService.subscribe(id, courierNumber, companyCode);
            }
            returnJson.put("code", 0);
            returnJson.put("message", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/detail")
    public JSONObject detail(Long id) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(id)) {
                throw new Exception("id不能为空");
            }
            returnJson = kuaishouItemCollectSamplesService.getDetail(id);
            returnJson.put("code", 0);
            returnJson.put("message", "查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }

    @GetMapping("/courierNumberInfo")
    public JSONObject courierNumberInfo(String courierNumber) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(courierNumber)) {
                throw new Exception("快递单号不能为空");
            }
            JSONObject data = kuaishouItemCollectSamplesService.courierNumberInfo(courierNumber);
            returnJson.put("data", data);
            returnJson.put("code", 0);
            returnJson.put("message", "查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }

    @PutMapping("/testSubscribe")
    public JSONObject testSubscribe(String phone, String courierNumber, String code) {
        JSONObject returnJson = new JSONObject();
        try {
            SubscribeParameters subscribeParameters = new SubscribeParameters();
            subscribeParameters.setCallbackurl("http://ruixuan.api.tjyourong.com.cn/itemCollectSamples/callback");
            subscribeParameters.setPhone(phone);
            SubscribeParam subscribeParam = new SubscribeParam();
            subscribeParam.setParameters(subscribeParameters);
            subscribeParam.setCompany(code);
            subscribeParam.setNumber(courierNumber);
            subscribeParam.setKey("BPEQUJxB9244");
            SubscribeReq subscribeReq = new SubscribeReq();
            subscribeReq.setSchema(ApiInfoConstant.SUBSCRIBE_SCHEMA);
            subscribeReq.setParam(new Gson().toJson(subscribeParam));
            IBaseClient subscribe = new Subscribe();
            JSONObject jsonObject = JSONObject.parseObject(subscribe.execute(subscribeReq).getBody());
            System.err.println(jsonObject);
            System.out.println(subscribe.execute(subscribeReq));
            returnJson.put("code", 0);
            returnJson.put("message", "调用成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @PostMapping("/callback")
    public SubscribeResp callback(HttpServletRequest request) {
        SubscribeResp subscribeResp = new SubscribeResp();
        try {
            String param = request.getParameter("param");
            log.info("快递回调信息：{}", param);
            JSONObject paramJson = JSONObject.parseObject(param);
            if (Check.isNull(paramJson)) {
                throw new Exception("回调信息为空");
            }
            String status = paramJson.getString("status");
            String message = paramJson.getString("message");
            JSONObject lastResult = paramJson.getJSONObject("lastResult");
            if (!Check.isNull(lastResult)) {
                String state = lastResult.getString("state");
                String nu = lastResult.getString("nu");
                String com = lastResult.getString("com");
                if ("3".equals(state)) {
                    Integer sampleStatus = kuaishouItemCollectSamplesService.getStatusByCourierNumbe(nu);
                    if (!Check.isNull(sampleStatus)) {
                        if (sampleStatus < 5) { // 防止快递重复回调
                            KuaishouItemCollectSamples updateSample = new KuaishouItemCollectSamples();
                            updateSample.setCourierNumber(nu);
                            updateSample.setCollectSampleStatus(5);
                            updateSample.setCollectSampleDesc("快递已签收，待上传作业");
                            kuaishouItemCollectSamplesService.updateByNum(updateSample);
                        }
                    }
                } else if ("0".equals(state) && "abort".equals(status) && message.contains("无记录")) {
                    KuaishouItemCollectSamples updateSample = new KuaishouItemCollectSamples();
                    updateSample.setCourierNumber(nu);
                    updateSample.setCollectSampleDesc("单号异常");
                    kuaishouItemCollectSamplesService.updateByNum(updateSample);
                }
                JSONArray data = lastResult.getJSONArray("data");
                KuaishouItemCollectSampleExpress express = new KuaishouItemCollectSampleExpress();
                express.setCourierNumber(nu);
                express.setCom(com);
                express.setState(state);
                if (!Check.isNull(data)) {
                    express.setExpressData(data.toJSONString());
                }
                kuaishouItemCollectSamplesService.replaceExpress(express);
            }
            subscribeResp.setResult(Boolean.TRUE);
            subscribeResp.setReturnCode("200");
            subscribeResp.setMessage("回调成功");
        } catch (Exception e) {
            e.printStackTrace();
            subscribeResp.setResult(Boolean.FALSE);
            subscribeResp.setReturnCode("-1");
            subscribeResp.setMessage(e.getMessage());
        }
        return subscribeResp;
    }


    @GetMapping("/copyInfo")
    public JSONObject copyInfo(String promoterId) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(promoterId)) {
                throw new Exception("请传入达人ID");
            }
            JSONObject copyJson = kuaishouItemCollectSamplesService.getCopyInfo(promoterId);
            returnJson.put("code", 0);
            returnJson.put("message", "调用成功");
            returnJson.put("data", copyJson);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @DeleteMapping("/remove")
    public AjaxResult remove(Long id) {
        return toAjax(kuaishouItemCollectSamplesService.deleteKuaishouItemCollectSamplesById(id));
    }

    /**
     * 认领商品列表导出
     *
     * @return
     */
    @PostMapping("/exportCollectSamples")
    @ApiOperation(value = "认领商品列表")
    @ResponseBody
    public void exportCollectSamples(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject requestJson) throws IOException {
        Map<String, Object> requestMap = new HashMap<>();
        if (!Check.isNull(requestJson.getJSONArray("ids"))) {
            requestMap.put("ids", requestJson.getJSONArray("ids"));
        }
        List<JSONObject> list = kuaishouItemCollectSamplesService.exportCollectSamples(requestMap);
        List<List<Object>> exportList = new ArrayList<>();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject date = list.get(i);
                List<Object> export = new ArrayList();
                export.add(date.getString("id"));
                export.add(date.getString("itemId"));
                export.add(date.getString("itemTitle"));
                export.add(date.getString("promoterId"));
                export.add(date.getString("promoterNickName"));
                export.add(date.getString("status"));
                JSONObject copyJson = kuaishouItemCollectSamplesService.getCopyInfo(date.getString("promoterId"));
                if (!Check.isNull(copyJson)) {
                    export.add(copyJson.getString("fansNumber"));
                    export.add(copyJson.getString("totalSale"));
                }
                export.add(date.getString("sampleCount"));
                export.add(date.getString("sampleRequirement"));
                export.add(date.getString("consignee"));
                export.add(date.getString("promoterPhone"));
                export.add(date.getString("promoterAddress"));
                exportList.add(export);
            }
        }
        String[] headers = {"id", "商品ID", "商品名称", "达人ID", "达人昵称", "领样状态", "粉丝数", "销售额", "领样数量", "领样规则", "收件人", "收件人手机号码", "收件人地址"};
        OutputStream os = response.getOutputStream();
        ExportExcelUtils eeu = new ExportExcelUtils();
        XSSFWorkbook workbook = new XSSFWorkbook();
        eeu.exportExcel(workbook, 0, "领样列表", headers, exportList);
        this.setResponseHeader(response, "领样列表.xls");
        workbook.write(os);
        os.flush();
        os.close();
    }


    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @GetMapping("/getMediaId")
    @ApiOperation(value = "工作台——个人信息")
    public JSONObject getMediaId(Long userId) {
        JSONObject returnJson = new JSONObject();
        try {

            String mediaId = null;
            String depName = sysUserService.getDepName(userId);
            if (depName.contains("抖音")) {
                mediaId = "1";
            } else {
                mediaId = "2";
            }
            returnJson.put("code", 0);
            returnJson.put("message", "success");
            returnJson.put("data", mediaId);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/getPersonalInfo")
    @ApiOperation(value = "工作台——个人信息")
    public JSONObject getPersonalInfo(@ApiParam("创建人ID") @RequestParam(value = "userId", required = true) Long userId,
                                      @ApiParam("类型，1-渠道；2-招商") @RequestParam(value = "type", required = true) String type) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(userId)) {
                throw new Exception("请传入人员ID");
            }
            return kuaishouItemCollectSamplesService.getPersonalInfo(userId, type);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/getOrderData")
    @ApiOperation(value = "工作台——订单数据")
    public JSONObject getOrderData(@ApiParam("创建人ID") @RequestParam(value = "userId", required = true) Long userId,
                                   @ApiParam("开始日期") @RequestParam(value = "statDate", required = false) String startDate,
                                   @ApiParam("结束日期") @RequestParam(value = "endDate", required = false) String endDate,
                                   @ApiParam("类型，1-渠道；2-招商") @RequestParam(value = "type", required = true) String type,
                                   @ApiParam("媒体，1-抖音；2-快手") @RequestParam(value = "mediaId", required = false) String mediaId
    ) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(userId)) {
                throw new Exception("请传入人员ID");
            }
            return kuaishouItemCollectSamplesService.getOrderData(userId, startDate, endDate, type, mediaId);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/getDataAnalysis")
    @ApiOperation(value = "工作台——数据分析")
    public JSONObject getDataAnalysis(@ApiParam("创建人ID") @RequestParam(value = "userId", required = true) Long userId,
                                      @ApiParam("开始日期") @RequestParam(value = "statDate", required = false) String startDate,
                                      @ApiParam("结束日期") @RequestParam(value = "endDate", required = false) String endDate,
                                      @ApiParam("类型，1-渠道；2-招商") @RequestParam(value = "type", required = true) String type,
                                      @ApiParam("媒体，1-抖音；2-快手 ") @RequestParam(value = "mediaId", required = false) String mediaId) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(userId)) {
                throw new Exception("请传入人员ID");
            }
            return kuaishouItemCollectSamplesService.getDataAnalysis(userId, startDate, endDate, type, mediaId);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }

    @GetMapping("/queryProductList")
    @ApiOperation(value = "查询商品列表")
    public TableDataInfo queryProductList(
            @ApiParam("商品ID") @RequestParam(value = "itemId", required = false) Long itemId,
            @ApiParam("商品标题") @RequestParam(value = "itemTitle", required = false) String itemTitle,
            @ApiParam("达人id") @RequestParam(value = "promoterId", required = false) String promoterId,
            @ApiParam("达人昵称") @RequestParam(value = "promoterNickName", required = false) String promoterNickName,
            @ApiParam("商品单价起始价") @RequestParam(value = "reservePriceStart", required = false) Double reservePriceStart,
            @ApiParam("商品单价结束价") @RequestParam(value = "reservePriceEnd", required = false) Double reservePriceEnd,
            @ApiParam("有效订单数起始数") @RequestParam(value = "validorderStart", required = false) Double validorderStart,
            @ApiParam("有效订单数结束数") @RequestParam(value = "validorderEnd", required = false) Double validorderEnd,
            @ApiParam("起始时间") @RequestParam(value = "startDate", required = true) String startDate,
            @ApiParam("结束时间") @RequestParam(value = "endDate", required = true) String endDate
    ) {
        Map<String, Object> map = new HashMap<>();
        map.put("itemId", itemId);
        map.put("itemTitle", itemTitle);
        map.put("promoterId", promoterId);
        map.put("promoterNickName", promoterNickName);
        map.put("reservePriceStart", reservePriceStart);
        map.put("reservePriceEnd", reservePriceEnd);
        map.put("validorderStart", validorderStart);
        map.put("validorderEnd", validorderEnd);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        JSONObject returnJson = new JSONObject();
        try {
            List<JSONObject> list = kuaishouItemCollectSamplesService.queryProductList(map);
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 激励列表导出
     *
     * @return
     */
    @PostMapping("/exportProductList")
    @ApiOperation(value = "激励列表导出")
    public void exportProductList(HttpServletResponse response, @RequestBody Map<String, Object> map) throws IOException {
        List<JSONObject> list = kuaishouItemCollectSamplesService.exportProductList(map);
        List<List<Object>> exportList = new ArrayList<>();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject date = list.get(i);
                List<Object> export = new ArrayList();
                export.add(date.getString("promoterNickName") + "（" + date.getString("promoterId") + "）");
                export.add(date.getString("itemTitle") + "（" + date.getString("itemId") + "）");
                export.add(date.getBigDecimal("reservePrice").divide(new BigDecimal("100")));
                export.add(date.getBigDecimal("orderAmount").divide(new BigDecimal("100")));
                export.add(date.getString("validorder"));
                export.add(date.getBigDecimal("regimentalPromotionAmount").divide(new BigDecimal("100")));
                exportList.add(export);
            }
        }
        String[] headers = {"达人名称", "商品名称", "商品单价", "销售额", "有效订单", "预估服务费"};
        OutputStream os = response.getOutputStream();
        ExportExcelUtils eeu = new ExportExcelUtils();
        XSSFWorkbook workbook = new XSSFWorkbook();
        eeu.exportExcel(workbook, 0, "激励列表", headers, exportList);
        this.setResponseHeader(response, "激励列表.xls");
        workbook.write(os);
        os.flush();
        os.close();
    }


    @PostMapping("/batchProcess")
    @ResponseBody
    public JSONObject batchProcess(@RequestBody JSONObject requestJson) {
        JSONObject returnJson = new JSONObject();
        try {
            JSONArray ids = requestJson.getJSONArray("ids");
            if (Check.isNull(ids)) {
                throw new Exception("请传入需要审核的领样ID");
            }
            Integer status = requestJson.getInteger("status");
            if (Check.isNull(status)) {
                throw new Exception("请传入审核状态");
            }
            Long userId = requestJson.getLong("userId");
            if (Check.isNull(userId)) {
                throw new Exception("请传入审核人id");
            }
            String userName = requestJson.getString("userName");
            if (Check.isNull(userName)) {
                throw new Exception("请传入审核人姓名");
            }
            kuaishouItemCollectSamplesService.batchProcess(ids, status);
            List<KuaishouItemCollectSampleLog> logs = new ArrayList<>();
            for (int i = 0; i < ids.size(); i++) {
                Long id = ids.getLong(i);
                KuaishouItemCollectSampleLog sampleLog = new KuaishouItemCollectSampleLog();
                sampleLog.setUserId(userId);
                sampleLog.setUserName(userName);
                sampleLog.setSampleId(id);
                sampleLog.setCollectSampleStatus(status);
                sampleLog.setCreateTime(new Date());
                sampleLog.setUpdateTime(new Date());
                logs.add(sampleLog);
            }

            if (!Check.isNull(logs)) {
                kuaishouItemCollectSamplesService.batchAddLogs(logs);
            }
            returnJson.put("code", 0);
            returnJson.put("message", "批量审核通过");
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;

    }


    @GetMapping("/samplesCheck")
    @ResponseBody
    public JSONObject samplesCheck(Long itemId, String promoterId, Long userId) {
        JSONObject returnJson = new JSONObject();
        try {

            KuaishouItemList itemInfoByItemId = itemListService.getItemInfoByItemId(itemId);
            if (Check.isNull(itemInfoByItemId)) {
                throw new Exception("该商品未录入");
            }

            Integer activityItemStatus = itemInfoByItemId.getActivityItemStatus();
            if (activityItemStatus == 3 || activityItemStatus == 4 || activityItemStatus == 5) {
                throw new Exception("该商品已下架或失效");
            }

            KuaishouPromoter onlyPromoterInfo = promoterService.getOnlyPromoterInfoByUserId(promoterId, userId);
            if (Check.isNull(onlyPromoterInfo)) {
                throw new Exception("该达人未录入");
            }

          /*  Long id = null;
            KuaishouPromoter userPromoterInfo = promoterService.getOnlyPromoterInfoByUserId(promoterId, userId);
            if (!Check.isNull(userPromoterInfo)) {
                id = userPromoterInfo.getId();
            } else {
                id = onlyPromoterInfo.getId();
            }*/
            returnJson.put("code", 0);
            returnJson.put("message", "校验通过");
            returnJson.put("id", onlyPromoterInfo.getId());
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;

    }

    /**
     * 定时改变状态：
     * 达人出单量超过50， 状态：待上传作业 -> 审核通过
     */
    @GetMapping("/updateStatusToApproved")
    public void updateStatusToApproved() {
        kuaishouItemCollectSamplesService.checkAndUpdateStatus();
    }

}


