package com.scm.contract.web.apply;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.scm.contract.model.apply.DictionaryLabelApplicationStatus;
import com.scm.contract.model.apply.LabelApplication;
import com.scm.contract.model.apply.LabelApplicationDataImport;
import com.scm.contract.service.apply.DictionaryLabelApplicationStatusService;
import com.scm.contract.service.apply.LabelApplicationService;
import com.scm.contract.tools.HumpLineAdopter;
import com.scm.contract.tools.OutSnowflakeIdGenerator;
import com.set.direwolf.core.mybatis.Page;
import com.set.direwolf.core.web.BaseController;
import com.set.direwolf.core.web.OperationResult;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zuo
 * @date 2024/6/4 17:43
 */

@Controller
@RequestMapping("${adminPath}/tag/apply")
public class LabelApplicationController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LabelApplicationController.class);

    private final LabelApplicationService entityService;


    private final DictionaryLabelApplicationStatusService statusService;

    @Autowired
    public LabelApplicationController(LabelApplicationService entityService, DictionaryLabelApplicationStatusService statusService) {
        this.entityService = entityService;
        this.statusService = statusService;
    }

    /**
     * 分页查询数据获取
     *
     * @param entity   参数实体
     * @param request  请求
     * @param response 响应
     * @return Page
     */
    @PostMapping("/page")
    public @ResponseBody OperationResult page(@RequestBody LabelApplication entity, HttpServletRequest request, HttpServletResponse response) {
        List<String> tagApplyStateIds = entity.getTagApplyStateIds();
        if (CollectionUtils.isEmpty(tagApplyStateIds)) {
            List<DictionaryLabelApplicationStatus> list = statusService.list(1L);
            List<String> ids = list.stream().map(DictionaryLabelApplicationStatus::getId).distinct().collect(Collectors.toList());
            entity.setTagApplyStateIds(ids);
        }
        Page<LabelApplication> page = Page.bootstrapPage(request, response);
        List<List<String>> orderList = entity.getOrder();
        String defaultOrder = HumpLineAdopter.humpToLine(orderList);
        if (StringUtils.isNotEmpty(defaultOrder)) {
            page.setOrderBy(defaultOrder);
        }
        return OperationResult.buildSuccessResult("获取标签申领分页查询信息成功", entityService.findPage(page, entity));
    }

    @PostMapping("/confirm/pay")
    public @ResponseBody OperationResult confirmPay(@RequestBody List<String> ids) {
        try {
            entityService.confirmPay(ids);
        } catch (Exception e) {
            logger.error("支付确认失败", e);
            return OperationResult.buildFailureResult("支付确认失败", false);
        }
        return OperationResult.buildSuccessResult("支付确认成功", true);
    }

    @PostMapping("/confirm/order")
    public @ResponseBody OperationResult confirmOrder(@RequestBody List<String> ids) {
        return OperationResult.buildSuccessResult("生成订单成功", entityService.confirmOrder(ids));
    }

    @PostMapping("/update/confirm/order")
    public @ResponseBody OperationResult updateConfirmOrder(@RequestBody LabelApplication entity) {
        return OperationResult.buildSuccessResult("修改成功", entityService.updateConfirmOrder(entity));
    }

    @PutMapping("/update")
    public @ResponseBody OperationResult update(@RequestBody LabelApplication entity) {
        return OperationResult.buildSuccessResult("修改成功", entityService.update(entity));
    }

    @GetMapping("/{id}")
    public @ResponseBody OperationResult getById(@PathVariable("id") String id) {
        return OperationResult.buildSuccessResult("获取详情信息成功", entityService.getById(id, true));
    }

    @GetMapping("/order/{id}")
    public @ResponseBody OperationResult orderByID(@PathVariable("id") String id) {
        return OperationResult.buildSuccessResult("获取标签需求单信息成功", entityService.orderById(id, true));
    }

    @Autowired
    private OutSnowflakeIdGenerator outSnowflakeIdGenerator;

    @ApiOperation(value = "下载excel模版", notes = "下载excel模版", produces = "application/octet-stream")
    @GetMapping(value = "/download/template")
    public @ResponseBody void getTemplate(@RequestParam("providerId") String providerId, HttpServletResponse response) {
//    public @ResponseBody void getTemplate(HttpServletResponse response) {
        try {
//            String providerId = "2";
            Map<String, Object> map = entityService.getTemplate(providerId);
            Workbook wb = (Workbook) map.get("wb");
            String providerName = (String) map.get("providerName");
            //设置要导出的文件的名字
            String fileName = "标签申领导入模版-" + providerName + ".xlsx";
            //导出数据
            response.setContentType("application/octet-stream");
            //解决跨域文件名问题
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            //导出失败
            e.printStackTrace();
//            return OperationResult.buildFailureResult("导出失败",false);
        }
//        return OperationResult.buildSuccessResult("导出成功", true);
    }

    @ApiOperation(value = "数据上传", notes = "数据上传", produces = "multipart/form-data; charset=utf-8")
    @PostMapping("/data/import")
    public @ResponseBody OperationResult importData(LabelApplicationDataImport dataImport) {
        return OperationResult.buildSuccessResult("导入成功", entityService.importData(dataImport));
    }

    @DeleteMapping("/{id}")
    public @ResponseBody OperationResult deleteById(@PathVariable("id") String id) {
        return OperationResult.buildSuccessResult("删除成功", entityService.deleteById(id));
    }
}
