package com.ywt.controllers.mg;

import com.ywt.config.DomainConfigurer;
import com.ywt.config.ParameterConfigurer;
import com.ywt.core.*;
import com.ywt.core.utils.*;
import com.ywt.domain.entity.glasses.GoodsOrders;
import com.ywt.domain.models.enums.GetChannelEnum;

import com.ywt.models.ConstantDef;
import com.ywt.models.enums.GoodsOrdersStatusEnum;
import com.ywt.models.enums.PaymentChannelEnum;
import com.ywt.models.enums.PaymentStatusEnum;
import com.ywt.params.mg.order.AmoutListRequest;
import com.ywt.params.mg.order.QueryOrdersListRequest;
import com.ywt.service.GoodsOrderService;
import com.ywt.service.UserService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController("/mg/orders")
@RequestMapping({"/mg/orders"})
@MGRight
@Api(description = "眼睛店后台订单列表")
public class GoodsOrderController {

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

    @Autowired
    private GoodsOrderService goodsOrderService;

    @Autowired
    private UserService userService;

    @Autowired
    private ParameterConfigurer parameterConfigurer;

    @Autowired
    private DomainConfigurer domainConfigurer;

    //查询订单列表
    @MGRight(menuCode = {" /queryOrderList"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    @RequestMapping({"/queryOrderList"})
    BaseResponse queryOrdersList(@RequestBody QueryOrdersListRequest request) {

        DataResponse<HashMap<String, Object>> response = new DataResponse<>();

        try {
            PagedList<GoodsOrders> ordersPagedList = goodsOrderService.queryOrderList(request);
            HashMap<String, Object> map = new HashMap<>();
            if (!Checker.isNone(ordersPagedList.getItems())) {

                List<Map<String, Object>> datas = CollectionUtil.toList(ordersPagedList.getItems(), p -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("id", p.getId());
                    item.put("orderNo", p.getOrderNo());
                    item.put("paymentNo", Checker.getStringValue(p.getPaymentNo()));
                    item.put("patientName", p.getPatientName());
                    item.put("age", p.getAge());
                    item.put("sex", p.getSex());
                    item.put("gender", p.getSex() == 1 ? "男" : "女");
                    item.put("mobile", p.getMobile());
                    String qrCodeUrl = parameterConfigurer.getYwtHttpsMsiteDomain() + String.format(ConstantDef.NFYYBYFY_GOODS_ORDERS_DETAIL_URL, p.getId());
                    item.put("qrCodeUrl", qrCodeUrl);
                    if (!Checker.isNone(p.getGetChannel())) {
                        item.put("getChannel", (GetChannelEnum.valueOf(p.getGetChannel())).getDisplayName());
                    }

                    item.put("payAmount", FormatUtil.intShrink100ToStr(p.getPayAmount()));
                    if (!Checker.isNone(p.getStatus())) {
                        item.put("status", (GoodsOrdersStatusEnum.valueOf(p.getStatus())).getDisplayName());
                    }
                    if (!Checker.isNone(p.getPaymentStatus())) {
                        item.put("paymentStatus", (PaymentStatusEnum.getPaymentStatus(p.getPaymentStatus())).getDisplayName());
                    }


                    if (!Checker.isNone(p.getPaymentChannel())) {
                        item.put("paymentChannel", PaymentChannelEnum.WeChat == PaymentChannelEnum.valueOf(p.getPaymentChannel()) ? "微信支付" : "其他支付方式");
                    } else {
                        item.put("paymentChannel", "");
                    }
                    String createTime = DateUtil.convertToString(p.getCreateTime());
                    item.put("createTime", createTime);

                    String paymentTime = DateUtil.convertToString(p.getPaymentTime());
                    if (!Checker.isNull(paymentTime)) {
                        item.put("paymentTime", paymentTime);
                    } else {
                        item.put("paymentTime", "");
                    }

                    String refundTime = DateUtil.convertToString(p.getRefundTime());
                    if (!Checker.isNull(refundTime)) {
                        item.put("refundTime", refundTime);
                    } else {
                        item.put("refundTime", "");
                    }
                    item.put("remark", Checker.getStringValue(p.getRefundRemark()));
                    return item;
                });
                map.put("list", datas);
                // pageDataResponse.setData(datas);
            } else {
                map.put("list", new ArrayList<>());
            }
            //  pageDataResponse.setPageIndex(request.getPageIndex());
            // pageDataResponse.setPageSize(request.getPageSize());
            // pageDataResponse.setTotalCount(ordersPagedList.getTotal());
            map.put("totalCount", ordersPagedList.getTotal());
            map.put("pageIndex", request.getPageIndex());
            map.put("pageSize", request.getPageSize());
            response.setData(map);

        } catch (Exception e) {
            logger.error("/orders/queryOrderList(): {}", e.getMessage(), e);
            e.printStackTrace();
            return response.failed(BaseResponse.OTHER_ERROR, "数据读取失败");
        }
        return response.succeed("处理成功");
    }

    //下载订单列表
    @MGRight(menuCode = {"/downloadOrdersList"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    @RequestMapping({"/downloadOrdersList"})
    BaseResponse downloadOrdersList(@RequestBody QueryOrdersListRequest request, HttpServletResponse httpServletResponse) {
        DataResponse<Map<String, String>> response = new DataResponse<>();
        Integer shopId = userService.getShopId();
        request.setShopId(shopId);
//        String uData = Base64.getEncoder().encodeToString(JsonSerializer.toJson(request).getBytes());
        String url = domainConfigurer.getYwtGlasses() + "/mg/orders/downloadOrdersListGet";
        Map<String, String> map = new HashMap<>();
        map.put("shopId", shopId.toString());
        String createUrl = BizUtil.createParentUrl(request, url, map);
        Map<String, String> mapper = new HashMap<>();
        mapper.put("url", createUrl);
        response.setData(mapper);
        return response.succeed("成功");
    }

    //下载订单列表2
    @MGRight(menuCode = {"/downloadOrdersListGet"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    @RequestMapping(value = {"/downloadOrdersListGet"}, method = RequestMethod.GET)
    void downloadOrdersListGet(QueryOrdersListRequest request,
                               HttpServletResponse httpServletResponse) {
        goodsOrderService.downloadGoods(request, httpServletResponse);
    }

    //对账展示
    @MGRight(menuCode = {"/amountList"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    @RequestMapping({"/amountList"})
    BaseResponse amountList(@RequestBody AmoutListRequest request) {
        DataResponse<Map<String, Object>> response = new DataResponse<>();

        try {
            List<Map<String, Object>> datases = new LinkedList<>();
            Map<String, Object> items = new HashMap<>();
            //支付方式
            List<Map<String, Object>> datas = goodsOrderService.amountListPay(request.getCreateTime(), request.getCreateEndTime());
            //取货方式账单
            List<Map<String, Object>> datass = goodsOrderService.amountListPost(request.getCreateTime(), request.getCreateEndTime());
            datas.addAll(datass);
            items.put("list", datas);
            //  datases.add(items);
            response.setData(items);

        } catch (Exception e) {
            logger.error("/orders/amountList(): {}", e.getMessage(), e);
            e.printStackTrace();
            return response.failed(BaseResponse.OTHER_ERROR, "数据读取失败");
        }
        return response.succeed("成功");
    }


    //下载报表post
    @MGRight(menuCode = {"/downloadAmountListPost"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    @RequestMapping({"/downloadAmountListPost"})
    BaseResponse downloadAmountListPost(@RequestBody AmoutListRequest request, HttpServletResponse httpServletResponse) {
        DataResponse<Map<String, String>> response = new DataResponse<>();
        Integer shopId = userService.getShopId();
        request.setShopId(shopId);
       String url =
               domainConfigurer.getYwtGlasses()
//                "http://127.0.0.1:8091/glasses"
                + "/mg/orders/downloadAmountListGet";
        Map<String, String> map = new HashMap<>();
        map.put("shopId", shopId.toString());
        String createUrl = BizUtil.createParentUrl(request, url, map);
        Map<String, String> mapper = new HashMap<>();
        mapper.put("url", createUrl);
        response.setData(mapper);
        return response.succeed("成功");
    }

    //下载报表get
    @MGRight(menuCode = {"/downloadAmountListGet"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    @RequestMapping({"/downloadAmountListGet"})
    void downloadAmountListGet(AmoutListRequest request, HttpServletResponse httpServletResponse) {
        goodsOrderService.downloadAmountListTwo(request, httpServletResponse);
    }

}
