package com.liquidnet.client.admin.web.controller.zhengzai.kylin;

import cn.hutool.core.text.UnicodeUtil;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.common.annotation.Log;
import com.liquidnet.client.admin.common.core.controller.BaseController;
import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.core.page.TableDataInfo;
import com.liquidnet.client.admin.common.enums.BusinessType;
import com.liquidnet.client.admin.common.utils.ShiroUtils;
import com.liquidnet.client.admin.zhengzai.kylin.service.impl.KylinOrderRefundsServiceImpl;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.constant.KylinTableStatusConst;
import com.liquidnet.service.kylin.dao.OrderRefundDao;
import com.liquidnet.service.kylin.dto.param.RefundApplyParam;
import com.liquidnet.service.kylin.dto.param.RefundSearchParam;
import com.liquidnet.service.kylin.dto.vo.returns.KylinOrderRefundsVo;
import com.liquidnet.service.kylin.dto.vo.returns.RefundOrderDetailsVo;
import com.liquidnet.service.kylin.service.IKylinOrderRefundsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * <p>
 * 后台单订单退款 服务实现类
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-05-25 10:58 上午
 */
@Controller
@RequestMapping("/kylin/refund")
public class KylinOrderRefundAdminController extends BaseController {

    private String prefix = "zhengzai/kylin/refund";

    @Autowired
    private KylinOrderRefundsServiceImpl kylinOrderRefundsServiceImpl;

    @RequiresPermissions("kylin:refund:view")
    @GetMapping()
    public String refund() {
        return prefix + "/refund";
    }

    @Log(title = "订单退款列表", businessType = BusinessType.DETAIL)
    @RequiresPermissions("kylin:refund:detail")
    @GetMapping(value = "/details/{orderRefundId}")
    public String detail(@PathVariable("orderRefundId") String orderRefundId, ModelMap mmap) {
        KylinOrderRefundsVo result = null;
        result = kylinOrderRefundsServiceImpl.detail(orderRefundId);
        mmap.put("KylinOrderRefundsVo", result);
        return prefix + "/details";
    }

    @Log(title = "订单退款列表", businessType = BusinessType.LIST)
    @RequiresPermissions("kylin:refund:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo refundList(RefundSearchParam refundSearchParam) {
        PageInfo<OrderRefundDao> result = kylinOrderRefundsServiceImpl.refundList(refundSearchParam);
        return getDataTable(result.getList());
    }

    @GetMapping("applyView")
    public String applyView() {
        return prefix + "/applyView";
    }

    @Log(title = "订单退款列表", businessType = BusinessType.DETAIL)
    @PostMapping("applyOrder")
    @ResponseBody
    public AjaxResult applyOrder(RefundApplyParam refundApplyParam) {
        return kylinOrderRefundsServiceImpl.orderDetails(refundApplyParam.getOrderCode());
    }

