package com.ruixuan.isc.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.annotation.Log;
import com.ruixuan.common.core.controller.BaseController;
import com.ruixuan.common.core.domain.AjaxResult;
import com.ruixuan.common.core.page.TableDataInfo;
import com.ruixuan.common.enums.BusinessType;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.poi.ExcelUtil;
import com.ruixuan.data.utils.ExportExcelUtils;
import com.ruixuan.isc.entity.KuaishouRuleSettlementData;
import com.ruixuan.isc.service.IKuaishouRuleSettlementDataService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2023-05-16
 */
@RestController
@RequestMapping("/settlement")
public class KuaishouRuleSettlementDataController extends BaseController {
    @Autowired
    private IKuaishouRuleSettlementDataService kuaishouRuleSettlementDataService;
    static ExecutorService executorService = Executors.newFixedThreadPool(2);
    static ExecutorService executorPromoterService = Executors.newFixedThreadPool(2);


    @PostMapping("/data")
    @ApiOperation(value = "查询快手达人")
    public void data(@RequestBody JSONObject requestJson) {
        Long statDate = requestJson.getLong("statDate");
        JSONArray data = requestJson.getJSONArray("data");
        if (Check.isNull(data)) {
            return;
        }
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                kuaishouRuleSettlementDataService.data(statDate, data);
            }
        });
    }


    @PostMapping("/promoterData")
    @ApiOperation(value = "查询快手达人")
    public void promoterData(@RequestBody JSONObject requestJson) {
        Long statDate = requestJson.getLong("statDate");
        JSONArray data = requestJson.getJSONArray("data");
        if (Check.isNull(data)) {
            return;
        }
        executorPromoterService.submit(new Runnable() {
            @Override
            public void run() {
                kuaishouRuleSettlementDataService.promoterData(statDate, data);
            }
        });
    }


    @GetMapping("/testData")
    public JSONObject testData(Long relateId, Long promoterId, Long ruleId, Long validOrderNum) {
       /* JSONObject data = kuaishouRuleSettlementDataService.getData();
        JSONArray array = new JSONArray();
        array.add(data);*/


        return kuaishouRuleSettlementDataService.getPromoterRuleData(null, promoterId, ruleId, validOrderNum);
        //  return kuaishouRuleSettlementDataService.getOrderRuleData(relateId, promoterId, ruleId, validOrderNum);

    }


    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/getSettlementList")
    public TableDataInfo list(String statDate, Long promoterId, String promoterName) {
        Long date = Long.valueOf(statDate.replace("-", ""));
        startPage();
        List<JSONObject> list = kuaishouRuleSettlementDataService.getSettlementDate(date, promoterId, promoterName);
        return getDataTable(list);
    }


    @RequestMapping(value = "/exportSettlementList")
    @ResponseBody
    public void exportSettlementList(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject requestJson) throws Exception {
        Long date = Long.valueOf(requestJson.getString("statDate").replace("-", ""));
        List<JSONObject> list = kuaishouRuleSettlementDataService.getSettlementDate(date, null, null);
        List<List<Object>> exportList = new ArrayList<>();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject data = list.get(i);
                List<Object> export = new ArrayList();
                export.add(data.getString("ruleName"));
                export.add(data.getString("itemIds"));
                export.add(data.getString("itemName"));
                export.add(data.getString("itemUserName"));
                export.add(data.getString("promoterId"));
                export.add(data.getString("promoterName"));
                export.add(data.getString("promoterUserName"));
                export.add(data.getString("orderNum"));
                export.add(data.getString("validOrderNum"));
                export.add(data.getString("lastSettlementOrderNum"));
                export.add(data.getString("anchorAmount"));
                export.add(data.getString("referenceAmount"));
                export.add(data.getString("settlementStatusDesc"));
                exportList.add(export);
            }
        }
        String[] headers = {"规则名称", "商品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();
    }

    @GetMapping("/updatePromoterStatus")
    public JSONObject updatePromoterStatus(String statDate, Long promoterId, Integer status) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(statDate)) {
                throw new Exception("请输入日期");
            }
            if (Check.isNull(promoterId)) {
                throw new Exception("请输入达人ID");
            }

            if (Check.isNull(status)) {
                throw new Exception("请输入状态");
            }
            Long date = Long.valueOf(statDate.replace("-", ""));
            kuaishouRuleSettlementDataService.updatePromoterStatus(date, promoterId, status);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }

        return returnJson;
    }


    @GetMapping("/getPromoterSettlementDetail")
    public TableDataInfo getPromoterSettlementDetail(String statDate, Long promoterId, Integer settlementStatus) {
        Long date = Long.valueOf(statDate.replace("-", ""));
        startPage();
        List<JSONObject> list = kuaishouRuleSettlementDataService.getPromoterSettlementDetail(date, promoterId, settlementStatus);
        return getDataTable(list);
    }

    @RequestMapping(value = "/exportPromoterSettlementDetail")
    @ResponseBody
    public void exportPromoterSettlementDetail(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject requestJson) throws Exception {
        Long date = Long.valueOf(requestJson.getString("statDate").replace("-", ""));
        Long promoterId = requestJson.getLong("promoterId");

        List<JSONObject> list = kuaishouRuleSettlementDataService.getPromoterSettlementDetail(date, promoterId, null);
        List<List<Object>> exportList = new ArrayList<>();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject data = list.get(i);
                List<Object> export = new ArrayList();
                export.add(data.getString("ruleName"));
                export.add(data.getString("itemIds"));
                export.add(data.getString("promoterId"));
                export.add(data.getString("promoterName"));
                export.add(data.getString("itemCreateName"));
                export.add(data.getString("promoterCreateName"));
                export.add(data.getString("orderNum"));
                export.add(data.getString("validOrderNum"));
                export.add(data.getString("lastSettlementOrderNum"));
                export.add(data.getString("anchorAmount"));
                export.add(data.getString("referenceAmount"));
                export.add(data.getString("settlementStatusStr"));
                exportList.add(export);
            }
        }
        String[] headers = {"规则名称", "结算商品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();
    }


    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:data:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KuaishouRuleSettlementData kuaishouRuleSettlementData) {
        List<KuaishouRuleSettlementData> list = kuaishouRuleSettlementDataService.selectKuaishouRuleSettlementDataList(kuaishouRuleSettlementData);
        ExcelUtil<KuaishouRuleSettlementData> util = new ExcelUtil<KuaishouRuleSettlementData>(KuaishouRuleSettlementData.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:data:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(kuaishouRuleSettlementDataService.selectKuaishouRuleSettlementDataById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:data:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KuaishouRuleSettlementData kuaishouRuleSettlementData) {
        return toAjax(kuaishouRuleSettlementDataService.insertKuaishouRuleSettlementData(kuaishouRuleSettlementData));
    }

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

    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody KuaishouRuleSettlementData kuaishouRuleSettlementData) {
        return toAjax(kuaishouRuleSettlementDataService.updateKuaishouRuleSettlementData(kuaishouRuleSettlementData));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:data:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(kuaishouRuleSettlementDataService.deleteKuaishouRuleSettlementDataByIds(ids));
    }

    //发送响应流方法
    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();
        }
    }

}

