package com.iformall.controller;

import com.alibaba.fastjson.JSON;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.domain.po.*;
import com.iformall.enums.EnumCarCmd;
import com.iformall.enums.EnumCarVendor;
import com.iformall.enums.EnumCouponSendSendType;
import com.iformall.enums.EnumETCPCode;
import com.iformall.service.*;
import com.iformall.utils.ETCPUtil;
import com.iformall.utils.TJDCarUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/carCallback")
public class WxCarCallBackController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    ETCPUtil etcp = new ETCPUtil();

    TJDCarUtil tjd = new TJDCarUtil();

    @Autowired
    WxParkService wxParkService;

    @Autowired
    WxCUserCarService wxCUserCarService;

    @Autowired
    WxMerchantService wxMerchantService;

    @Autowired
    WxCarCmdLogService wxCarCmdLogService;

    @Autowired
    WxCouponSendService wxCouponSendService;

    @Autowired
    WxCarPayRecordService wxCarPayRecordService;

    @Autowired
    WxCUserService wxCUserService;

    /**
     * ETCP 车辆入场通知
     * {
     * "synId": "4ebd80ff-cfcf-462a-94cb-727e9fa9547c",
     * "plateNumber": "渝 ATX061",
     * "parkName": "ETCP 智慧停车场",
     * "parkId": "1",
     * "entranceTime": "2017-08-20 12:59:54",
     * "userType": "76",
     * "pushTime": "2017-08-20 12:59:57",
     * "fixParkingId": "U7",
     * "remainingDays": "11"
     * }
     */
    @PostMapping(value = "/etcpParkInCallback")
    public Result etcpParkInCallback(@RequestBody Map<String, String> paramMap) {
        logger.info("["+getIpAddr()+"] etcpParkInCallback: " + paramMap.toString());
        Date currentDate = new Date();
        WxCarCmdLog wxCarCmdLog = new WxCarCmdLog();

        wxCarCmdLog.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
        wxCarCmdLog.setCmdType(EnumCarCmd.CAR_ETCP_CALLBACK_PARK_IN.getCode());
        wxCarCmdLog.setCmdJson(JSON.toJSONString(paramMap));
        wxCarCmdLog.setCreateDate(currentDate);
        wxCarCmdLog.setUpdateDate(currentDate);

        String etcpParkId = paramMap.get("parkId");
        String tenantId = "456";
        WxPark parkQ = new WxPark();
        parkQ.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
        parkQ.setParkingId(etcpParkId);
        WxPark park = wxParkService.getByObj(parkQ);
        if (park == null) {
            logger.error("etcpParkInCallback: ETCP车场未找到" + etcpParkId);
            //return new Result(ErrorCode.CAR_PARK_NOT_FOUND.getCode(), "ETCP车场未找到"+ etcpParkId);
        } else {
            tenantId = park.getTenantId();
            wxCarCmdLog.setTenantId(park.getTenantId());
        }

        try {
            wxCarCmdLogService.saveOrUpdate(wxCarCmdLog);
        } catch (Exception e) {
            logger.error("etcpParkInCallback: 入库错误 " + paramMap.toString());
            return new Result(ErrorCode.DB_FAIL.getCode(), "入库错误" + paramMap.toString());
        }

        String phoneStrs = "";

        // 停车发券
        String carNumber = paramMap.get("plateNumber");
        if (!StringUtils.isBlank(carNumber)) {
            // 根据车牌查找用户
            WxCUserCar userCarQ = new WxCUserCar();
            userCarQ.setTenantId(tenantId);
            userCarQ.setCarNumber(carNumber);
            userCarQ.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
            // TODO 可能多用户关联同一张车牌
            List<WxCUserCar> userCarList = wxCUserCarService.getList(userCarQ);
            for (WxCUserCar userCar : userCarList) {
                wxCouponSendService.sendCouponToUser(EnumCouponSendSendType.CAR_STOP, userCar);
                WxCUser cUser = wxCUserService.getById(userCar.getCUserId());
                if(cUser != null){
                    phoneStrs += cUser.getPhone() + ",";
                }
            }
        }
        // 替换最后一个逗号
        if(StringUtils.isNotBlank(phoneStrs)){
            phoneStrs = phoneStrs.substring(0,phoneStrs.length() - 1);
        }

        try {
            // 保存WxCarPayRecord
            WxCarPayRecord record = new WxCarPayRecord();
            record.setVendorType(wxCarCmdLog.getVendorType());
            Map<String,String> jsonMap = (Map)JSON.parseObject(wxCarCmdLog.getCmdJson());
            record.setSynId(jsonMap.get("synId"));
            record.setParkId(jsonMap.get("parkId"));
            record.setParkName(jsonMap.get("parkName"));
            record.setUserType(jsonMap.get("userType"));
            record.setPlateNumber(jsonMap.get("plateNumber"));
            if(StringUtils.isNotBlank(jsonMap.get("entranceTime"))) {
                record.setEntranceTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(jsonMap.get("entranceTime")));
            }
            record.setFixParkingId(jsonMap.get("fixParkingId"));
            record.setRemainingDays(jsonMap.get("remainingDays"));
            record.setPhone(phoneStrs);
            record.setTenantId(park.getTenantId());
            wxCarPayRecordService.saveOrUpdate(record);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("WxCarPayRecord: 入库错误 " + paramMap.toString());
            return new Result(ErrorCode.DB_FAIL.getCode(), "入库错误" + paramMap.toString());
        }

        return new Result(EnumETCPCode.SUCCESS.getCode(), EnumETCPCode.SUCCESS.getMessage());
    }

    /**
     * ETCP 车辆出场通知
     * {
     * "synId": "fd92f645-880e-4c2a-9d7d-7081a2488181",
     * "plateNumber": "渝 ATX061",
     * "parkName": "ETCP 智慧停车场",
     * "parkId": "1",
     * "entranceTime": "2017-08-17 18:44:19",
     * "userType": "76",
     * "pushTime": "2017-08-20 11:57:51",
     * "exitTime": "2017-08-19 12:07:19",
     * "stayedTime": 148980,
     * "receivableFee": 0,
     * "paidServiceFee": 0,
     * "fixParkingId": "U7",
     * "remainingDays": "12"
     * }
     */
    @PostMapping(value = "/etcpParkOutCallback")
    public Result etcpParkOutCallback(@RequestBody Map<String, String> paramMap) {
        logger.info("["+getIpAddr()+"etcpParkOutCallback: " + paramMap.toString());
        Date currentDate = new Date();

        WxCarCmdLog wxCarCmdLog = new WxCarCmdLog();
        wxCarCmdLog.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
        wxCarCmdLog.setCmdType(EnumCarCmd.CAR_ETCP_CALLBACK_PARK_OUT.getCode());
        wxCarCmdLog.setCmdJson(JSON.toJSONString(paramMap));
        wxCarCmdLog.setCreateDate(currentDate);
        wxCarCmdLog.setUpdateDate(currentDate);

        String etcpParkId = paramMap.get("parkId");
        WxPark parkQ = new WxPark();
        parkQ.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
        parkQ.setParkingId(etcpParkId);
        WxPark park = wxParkService.getByObj(parkQ);
        if (park == null) {
            logger.error("etcpParkOutCallback: ETCP车场未找到 " + etcpParkId);
            // return new Result(ErrorCode.CAR_PARK_NOT_FOUND.getCode(), "ETCP车场未找到"+ etcpParkId);
        } else {
            wxCarCmdLog.setTenantId(park.getTenantId());
        }

        try {
            wxCarCmdLogService.saveOrUpdate(wxCarCmdLog);
        } catch (Exception e) {
            logger.error("etcpParkOutCallback: 入库错误 " + paramMap.toString());
            return new Result(ErrorCode.DB_FAIL.getCode(), "入库错误" + paramMap.toString());
        }

        try {
            // 保存WxCarPayRecord
            WxCarPayRecord record = new WxCarPayRecord();
            record.setSynId(paramMap.get("synId"));
            if(StringUtils.isNotBlank(paramMap.get("exitTime"))) {
                record.setExitTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(paramMap.get("exitTime")));
            }
            if(StringUtils.isNotBlank(paramMap.get("stayedTime"))) {
                record.setStayedTime(Long.parseLong(paramMap.get("stayedTime")));
            }
            wxCarPayRecordService.updateBySynId(record);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("WxCarPayRecord: 出场更新错误 " + paramMap.toString());
            return new Result(ErrorCode.DB_FAIL.getCode(), "入库错误" + paramMap.toString());
        }

        // TODO 如果此车关联了停车优免券，自动把优免券设为已使用

        return new Result(EnumETCPCode.SUCCESS.getCode(), EnumETCPCode.SUCCESS.getMessage());
    }

    /**
     * ETCP 车辆解绑通知
     * {
     * "plateNumber": "渝 ATX061",
     * "time": "2017-08-20 11:57:51"
     * }
     */
    @PostMapping(value = "/etcpUnbindCarCallBack")
    public Result etcpUnbindCarCallBack(@RequestBody Map<String, String> paramMap) {
        logger.info("["+getIpAddr()+"etcpUnbindCarCallBack: " + paramMap.toString());
        String carNumber = paramMap.get("plateNumber");

        // TODO how to get the parkId

        Date currentDate = new Date();
        WxCarCmdLog wxCarCmdLog = new WxCarCmdLog();
        wxCarCmdLog.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
        wxCarCmdLog.setCmdType(EnumCarCmd.CAR_ETCP_CALLBACK_UNBIND.getCode());
        wxCarCmdLog.setCmdJson(JSON.toJSONString(paramMap));
        wxCarCmdLog.setCreateDate(currentDate);
        wxCarCmdLog.setUpdateDate(currentDate);
        try {
            wxCarCmdLogService.saveOrUpdate(wxCarCmdLog);
        } catch (Exception e) {
            logger.error("etcpUnbindCarCallBack: 入库错误 " + paramMap.toString());
            return new Result(ErrorCode.DB_FAIL.getCode(), "入库错误" + paramMap.toString());
        }

        WxCUserCar userCarQ = new WxCUserCar();
        userCarQ.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
        userCarQ.setCarNumber(carNumber);
        // 数据库里删除，保持同步
        try {
            wxCUserCarService.deleteByObj(userCarQ);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        // 营销 - 短信
        return new Result(EnumETCPCode.SUCCESS.getCode(), EnumETCPCode.SUCCESS.getMessage());
    }

    /**
     * ETCP 主动支付结果通知
     * {
     * "plateNumber": "渝 ATX061",
     * "orderId": "fd92f645-880e-4c2a-9d7d-7081a2488181",
     * "fee": 7.65,
     * "paidServiceFee": 0.07,
     * "coupon": 0,
     * "time": "2017-08-20 11:57:51"
     * }
     */
    @PostMapping(value = "/etcpPaidCallback")
    public Result etcpPaidCallback(@RequestBody Map<String, String> paramMap) {
        logger.info("["+getIpAddr()+"etcpPaidCallback: " + paramMap.toString());
        String carNumber = paramMap.get("plateNumber");

        // 根据orderId获取入场信息，确定租户ID
        String orderId = paramMap.get("orderId");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("synId", orderId);
        String tenant_id = wxCarCmdLogService.getTenantIdBySynId(map);

        Date currentDate = new Date();
        WxCarCmdLog wxCarCmdLog = new WxCarCmdLog();
        if(StringUtils.isNotBlank(tenant_id)) {
            wxCarCmdLog.setTenantId(tenant_id);
        }
        wxCarCmdLog.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
        wxCarCmdLog.setCmdType(EnumCarCmd.CAR_ETCP_CALLBACK_PAY_MANUAL.getCode());
        wxCarCmdLog.setCmdJson(JSON.toJSONString(paramMap));
        wxCarCmdLog.setCreateDate(currentDate);
        wxCarCmdLog.setUpdateDate(currentDate);
        try {
            wxCarCmdLogService.saveOrUpdate(wxCarCmdLog);
        } catch (Exception e) {
            logger.error("etcpPaidCallback: 入库错误 " + paramMap.toString());
            return new Result(ErrorCode.DB_FAIL.getCode(), "入库错误" + paramMap.toString());
        }

        try {
            // 保存WxCarPayRecord
            WxCarPayRecord record = new WxCarPayRecord();
            record.setSynId(paramMap.get("orderId"));
            record.setPaidServiceFee(paramMap.get("paidServiceFee"));
            if(StringUtils.isNotBlank(paramMap.get("time"))) {
                record.setFeeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(paramMap.get("time")));
            }
            record.setFee(paramMap.get("fee"));
            wxCarPayRecordService.updateBySynId(record);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("WxCarPayRecord: 缴费更新错误 " + paramMap.toString());
            return new Result(ErrorCode.DB_FAIL.getCode(), "入库错误" + paramMap.toString());
        }

        // 营销 - 短信
        return new Result(EnumETCPCode.SUCCESS.getCode(), EnumETCPCode.SUCCESS.getMessage());
    }


    /**
     * TJD 车辆入场通知
     * {
     * "tradeId": "5836b8b52ada463ebc6199579f029565",
     * "outCarId": "45454545454",
     * "carNum": "京A45413",
     * "carNumColor ": "blue",
     * "inDt": "20170319202020",
     * "parkName": "测试停车场",
     * "parkId": "5836b8b52ada463ebc6199579f029561",
     * "lon": "74.000272",
     * "lat": "159.768703",
     * "wLon": "123.523032",
     * "wLat": "35.430735",
     * "payUrl": "http://prep.tingjiandan.com/tcweixin/letter/prePay/payInPark.html?prePayType=16&channel=10001",
     * "canFindCar": "0"
     * }
     */
    @RequestMapping(value = "/tjdParkInCallback")
    public Map tjdParkInCallback(@RequestBody Map<String, String> paramMap) {
        logger.info("["+getIpAddr()+"tjdParkInCallback: " + paramMap.toString());
        Map map = new HashMap();


        String tjdParkId = paramMap.get("parkId");

        WxPark parkQ = new WxPark();
        parkQ.setVendorType(EnumCarVendor.CAR_TJD.getCode());
        parkQ.setParkId(tjdParkId);
        WxPark park = wxParkService.getByObj(parkQ);
        if (park == null) {
            logger.error("tjdParkInCallback: 停简单车场未找到" + tjdParkId);
            map.put("isSuccess", "0");
            map.put("errorMsg", "停简单车场未找到" + tjdParkId);
            return map;
        }

        Date currentDate = new Date();
        WxCarCmdLog wxCarCmdLog = new WxCarCmdLog();
        wxCarCmdLog.setTenantId(park.getTenantId());
        wxCarCmdLog.setVendorType(EnumCarVendor.CAR_TJD.getCode());
        wxCarCmdLog.setCmdType(EnumCarCmd.CAR_ETCP_CALLBACK_PARK_IN.getCode());
        wxCarCmdLog.setCmdJson(JSON.toJSONString(paramMap));
        wxCarCmdLog.setCreateDate(currentDate);
        wxCarCmdLog.setUpdateDate(currentDate);
        try {
            wxCarCmdLogService.saveOrUpdate(wxCarCmdLog);
        } catch (Exception e) {
            logger.error("tjdParkInCallback: 入库错误" + paramMap.toString());
            map.put("isSuccess", "0");
            map.put("errorMsg", "入库错误" + paramMap.toString());
            return map;
        }

        map.put("isSuccess", "0");
        map.put("errorMsg", "");
        return map;
    }

    /**
     * TJD 车辆出场通知
     * {
     * "tradeId": "5836b8b52ada463ebc6199579f029565",
     * "outDt": "20170319232020",
     * "lon": "74.000272",
     * "lat": "159.768703",
     * "wLon": "123.523032",
     * "wLat": "35.430735",
     * "parkAmount": "5.20"
     * }
     */
    @RequestMapping(value = "/tjdParkoutCallback")
    public Map tjdParkOutCallback(@RequestBody Map<String, String> paramMap) {
        logger.info("["+getIpAddr()+"tjdParkoutCallback: " + paramMap.toString());
        Map map = new HashMap();


        String tradeId = paramMap.get("tradeId");

        Date currentDate = new Date();
        WxCarCmdLog wxCarCmdLog = new WxCarCmdLog();
        wxCarCmdLog.setVendorType(EnumCarVendor.CAR_ETCP.getCode());
        wxCarCmdLog.setCmdType(EnumCarCmd.CAR_ETCP_CALLBACK_PARK_OUT.getCode());
        wxCarCmdLog.setCmdJson(JSON.toJSONString(paramMap));
        wxCarCmdLog.setCreateDate(currentDate);
        wxCarCmdLog.setUpdateDate(currentDate);
        try {
            wxCarCmdLogService.saveOrUpdate(wxCarCmdLog);
        } catch (Exception e) {
            logger.error("tjdParkoutCallback: 入库错误" + paramMap.toString());
            map.put("isSuccess", "0");
            map.put("errorMsg", "入库错误" + paramMap.toString());
            return map;
        }

        map.put("isSuccess", "0");
        map.put("errorMsg", "");
        return map;
    }

}