    @Log(title = "订单退款列表", businessType = BusinessType.INSERT)
    @RequiresPermissions("kylin:refund:apply")
    @PostMapping("apply")
    @ResponseBody
    public AjaxResult refundApply(RefundApplyParam refundApplyParam) {
        try {
            String authId = ShiroUtils.getUserId().toString();
            String authName = ShiroUtils.getLoginName();
            ResponseDto res = kylinOrderRefundsServiceImpl.refundApply(refundApplyParam, authId, authName);
            if (res.isSuccess()) {
                return success();
            } else {
                return error(res.getMessage());
            }
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @Log(title = "订单退款列表", businessType = BusinessType.CANCEL)
    @RequiresPermissions("kylin:refund:cancel")
    @PostMapping("cancel")
    @ResponseBody
    public AjaxResult refundCancel(RefundApplyParam refundApplyParam) {
        try {
            refundApplyParam.setType("cancel");
            String authId = ShiroUtils.getUserId().toString();
            String authName = ShiroUtils.getLoginName();
            ResponseDto res = kylinOrderRefundsServiceImpl.refundCheckStatus(refundApplyParam, authId, authName);
            if (res.isSuccess()) {
                return success();
            } else {
                return error(res.getMessage());
            }
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @Log(title = "订单退款列表", businessType = BusinessType.REAPPLY)
    @RequiresPermissions("kylin:refund:reapply")
    @PostMapping("reapply")
    @ResponseBody
    public AjaxResult refundReapply(RefundApplyParam refundApplyParam) {
        try {
            refundApplyParam.setType("reapply");
            String authId = ShiroUtils.getUserId().toString();
            String authName = ShiroUtils.getLoginName();
            ResponseDto res = kylinOrderRefundsServiceImpl.refundCheckStatus(refundApplyParam, authId, authName);
            if (res.isSuccess()) {
                return success();
            } else {
                return error(res.getMessage());
            }
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    // 一审
    @Log(title = "订单退款列表", businessType = BusinessType.AUDIT)
    @RequiresPermissions("kylin:refund:review")
    @PostMapping("review")
    @ResponseBody
    public AjaxResult refundReview(RefundApplyParam refundApplyParam) {
        try {
            ResponseDto res = null;
            Integer status = refundApplyParam.getStatus();
            String authId = ShiroUtils.getUserId().toString();
            String authName = ShiroUtils.getLoginName();
            if (status == KylinTableStatusConst.ORDER_REFUND_STATUS_APPROVED) { // 通过
                refundApplyParam.setType("approved");
                res = kylinOrderRefundsServiceImpl.refundCheckStatus(refundApplyParam, authId, authName);
            }
            if (status == KylinTableStatusConst.ORDER_REFUND_STATUS_REJECT) { // 驳回
                refundApplyParam.setType("reject");
                res = kylinOrderRefundsServiceImpl.refundCheckStatus(refundApplyParam, authId, authName);
            }
            if (res.isSuccess()) {
                return success();
            } else {
                return error(res.getMessage());
            }
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    // 二审
    @Log(title = "订单退款列表", businessType = BusinessType.AUDIT2)
    @RequiresPermissions("kylin:refund:execute")
    @PostMapping("execute")
    @ResponseBody
    public AjaxResult refundExecute(RefundApplyParam refundApplyParam) {
        try {
            ResponseDto res = null;
            Integer status = refundApplyParam.getStatus();
            String authId = ShiroUtils.getUserId().toString();
            String authName = ShiroUtils.getLoginName();
            if (status == KylinTableStatusConst.ORDER_REFUND_STATUS_UNFILLED) { // 通过
                refundApplyParam.setType("unfilled");
                res = kylinOrderRefundsServiceImpl.refundCheckStatus(refundApplyParam, authId, authName);
            }
            if (status == KylinTableStatusConst.ORDER_REFUND_STATUS_REFUSE) { // 驳回
                refundApplyParam.setType("refuse");
                res = kylinOrderRefundsServiceImpl.refundCheckStatus(refundApplyParam, authId, authName);
            }
            if (res.isSuccess()) {
                return success();
            } else {
                return error(res.getMessage());
            }
        } catch (Exception e) {
            String message = e.getMessage();
            boolean error400 = message.contains("400");
            boolean error401 = message.contains("401");
            if (error400) {
                String[] msg = e.getMessage().split(" ");
                if (msg.length > 0 && null != msg[3]) {
                    String msgStr = UnicodeUtil.toString(msg[3]);
                    Map msgMap = JsonUtils.fromJson(msgStr.replace("[", "").replace("]", ""), Map.class);
                    message = msgMap.get("message").toString();
                }
            } else if (error401) {
                message = message + "无权限";
            }
            return error(message);
        }
    }

    // 主动完成退款 没有批量
    @Log(title = "订单退款列表", businessType = BusinessType.COMPLETE_REFUND)
    @RequiresPermissions("kylin:refund:completed")
    @PostMapping("completed")
    @ResponseBody
    public AjaxResult refundCompleted(RefundApplyParam refundApplyParam) {
        try {
            ResponseDto res = kylinOrderRefundsServiceImpl.refundCompleted(refundApplyParam);
            if (res.isSuccess()) {
                return success();
            } else {
                return error(res.getMessage());
            }
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @Autowired
    IKylinOrderRefundsService kylinOrderRefundsService;

    //    @RequiresPermissions("order:switch:search:code")
    @ApiOperation(value = "根据截取订单号获取全量订单号")
    @GetMapping("/search/code")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "code", value = "订单号", example = ""),
            @ApiImplicitParam(type = "form", required = true, dataType = "int", name = "type", value = "1退款单号 2订单号", example = ""),
    })
    public AjaxResult loginSmsSwitch(@NotNull(message = "订单号不能为空") @RequestParam String code,
                                              @NotNull(message = "类型不能为空") @RequestParam int type) {
        String codeNum = kylinOrderRefundsService.getOrderRefundCode(code,type);
        if(codeNum==null){
            return success("ERROR");
        }else{
            return success(codeNum);
        }
    }

}
