package com.zfire.mall.manager.controller.wallet;

import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zfire.mall.manager.annotation.ZfireList;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.listV2.RebateOrderVO;
import com.zfire.mall.manager.bean.listV2.SaleTypeVO;
import com.zfire.mall.manager.bean.listV2.dto.ExamineZfireParamBean;
import com.zfire.mall.manager.bean.rebateorder.RebateOrderItemBean;
import com.zfire.mall.manager.bean.wallet.RebateMessageBean;
import com.zfire.mall.manager.bean.wallet.RebateOrderAck;
import com.zfire.mall.manager.bean.wallet.RebateOrderBean;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.logic.wallet.RebateOrderLogic;
import com.zfire.mall.manager.plus.entity.RebateOrderItem;
import com.zfire.mall.manager.utils.CommonUtils;
import com.zfire.mall.manager.utils.excel.ExcelUtils;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "返利单API", tags ={"返利单API"} )
@RequestMapping(value = "/rebate/order", produces = "application/json; charset=utf-8")
public class RebateOrderController {

    @Autowired
    RebateOrderLogic rebateOrderLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;


    @ZfireList
    @PostMapping("/list/v2")
    @ApiOperation("列表V2")
    public ResponseHelper<IPage<RebateOrderVO>> listV2(
            @RequestBody ExamineZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        IPage<RebateOrderVO> page = rebateOrderLogic.listV2(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<RebateOrderVO>() {});
    }

    @PostMapping("/list/v2/export")
    @ApiOperation("列表V2-导出")
    public void listExportV2(
            @RequestBody ExamineZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<RebateOrderVO> list = rebateOrderLogic.listV2(zfireParamBean);
        //3.导出
        FieldUtils.exportData(list.getRecords(),zfireParam.getExportFields(),request,response);
    }



    @GetMapping("/list")
    @ApiOperation(value = "列表")
    public ResponseHelper<IPage<RebateOrderItem>> list(
            @ApiParam(value = "返利单号",required = false) @RequestParam(required = false) String id,
            @ApiParam(value = "经销商编码",required = false) @RequestParam(required = false) String customerNumber,
            @ApiParam(value = "经销商名称",required = false) @RequestParam(required = false) String customerName,
            @ApiParam(value = "钱包名称(返利类型)",required = false) @RequestParam(required = false) String walletName,
            @ApiParam(value = "返利日期开始时间",required = false) @RequestParam(required = false) String startTime,
            @ApiParam(value = "返利日期结束时间",required = false) @RequestParam(required = false) String endTime,
            @ApiParam(value = "是否已确认 true=是 false=否",required = false) @RequestParam(required = false) Boolean isConfirm,
            @ApiParam(value = "是否已复核 true=是 false=否",required = false) @RequestParam(required = false) Boolean isSecondExamine,
            @ApiParam(value = "审核状态 SAVE=保存 WAIT=待审核 OK_ONE=初审通过  FAIL_ONE=初审不通过  OK=复核通过 FAIL=不通过 CLOSE=已关闭,OK_ONE_AND_CONFIRM=商家已确认未复核",required = false)
            @RequestParam(required = false) String examineStatus,
            @ApiParam(value = "制单人",required = false) @RequestParam(required = false) String createBy,
            @ApiParam(value = "审核人",required = false) @RequestParam(required = false) String examineBy,
            @ApiParam(value = "备注1",required = false) @RequestParam(required = false) String remark1,
            @ApiParam(value = "页号",required = true) @RequestParam(required = true) Integer pageNum,
            @ApiParam(value = "页大小",required = true) @RequestParam(required = true) Integer pageSize
    ) throws Exception {
        IPage<RebateOrderItem> list = rebateOrderLogic.list(id,customerNumber, customerName, walletName,isConfirm, startTime, endTime,isSecondExamine,
                examineStatus,createBy,examineBy,remark1,pageNum, pageSize);
        return ResponseHelper.success(list);
    }

    @GetMapping("/detail")
    @ApiOperation(value = "详情")
    public ResponseHelper<RebateOrderBean> detail(
            @ApiParam(value = "id",required = true) @RequestParam(required = true) String id,
             @ApiParam(value = "是否已确认 true=是 false=否",required = false) @RequestParam(required = false) Boolean isConfirm
    ) throws Exception {
        RebateOrderBean detail = rebateOrderLogic.detail(id,isConfirm);
        return ResponseHelper.success(detail);
    }

