package com.xxfc.platform.order.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.order.biz.OrderMemberDetailBiz;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderMemberDetail;
import com.xxfc.platform.order.pojo.dto.MemberOrderFindDTO;
import com.xxfc.platform.order.pojo.order.MemberBO;
import com.xxfc.platform.order.pojo.order.add.AddMemberDTO;
import com.xxfc.platform.order.pojo.vo.MemberOrderPageVo;
import com.xxfc.platform.order.service.OrderMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Controller
@RequestMapping("orderMember")
@Api(value = "会员订单", tags = {"会员订单"})
@IgnoreClientToken
public class OrderMemberController extends BaseController<OrderMemberDetailBiz, OrderMemberDetail> {

    @Autowired
    OrderMemberService orderMemberService;

    @Autowired
    UserFeign userFeign;

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "确认会员订单")
    public ObjectRestResponse<BaseOrder> add(@RequestBody AddMemberDTO dto) {
        MemberBO bo = BeanUtil.toBean(dto, MemberBO.class);
        bo.setTickerNo(StrUtil.isNotBlank(dto.getTickerNos())?
                StrUtil.splitTrim(dto.getTickerNos(), ","):null);
        //查询会员等级实体
//        bo.setBaseUserMemberLevel(userFeign.memberEntityList(BeanUtil.beanToMap(new BaseUserMemberLevel(){{
//            setId(dto.getMemberLevelId());
//        }})).getData().get(0));

//        bo.setMemberLevelId(bo.getBaseUserMemberLevel().getId());

        bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
        //查询优惠券
        orderMemberService.createOrder(bo);
        return ObjectRestResponse.succ(bo.getOrder());
        //return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "为了更好地为您提供会员服务，请联系在线客服（或拨打客服电话：4000-369-369）");
    }

    /**
     * 会员订单列表
     *
     * @param memberOrderFindDTO
     * @return
     */
    @PostMapping("/page")
    @ResponseBody
    public ObjectRestResponse<MemberOrderPageVo> listMemberOrderPage(@RequestBody MemberOrderFindDTO memberOrderFindDTO) {
        MemberOrderPageVo memberOrderPageVo = orderMemberService.listMemberOrderPage(memberOrderFindDTO);
        return ObjectRestResponse.succ(memberOrderPageVo);
    }

    @PostMapping("/export")
    public void exportMemberOrders(@RequestBody MemberOrderFindDTO memberOrderFindDTO, HttpServletResponse response){
        try {
            String name = DateTimeFormatter.ofPattern("YYYYMMddHHmmss").format(LocalDateTime.now());
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String filename = String.format("%s-MemberOrder.xlsx",name);
            response.setHeader("Content-Disposition","attachment;filename="+ new String(filename.getBytes(), "iso8859-1"));
            ServletOutputStream outputStream = response.getOutputStream();
            orderMemberService.exportMemberOrderData(memberOrderFindDTO, name, outputStream);
            response.setCharacterEncoding("UTF-8");
        }catch (Exception ex){
            throw  new BaseException("导出数据失败");
        }
    }
}