package com.community.huiju.service.impl;

import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.dao.TaUserLicenseMapper;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.model.TaUserLicense;
import com.community.huiju.service.IFuShiService;
import com.community.huiju.service.ITaUserLicenseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

/**
 * 月租车 业务
 * @author weiximei
 */
@Service
@Slf4j
public class TaUserLicenseServiceImpl implements ITaUserLicenseService {

    @Autowired
    private TaUserLicenseMapper taUserLicenseMapper;

    @Autowired
    private IFuShiService iFuShiService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean associatedLicense(UserElement userElement, String carNo) {
        ResponseBean responseBean = new ResponseBean();

        TaUserLicense taUserLicense = taUserLicenseMapper.selectByUserIdAndCommunityIdAndLicensePlate(userElement.getCommunityId(), userElement.getId(), carNo);
        if (null == taUserLicense) {
            taUserLicense = new TaUserLicense();
        }

        taUserLicense.setCommunityId(userElement.getCommunityId());
        taUserLicense.setTaUserId(userElement.getId());
        taUserLicense.setCreateUser(userElement.getId());
        taUserLicense.setCreateDate(new Date());

        // 获取最新的车牌信息
        getTaUserLicense(carNo, taUserLicense);

        if (taUserLicense.getLicenseType().intValue() != 1) {
            throw new WisdomException("该车牌不是月租车！");
        }

        int rows = 0;
        if (null == taUserLicense.getId()) {
            rows = taUserLicenseMapper.insertSelective(taUserLicense);
            responseBean.addSuccess(taUserLicense);
        } else {
            taUserLicense.setUpdateUser(userElement.getId());
            taUserLicense.setUpdateDate(new Date());
            rows = taUserLicenseMapper.updateByPrimaryKeySelective(taUserLicense);
            responseBean.addSuccess("当前小区已关联此车牌");
        }


        if (rows > 0) {
            taUserLicense.setUnitPrice(String.valueOf(Double.valueOf(taUserLicense.getUnitPrice()) / 100));
            return responseBean;
        }

        responseBean.addError("操作失败!");
        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean getLicense(UserElement userElement, String carNo) {
        ResponseBean responseBean = new ResponseBean();
        TaUserLicense taUserLicense = taUserLicenseMapper.selectByUserIdAndCommunityIdAndLicensePlate(userElement.getCommunityId(), userElement.getId(), carNo);
        if (null != taUserLicense) {
            taUserLicense = getTaUserLicense(carNo, taUserLicense);
            taUserLicense.setUpdateUser(userElement.getId());
            taUserLicense.setUpdateDate(new Date());
            taUserLicenseMapper.updateByPrimaryKeySelective(taUserLicense);
        }

        responseBean.addSuccess(taUserLicense);
        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean getAllUserLicense(UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();
        List<TaUserLicense> taUserLicenses = taUserLicenseMapper.selectAllByCommunityIdAndUserId(userElement.getCommunityId(), userElement.getId());

        //1. 查询所有车牌
        //2. 更新车牌信息

        taUserLicenses = taUserLicenses.stream().map(e-> {
            e.setUnitPrice(String.valueOf(Double.valueOf(e.getUnitPrice()) / 100));
            return e;
        }).collect(Collectors.toList());

        responseBean.addSuccess(taUserLicenses);
        return responseBean;
    }

    /**
     * 获取最新的车牌信息
     * @param carNo
     * @return
     */
    private TaUserLicense getTaUserLicense(String carNo, TaUserLicense taUserLicense) {

        // 查询车牌
        ResponseBean responseBean = iFuShiService.getParkInfoByCarNo(carNo);
        Object resultCar = responseBean.getData();
        if (null == resultCar) {
            throw new WisdomException("无此车牌记录！");
        }

        // 获取车牌的最新信息，并替换旧数据

        // 获取到的车牌信息
        Map<String,Object> map = (Map<String,Object>)resultCar;

        Map<String,Object> jsonParam = (Map<String, Object>) map.get("JsonParam");

        Integer dataType = (Integer) map.get("DataType");
        // 车类型
        taUserLicense.setLicenseType(dataType);

        taUserLicense.setLicensePlate(carNo);
        String price = String.valueOf(Double.valueOf(((BigDecimal) jsonParam.get("Cost")).toString()) * 100);
        taUserLicense.setUnitPrice(price.substring(0, price.lastIndexOf(".")));
        taUserLicense.setCreateDate(new Date());
        taUserLicense.setParkingLot(String.valueOf(jsonParam.get("ParkingName")));
        taUserLicense.setRenewTime(Integer.valueOf(String.valueOf(jsonParam.get("RenewTime"))));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            taUserLicense.setExpireDate(simpleDateFormat.parse(String.valueOf(jsonParam.get("EndTime"))));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return taUserLicense;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean deleteUserLicense(UserElement userElement, Integer licenseId) {
        ResponseBean responseBean = new ResponseBean();

        TaUserLicense taUserLicense = taUserLicenseMapper.selectByUserIdAndCommunityIdAndLicenseId(userElement.getCommunityId(), userElement.getId(), licenseId);
        if (null == taUserLicense) {
            responseBean.addError("没有关联此车牌！");
            return responseBean;
        }

        taUserLicenseMapper.deleteByPrimaryKey(licenseId);
        responseBean.addSuccess("操作成功！");
        return responseBean;
    }
}