    @PostMapping("/add")
    @ApiOperation(value = "新增")
    public ResponseHelper add(
            @ApiParam(value = "object",required = false) @RequestBody RebateOrderBean rebateOrderBean) throws Exception {
        rebateOrderLogic.add(rebateOrderBean);
        return ResponseHelper.success();
    }

    @PostMapping("/update")
    @ApiOperation(value = "编辑")
    public ResponseHelper update(
            @ApiParam(value = "object",required = false) @RequestBody RebateOrderBean rebateOrderBean) throws Exception {
        rebateOrderLogic.update(rebateOrderBean);
        return ResponseHelper.success();
    }

    @PostMapping("/batchDel")
    @ApiOperation(value = "批量删除")
    public ResponseHelper batchDel(
            @ApiParam(value = "ids",required = true) @RequestParam(required = true) List<String> ids)  {
        rebateOrderLogic.batchDel(ids);
        return ResponseHelper.success();
    }


    @PostMapping("/apply")
    @ApiOperation(value = "提审")
    public ResponseHelper apply(
            @ApiParam(value = "id",required = true) @RequestParam(required = true) String id
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_CUSTOMER + id);
        try {
            if(!obtain.tryLock(5,TimeUnit.SECONDS)){
                return ResponseHelper.error("请勿重复操作");
            }
            rebateOrderLogic.apply(id);
        }finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/apply/batch")
    @ApiOperation(value = "批量提审")
    public ResponseHelper batchApply(
            @ApiParam(value = "ids",required = true) @RequestParam(required = true) List<String> ids
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_REBATE_APPLY + ids.toString());
        try {
            if(!obtain.tryLock(5,TimeUnit.SECONDS)){
                return ResponseHelper.error("请勿重复操作");
            }
            rebateOrderLogic.batchApply(ids);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }



    @PostMapping("/examine")
    @ApiOperation(value = "审核")
    public ResponseHelper examine(
            @ApiParam(value = "id",required = true) @RequestParam(required = true) String id,
            @ApiParam(value = "审核状态(OK=通过 FAIL=不通过)",required = true) @RequestParam(required = true) String examineStatus,
            @ApiParam(value = "审核备注",required = true) @RequestParam(required = true) String examineRemark
    ) throws Exception {
        rebateOrderLogic.examine(id,examineStatus,examineRemark);
        return ResponseHelper.success();
    }


    @PostMapping("/examine/batch")
    @ApiOperation(value = "批量审核")
    public ResponseHelper batchExamine(
            @ApiParam(value = "id",required = true) @RequestParam(required = true) List<String> ids,
            @ApiParam(value = "审核状态(OK=通过 FAIL=不通过)",required = true) @RequestParam(required = true) String examineStatus,
            @ApiParam(value = "审核备注",required = true) @RequestParam(required = true) String examineRemark) throws Exception{
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_REBATE_EXAMINE + ids.toString());
        try {
            if(!obtain.tryLock(5,TimeUnit.SECONDS)){
                return ResponseHelper.error("请勿重复操作");
            }
            for(String idItem:ids){
                rebateOrderLogic.examine(idItem,examineStatus,examineRemark);
            }
        }
        finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/cancel")
    @ApiOperation(value = "取消审核")
    public ResponseHelper cancel(
            @ApiParam(value = "id",required = true) @RequestParam(required = true) String id,
            @ApiParam(value = "取消审核备注",required = false) @RequestParam(required = false) String cancelRemark
    ) throws Exception {
        rebateOrderLogic.cancel(id,cancelRemark);
        return ResponseHelper.success();
    }


    @PostMapping("/examine2")
    @ApiOperation(value = "复核")
    public ResponseHelper examine2(
            @ApiParam(value = "id",required = true) @RequestBody RebateOrderItemBean rebateOrderItemBean
            ) throws Exception {
        rebateOrderLogic.examine2(rebateOrderItemBean);
        return ResponseHelper.success();
    }


