package com.kmall.api.fromcomm.controller.pay.data.open;

import com.kmall.manager.entity.CusReqRecordEntity;
import com.kmall.manager.service.CusReqRecordService;
import com.kmall.common.constant.Dict;
import com.kmall.manager.entity.pay.data.open.ReqPay;
import com.kmall.manager.entity.pay.data.open.ResponseMsg;
import com.kmall.common.utils.BeanUtils;
import com.kmall.common.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * 企业接收海关发起的支付相关实时数据获取请求
 *
 * @author Scott Chen
 * @since 1.0
 * 2018-12-26
 */
@Controller
public class PlatDataOpen {
    private static final Logger logger = LoggerFactory.getLogger(PlatDataOpen.class);

    @Autowired
    private CusReqRecordService cusReqRecordService;

    /**
     * 海关抽查数据请求接口
     * Content-Type: application/x-www-form-urlencoded
     * 请求报文格式是key=openReq,value=json字符串
     * openReq={"orderNo":"ord201800002","sessionID":"fe2374-8fnejf97-32839218","serviceTime":1533271903898}
     *
     * @param openReq
     * @return
     */
    @RequestMapping(value = "/cus/platDataOpen")
    @ResponseBody
    public ResponseMsg platDataOpen(@RequestParam(required = false) String openReq) {
        if (StringUtils.isBlank(openReq)) {
            return ResponseMsg.builder().setCode(ResponseMsg.ERROR_CODE)
                    .setMessage("请求openReq为空").build();
        }

        logger.debug("海关请求openReq数据: {}", openReq);

        ReqPay reqPay = null;

        reqPay = JacksonUtils.fromStringJson(openReq, ReqPay.class);
        if (reqPay == null) {
            return ResponseMsg.builder().setCode(ResponseMsg.ERROR_CODE)
                    .setMessage("请求openReq数据异常").build();
        }

        logger.debug("海关请求openReq转换后数据: {}", openReq);

        // 添加海关请求记录
        CusReqRecordEntity record = new CusReqRecordEntity();
        BeanUtils.copyProperties(reqPay, record);
        record.setStatus(Dict.cusDateOpenStatus.item_0.getItem());
        record.setCreateTime(new Date());
        record.setModTime(new Date());
        cusReqRecordService.save(record);

        return ResponseMsg.builder().build();
    }

}