    @PostMapping("/examine2/batch")
    @ApiOperation(value = "批量复核")
    public ResponseHelper batchExamine2(
            @ApiParam(value = "id", required = true) @RequestParam(required = true) List<String> ids,
            @ApiParam(value = "examineStatus", required = true) @RequestParam(required = true) String examineStatus,
            @ApiParam(value = "备注", required = false) @RequestParam(required = false) String remark
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_REBATE_EXAMINE2 + "batch");
        try {
            if(!obtain.tryLock(5,TimeUnit.SECONDS)){
                return ResponseHelper.error("请勿重复操作");
            }
            rebateOrderLogic.batchExamine2(ids,examineStatus,remark);
        }
        finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }


    @PostMapping("/ack")
    @ApiOperation(value = "客户确认")
    public ResponseHelper ack(
            @RequestBody List<RebateOrderAck> list
    ) throws Exception {
        rebateOrderLogic.ack(list);
        return ResponseHelper.success();
    }

    @PostMapping("/ackUpdate")
    @ApiOperation(value = "复核前-编辑")
    public ResponseHelper ackUpdate(
            @RequestBody List<RebateOrderAck> list) {
        rebateOrderLogic.ackUpdate(list);
        return ResponseHelper.success();
    }


    @GetMapping("/download")
    @ApiOperation("下载销售返利单模板")
    public void download(
            HttpServletResponse response
    ) throws IOException {
        CommonUtils.downloadFile("rebate_order.xlsx",response);
    }

    @PostMapping("/import")
    @ApiOperation("导入销售返利单数据")
    public ResponseHelper importRebateOrder(MultipartFile file) throws Exception {
        List<Object> objects = ExcelUtils.importExcel(file);
        List<String>  ids = rebateOrderLogic.importRebateOrder(objects);
        return ResponseHelper.success(ids);
    }

//    @PostMapping("/import/data")
//    @ApiOperation("导入销售返利单-返回数据")
//    public ResponseHelper<RebateOrderBean> importRebateOrderData(MultipartFile file) throws Exception {
//        List<Object> objects = ExcelUtils.importExcel(file);
//        RebateOrderBean  rebateOrderBean = rebateOrderLogic.importRebateOrderData(objects);
//        return ResponseHelper.success(rebateOrderBean);
//    }

    @GetMapping("/msg")
    @ApiOperation(value = "返利通知获取信息接口")
    public ResponseHelper<RebateMessageBean> rebateMessage(){
        RebateMessageBean rebateMessageBean = rebateOrderLogic.rebateMessage();
        return ResponseHelper.success(rebateMessageBean);
    }


    @GetMapping("/export")
    @ApiOperation(value = "返利单列表-导出")
    public void export(
            @ApiParam(value = "返利单号",required = false) @RequestParam(required = false) String id,
            @ApiParam(value = "经销商编码",required = false) @RequestParam(required = false) String customerNumber,
            @ApiParam(value = "经销商名称",required = false) @RequestParam(required = false) String customerName,
            @ApiParam(value = "钱包名称(返利类型)",required = false) @RequestParam(required = false) String walletName,
            @ApiParam(value = "返利日期开始时间",required = false) @RequestParam(required = false) String startTime,
            @ApiParam(value = "返利日期结束时间",required = false) @RequestParam(required = false) String endTime,
            @ApiParam(value = "是否已确认 true=是 false=否",required = false) @RequestParam(required = false) Boolean isConfirm,
            @ApiParam(value = "是否已复核 true=是 false=否",required = false) @RequestParam(required = false) Boolean isSecondExamine,
            @ApiParam(value = "审核状态",required = false) @RequestParam(required = false) String examineStatus,
            @ApiParam(value = "制单人",required = false) @RequestParam(required = false) String createBy,
            @ApiParam(value = "审核人",required = false) @RequestParam(required = false) String examineBy,
            @ApiParam(value = "备注1",required = false) @RequestParam(required = false) String remark1,
            HttpServletRequest request,HttpServletResponse response
    ) throws Exception {
        IPage<RebateOrderItem> list = rebateOrderLogic.list(id,customerNumber, customerName, walletName,isConfirm,
                startTime, endTime,isSecondExamine,examineStatus,createBy,examineBy,remark1, 1, -1);
        ExcelData excelData = rebateOrderLogic.export(list.getRecords());
        ExcelUtils.exportExcel(request,response,"销售返利单.xlsx",excelData);
    }


}
