package com.steerinfo.baseinfo.meterbasecar.controller;

import com.alibaba.fastjson.JSONObject;
import com.steerinfo.baseinfo.appverificationcode.mapper.AppVerificationCodeMapper;
import com.steerinfo.baseinfo.appverificationcode.model.AppVerificationCode;
import com.steerinfo.baseinfo.meterbasecar.mapper.MeterBaseCarMapper;
import com.steerinfo.baseinfo.meterbasecussupcar.model.MeterBaseCusSupCar;
import com.steerinfo.baseinfo.meterbasedriver.mapper.MeterBaseDriverMapper;
import com.steerinfo.baseinfo.meterbasedriver.model.MeterBaseDriver;
import com.steerinfo.baseinfo.meterbasedriver.service.IMeterBaseDriverService;
import com.steerinfo.baseinfo.meterbasespecialunit.mapper.MeterBaseSpecialUnitMapper;
import com.steerinfo.baseinfo.meterbasespecialunit.model.MeterBaseSpecialUnit;
import com.steerinfo.baseinfo.meterbasetravellingmerchant.mapper.MeterBaseTravellingMerchantMapper;
import com.steerinfo.baseinfo.meterbasetravellingmerchant.model.MeterBaseTravellingMerchant;
import com.steerinfo.baseinfo.meterbaseverificationcode.mapper.MeterBaseVerificationCodeMapper;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.baseinfo.meterbasecar.model.MeterBaseCar;
import com.steerinfo.baseinfo.meterbasecar.service.IMeterBaseCarService;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.util.CommonPage;
import com.steerinfo.util.SSOUtil;
import io.micrometer.core.instrument.Meter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.math.BigDecimal;

/**
 * MeterBaseCar RESTful接口：
 *
 * @author generator
 * @version 1.0-SNAPSHORT 2022-01-10 10:09
 * 类描述
 * 修订历史：
 * 日期：2022-01-10
 * 作者：generator
 * 参考：
 * 描述：MeterBaseCar RESTful接口
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 * @see null
 */
@RestController
@RequestMapping("/${api.version}/meterbasecars")
@Api(value = "/${api.version}/meterbasecars", tags = "车辆信息 - MeterBaseCarControllerv")
public class MeterBaseCarController extends BaseRESTfulController {

    @Autowired
    IMeterBaseCarService meterBaseCarService;

    @Resource
    MeterBaseSpecialUnitMapper meterBaseSpecialUnitMapper;

    @Autowired
    IMeterBaseDriverService meterBaseDriverService;

    @Resource
    MeterBaseCarMapper meterBaseCarMapper;

    @Resource
    MeterBaseDriverMapper meterBaseDriverMapper;

    @Resource
    MeterBaseTravellingMerchantMapper meterBaseTravellingMerchantMapper;

    @Resource
    AppVerificationCodeMapper appVerificationCodeMapper;

    @Resource
    MeterBaseVerificationCodeMapper meterBaseVerificationCodeMapper;

    @ApiOperation(value = "获取列表", notes = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterbasecar:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        PageList<MeterBaseCar> list = meterBaseCarService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "获取列表", notes = "不分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterbasecar:view")
    @GetMapping(value = "/queryForNoPage")
    public RESTfulResult list(@RequestParam HashMap parmas) {
        List<MeterBaseCar> list = meterBaseCarService.queryForNoPage(parmas);
        return success(list);
    }

    @ApiOperation(value = "获取列表", notes = "分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterbasecar:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        PageList<MeterBaseCar> list = meterBaseCarService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "创建", notes = "根据MeterBaseCar对象创建")
    @ApiImplicitParam(name = "meterBaseCar", value = "详细实体meterBaseCar", required = true, dataType = "MeterBaseCar")
    //@RequiresPermissions("meterbasecar:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute MeterBaseCar model) {
        MeterBaseCar meterBaseCar = meterBaseCarService.add(model);
        return success(meterBaseCar);
    }

    @ApiOperation(value = "获取详细信息", notes = "根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterbasecar:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id) {
        MeterBaseCar meterBaseCar = meterBaseCarService.getById(id);
        return success(meterBaseCar);
    }

    @ApiOperation(value = "更新详细信息", notes = "根据url的id来指定更新对象，并根据传过来的meterBaseCar信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "meterBaseCar", value = "详细实体meterBaseCar", required = true, dataType = "MeterBaseCar")
    })
    //@RequiresPermissions("meterbasecar:update")
    @PutMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody MeterBaseCar model) {
        model.setId(id);
        MeterBaseCar meterBaseCar = meterBaseCarService.modify(model);
        return success(meterBaseCar);
    }

    @ApiOperation(value = "删除", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterbasecar:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id) {
        List<String> list = Arrays.asList(id.split(","));
        if (ListUtils.isNotEmpty(list)) {
            List<String> ids = ListUtils.convertList(list);
            meterBaseCarService.delete(ids);
        }
        return success();
    }

    @ApiOperation(value = "启用", notes = "根据传过来的MeterBaseCusSupCar集合信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MeterBaseCar", value = "详细实体MeterBaseCar", required = true, dataType = "MeterBaseCar")
    })
    @Transactional
    @PostMapping(value = "/Recovery")
    public RESTfulResult Recovery(@RequestBody List<MeterBaseCar> models) {
        try {
            String msg = meterBaseCarService.Recovery(models);
            if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "停用", notes = "根据传过来的MeterBaseCar集合信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MeterBaseCar", value = "详细实体MeterBaseCar", required = true, dataType = "MeterBaseCar")
    })
    @Transactional
    @PostMapping(value = "/abolish")
    public RESTfulResult abolish(@RequestBody List<MeterBaseCar> models) {
        try {
            String msg = meterBaseCarService.abolish(models);
            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "app自助注册", notes = "app自助注册")
    @Transactional
    @PostMapping(value = "/appregister")
    public RESTfulResult appregister(@RequestBody HashMap params) {
        try {
            String msg = "";
            // sso注册
            SSOUtil ssoUtil = new SSOUtil();
            HashMap ssoMap = ssoUtil.ssoRegister(params);

            // sso注册成功时，增加车辆表
            if (ssoMap.get("code").equals("1") && !"账号已被注册".equals(ssoMap.get("msg").toString())) {
                return failed(null, ssoMap.get("msg").toString());
            } else {
                // 清除SSO"账号已被注册"
                msg = "";

                // 查询车辆是否写入车辆表
                HashMap queryCar = new HashMap();
                queryCar.put("carNo", params.get("carNo").toString());
                queryCar.put("validFlag", "0");
                String carNo = params.get("carNo").toString();
                //查询服役状态的车辆信息
                List<MeterBaseCar> queryList01 = meterBaseCarService.query(queryCar);
                //查询停役、删除状态的车辆信息
                List<MeterBaseCar> queryList02 = meterBaseCarMapper.selectByMap(queryCar);

                //meterBaseDriverMapper.batchDeleteSelf(params.get("carNo").toString());

                // 车辆表已存在车辆信息时，跳过
                if (queryList01.size()+queryList02.size() == 0) {

                    // 新增车辆
                    MeterBaseCar car = new MeterBaseCar();
                    car.setCarNo(params.get("carNo").toString());
                    car.setValidFlag("0");

                    String unitNo = params.get("unitNo").toString();
                    HashMap<String, Object> unitMap = new HashMap<>();
                    unitMap.put("unitNo", unitNo);

                    List<MeterBaseSpecialUnit> unitList = meterBaseSpecialUnitMapper.selectByParameters(unitMap);
                    if(unitList.size() >= 1) {
                        if(unitNo.equals(unitList.get(0).getUnitNo())) {
                            car.setIsSpecialunit("1");
                        }else {
                            car.setIsSpecialunit("0");
                        }
                    }else {
                        car.setIsSpecialunit("0");
                    }
                    car.setUsetDepartmentNo(params.get("unitNo").toString());
                    car.setUsetDepartment(params.get("unitName").toString());

                    car.setCarTypeNo(params.get("carTypeNo").toString());
                    car.setCarTypeName(params.get("carTypeName").toString());
                    if (params.get("carCarrierWeight") != null) {
                        new BigDecimal(params.get("carCarrierWeight").toString());
                    }

                    // 将sso id写入车辆表，便于以后删除和重置密码
                    if(!ssoMap.get("code").toString().equals("1")){
                        car.setSsoId(ssoMap.get("data").toString());
                    }else{
                        msg = ssoUtil.ssoResetPwd(car.getSsoId(), params.get("password").toString(), "");
                    }
                    car.setCreateManNo("admin");
                    car.setCreateManName("admins");
                    car.setCreateTime(new Date());

                    meterBaseCarService.checkandadd(car);
                }else if(queryList02.size() >= 1){
                    for (MeterBaseCar model: queryList02) {
                        HashMap map = new HashMap();
                        queryCar.put("carId",model.getCarNo());
                        queryCar.put("pkNo", model.getPkNo());
                        //停役或者删除状态的车辆信息更新为服役状态
                        meterBaseCarMapper.updateValidFlagById(map);
                        //停役或者删除状态的司机信息更新为服役状态
                        meterBaseDriverMapper.updateValidFlagByCarId(map);
                    }

                    // 新增车辆
                    queryList01 = meterBaseCarService.query(queryCar);
                    MeterBaseCar car = queryList01.get(0);
                    car.setValidFlag("0");

                    String unitNo = params.get("unitNo").toString();
                    HashMap<String, Object> unitMap = new HashMap<>();
                    unitMap.put("unitNo", unitNo);

                    List<MeterBaseSpecialUnit> unitList = meterBaseSpecialUnitMapper.selectByParameters(unitMap);
                    if(unitList.size() >= 1) {
                        if(unitNo.equals(unitList.get(0).getUnitNo())) {
                            car.setIsSpecialunit("1");
                        }else {
                            car.setIsSpecialunit("0");
                        }
                    }else {
                        car.setIsSpecialunit("0");
                    }
                    car.setUsetDepartmentNo(params.get("unitNo").toString());
                    car.setUsetDepartment(params.get("unitName").toString());

                    car.setCarTypeNo(params.get("carTypeNo").toString());
                    car.setCarTypeName(params.get("carTypeName").toString());
                    if (params.get("carCarrierWeight") != null) {
                        new BigDecimal(params.get("carCarrierWeight").toString());
                    }
                    ssoUtil.ssoResetPwd(car.getSsoId(), params.get("password").toString(), "");

                    car.setCreateManNo("admin");
                    car.setCreateManName("admins");
                    car.setCreateTime(new Date());

                    meterBaseCarMapper.updateByPrimaryKeySelective(car);
                }
                // 拆分司机list，新增司机表
                List<MeterBaseDriver> driverList = JSONObject.parseArray(params.get("driverList").toString(), MeterBaseDriver.class);
                // 循环新增司机
                for (MeterBaseDriver driver : driverList) {
                    // 检查司机是否存在
                    HashMap query = new HashMap();
                    query.put("carId", params.get("carNo").toString());
                    query.put("driverName", driver.getDriverName());
                    query.put("telNum", driver.getTelNum());
                    query.put("validFlag", "0");

                    List<MeterBaseDriver> list = meterBaseDriverService.query(query);
                    // 司机表已存在时，跳过
                    if (list.size() == 0) {
                        // 将司机信息加入实体
                        // 主键改为日期主键
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//                        String no = meterBaseDriverMapper.getNewID(sdf.format(new Date()));
//                        driver.setId(sdf.format(new Date()) + no);
                        String pkNO = params.get("carNo").toString() + driver.getTelNum();
                        driver.setId(pkNO);
                        driver.setCarId(params.get("carNo").toString());
                        driver.setDriverName(driver.getDriverName());
                        driver.setTelNum(driver.getTelNum());
                        driver.setValidFlag("0");
                        driver.setCreateManNo("admin");
                        driver.setCreateManName("admins");
                        driver.setCreateTime(new Date());

                        MeterBaseDriver list1 = meterBaseDriverMapper.selectByPrimaryKey(pkNO);
                        if(list1 == null){
                            meterBaseDriverService.checkandadd(driver);
                        }
                        else {
                            list1.setValidFlag("0");
                            meterBaseDriverMapper.updateByPrimaryKeySelective(list1);
                        }

                    }

                    if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        break;
                    }
                }
            }

            if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "app登录", notes = "app登录")
    @Transactional
    @PostMapping(value = "/applogin")
    public RESTfulResult applogin(@RequestBody HashMap params) {

        RESTfulResult rm = failed();
        Object ssodata = "";

        HashMap<String, Object> info = new HashMap();
        try {
            if (params.get("carNo") == null || com.steerinfo.util.StringUtils.isEmpty(params.get("carNo").toString())) {
                rm.setMessage("车号不能为空！！");
                return rm;
            } else if (params.get("telNum") == null || com.steerinfo.util.StringUtils.isEmpty(params.get("telNum").toString())) {
                rm.setMessage("手机号不能为空！！");
                return rm;
            } else {
                // 状态（0：服役；1:停役;2:删除）
                params.put("validFlag", "0");

                // 判断车号，司机手机号是否存在
                List<MeterBaseCusSupCar> list = meterBaseDriverService.query(params);
                if (list.size() >= 1) {
                    // sso登录
                    SSOUtil ssoUtil = new SSOUtil();
                    HashMap map = ssoUtil.ssoLogin(params, "");

                    if (map.get("code").toString().equals("0")) {
                        ssodata = map.get("data").toString();
                        info.put("ssoData", ssodata);
                        HashMap<String, Object> carInfoMap = new HashMap<>();
                        carInfoMap.put("carNo", params.get("carNo"));
                        List<MeterBaseCar> carInfo = meterBaseCarMapper.selectByParameters(carInfoMap);
                        if(carInfo.size() >= 1){
                            info.put("carInfo", carInfo);
                            HashMap<String, Object> dirverInfoMap = new HashMap();
                            dirverInfoMap.put("carId", params.get("carNo"));
                            dirverInfoMap.put("telNum", params.get("telNum"));
                            List<MeterBaseDriver> driverInfo = meterBaseDriverMapper.selectByParameters(dirverInfoMap);
                            if(driverInfo.size() >= 1){
                                info.put("driverInfo", driverInfo);
                                rm = success();
                                rm.setData(info);
                                rm.setMessage("操作成功");
                                return rm;
                            }else{
                                rm.setMessage("司机配置信息表没有此车号和电话号码");
                                return rm;
                            }
                        }else{
                            rm.setMessage("车辆配置信息表没有此车号");
                            return rm;
                        }

                    } else {
                        rm.setMessage(map.get("msg").toString());
                    }
                } else {
                    rm.setMessage("没有此车号或手机号");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return rm;
    }

    @ApiOperation(value = "app非司机登录", notes = "app非司机登录")
    @Transactional
    @PostMapping(value = "/notApplogin")
    public RESTfulResult notApplogin(@RequestBody HashMap params) {

        RESTfulResult rm = new RESTfulResult();
        String msg = "";
        Object ssodata = "";
        String userType = "1";
        HashMap returnObj = new HashMap();
        try {
            SSOUtil ssoUtil = new SSOUtil();
            HashMap map = ssoUtil.ssoLogin(params, "");

            if (map.get("code").toString().equals("0")) {
                ssodata = map.get("data").toString();
            } else {
                msg = map.get("msg").toString();
            }
            HashMap trave = new HashMap();
            trave.put("travellingMerchantName",params.get("carNo"));
            trave.put("travellingMerchantPossword",params.get("password"));
            List<MeterBaseTravellingMerchant> meterBaseTravellingMerchant = meterBaseTravellingMerchantMapper.selectByParameters(trave);
            if (meterBaseTravellingMerchant.size()>0){
                MeterBaseTravellingMerchant mbtm = meterBaseTravellingMerchant.get(0);
                ssodata = mbtm;
                userType = "2";
            }

            returnObj.put("ssodata",ssodata);
            returnObj.put("userType",userType);

            if (com.steerinfo.util.StringUtils.isNotEmpty(msg) && meterBaseTravellingMerchant.size()<0) {
                return failed(null, msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success(returnObj);
    }

    @ApiOperation(value = "app修改密码", notes = "app修改密码")
    @Transactional
    @PostMapping(value = "/appchangepwd")
    public RESTfulResult appchangepwd(@RequestBody HashMap params) {

        RESTfulResult rm = failed();
        String carNo = params.get("carNo").toString();
        String telNum = params.get("telNum").toString();
        String passWord = params.get("newpassword").toString();
        String passCode = params.get("code").toString();
        try {
            if (carNo == null || com.steerinfo.util.StringUtils.isEmpty(carNo)) {
                rm.setMessage("车号不能为空！！");
                return rm;
            } else if (telNum == null || com.steerinfo.util.StringUtils.isEmpty(telNum)) {
                rm.setMessage("手机号不能为空！！");
                return rm;
            } else if (passWord == null || com.steerinfo.util.StringUtils.isEmpty(passWord)) {
                rm.setMessage("新密码不能为空！！");
                return rm;
            } else if(passCode == null || com.steerinfo.util.StringUtils.isEmpty(passCode)) {
                rm.setMessage("验证码不能为空！！");
                return rm;
            }else{
                //通过手机获取验证码列表
                AppVerificationCode modelTemp =  appVerificationCodeMapper.selectByPhone(telNum);
                //手机号验证是否存在
                if(modelTemp!=null){
                    //当前时间是否在过期时间之内
                    Date date = new Date();
                    //验证码是否过期
                    int flag = date.compareTo(modelTemp.getExpirationTime());
                    if(flag > 0 || modelTemp.getValueFlag().equals("0")){
                        rm.setMessage("验证码已过期，请重新发送验证码！！");
                        modelTemp.setValueFlag("0");
                        appVerificationCodeMapper.updateByPrimaryKey(modelTemp);
                        return rm;
                    }
                    //验证码没过期且相等
                    if(modelTemp.getCode().equals(passCode) && modelTemp.getValueFlag().equals("1")){
                        modelTemp.setValueFlag("0");
                        appVerificationCodeMapper.updateByPrimaryKey(modelTemp);
                        // 判断车号，司机手机号是否存在
                        List<MeterBaseCusSupCar> list = meterBaseDriverService.query(params);
                        if (list.size() >= 1) {
                            // SSO修改密码
                            SSOUtil ssoUtil = new SSOUtil();
                            HashMap map = ssoUtil.ssoChangePwd(params);

                            if (map.get("code").toString().equals("0")) {
                            } else {
                                rm.setMessage(map.get("msg").toString());
                            }
                        } else {
                            rm.setMessage("没有此车号或手机号");
                        }
                    }else{
                        return failed(null, "验证码错误");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "通过手机发送验证码重置密码", notes = "app重置密码")
    @Transactional
    @PostMapping(value = "/appreSetPwdByCode")
    public RESTfulResult appreSetPwdByCode(@RequestBody HashMap params) {
        RESTfulResult rm = failed();

        rm.setMessage("");
        String carNo = params.get("carNo").toString();
        String telNum = params.get("telNum").toString();
        String passWord = params.get("password").toString();
        String passCode = params.get("code").toString();
        try {
            if (carNo == null || com.steerinfo.util.StringUtils.isEmpty(carNo)) {
                rm.setMessage("车号不能为空！！");
                return rm;
            } else if (telNum == null || com.steerinfo.util.StringUtils.isEmpty(telNum)) {
                rm.setMessage("手机号不能为空！！");
                return rm;
            } else if (passWord == null || com.steerinfo.util.StringUtils.isEmpty(passWord)) {
                rm.setMessage("新密码不能为空！！");
                return rm;
            } else if(passCode == null || com.steerinfo.util.StringUtils.isEmpty(passCode)) {
                rm.setMessage("验证码不能为空！！");
                return rm;
            } else {
                HashMap<String, Object> map = new HashMap<>();
                map.put("carNo", carNo);
                map.put("telNum", telNum);
                List<MeterBaseDriver> driverModel = meterBaseDriverMapper.selectByParameters(map);
                if(driverModel.size() >= 1){
                    //通过手机获取验证码列表
                    AppVerificationCode modelTemp =  appVerificationCodeMapper.selectByPhone(telNum);
                    if(modelTemp!=null){
                        //当前时间是否在过期时间之内
                        Date date = new Date();
                        //验证码是否过期
                        int flag = date.compareTo(modelTemp.getExpirationTime());
                        if(flag > 0 || modelTemp.getValueFlag().equals("0")){
                            rm.setMessage("验证码已过期，请重新发送验证码！！");
                            modelTemp.setValueFlag("0");
                            appVerificationCodeMapper.updateByPrimaryKey(modelTemp);
                            return rm;
                        }
                        //验证码没过期且相等
                        if(modelTemp.getCode().equals(passCode) && modelTemp.getValueFlag().equals("1")){
                            modelTemp.setValueFlag("0");
                            appVerificationCodeMapper.updateByPrimaryKey(modelTemp);
                            // 判断车号，司机手机号是否存在
                            List<MeterBaseDriver> list = meterBaseDriverService.query(params);
                            if (list.size() >= 1) {
                                // 获取车辆SSO ID
                                HashMap queryMap = new HashMap();
                                queryMap.put("carNo", params.get("carNo").toString());

                                MeterBaseCar car = meterBaseCarService.getByParams(queryMap);

                                // 通过车辆SSO ID重置密码
                                if (car != null) {
                                    // SSO重置密码
                                    SSOUtil ssoUtil = new SSOUtil();
                                    rm.setMessage(ssoUtil.ssoResetPwd(car.getSsoId(), params.get("password").toString(), ""));
                                }
                            } else {
                                rm.setMessage("没有此车号或手机号");
                            }
                        }
                        if (com.steerinfo.util.StringUtils.isNotEmpty(rm.getMessage())) {
                            return failed(null, rm.getMessage());
                        }
                    }else{
                        rm.setMessage("验证码有误！！");
                        return rm;
                    }
                }else {
                    rm.setMessage("重置密码失败，根据手机号和车号未查询到相应的账号！！");
                    return rm;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "app重置密码", notes = "app重置密码")
    @Transactional
    @PostMapping(value = "/appresetpwd")
    public RESTfulResult appresetpwd(@RequestBody HashMap params) {

        String msg = "";

        try {
            if (params.get("carNo") == null || com.steerinfo.util.StringUtils.isEmpty(params.get("carNo").toString())) {
                msg = "车号不能为空！！";
            } else if (params.get("telNum") == null || com.steerinfo.util.StringUtils.isEmpty(params.get("telNum").toString())) {
                msg = "手机号不能为空！！";
            } else {
                // 状态（0：服役；1:停役;2:删除）
                params.put("validFlag", "0");

                // 判断车号，司机手机号是否存在
                List<MeterBaseDriver> list = meterBaseDriverService.query(params);
                if (list.size() >= 1) {
                    // 获取车辆SSO ID
                    HashMap queryMap = new HashMap();
                    queryMap.put("carNo", params.get("carNo").toString());

                    MeterBaseCar car = meterBaseCarService.getByParams(queryMap);

                    // 通过车辆SSO ID重置密码
                    if (car != null) {
                        // SSO重置密码
                        SSOUtil ssoUtil = new SSOUtil();
                        msg = ssoUtil.ssoResetPwd(car.getSsoId(), params.get("newpassword").toString(), "");
                    }
                } else {
                    msg = "没有此车号或手机号";
                }
            }

            if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }

        return success();
    }

    @ApiOperation(value = "web重置密码", notes = "web重置密码")
    @Transactional
    @PostMapping(value = "/webresetpwd")
    public RESTfulResult webresetpwd(@RequestBody HashMap params) {

        String msg = "";

        try {
            // 获取车辆SSO ID
            HashMap queryMap = new HashMap();
            queryMap.put("carNo", params.get("carNo").toString());

            MeterBaseCar car = meterBaseCarService.getByParams(queryMap);

            // 通过车辆SSO ID重置密码
            if (car != null) {
                // SSO重置密码
                SSOUtil ssoUtil = new SSOUtil();
                msg = ssoUtil.ssoResetPwd(car.getSsoId(), params.get("newpassword").toString(), "");
            }

            if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }

        return success();
    }

    @ApiOperation(value = "PC新增车辆", notes = "PC新增车辆")
    @Transactional
    @PostMapping(value = "/addcar")
    public RESTfulResult addcar(@RequestBody HashMap params) {
        try {
            String msg = "";

            // 检查车辆是否存在
            HashMap query = new HashMap();
            query.put("carNo", params.get("carNo").toString());
            query.put("validFlag", "0");

            List<MeterBaseCar> list = meterBaseCarService.query(query);
            if (list.size() == 0) {
                // sso注册
                SSOUtil ssoUtil = new SSOUtil();
                HashMap ssoMap = ssoUtil.ssoRegister(params);

                // sso注册成功时，增加车辆表
                if (ssoMap.get("code").equals("1")) {
                    return failed(null, ssoMap.get("msg").toString());
                } else {
                    // sso注册成功时，增加车辆表
                    MeterBaseCar car = new MeterBaseCar();
                    // 将车辆类型，载重信息加入实体
                    car.setCarNo(params.get("carNo").toString());
                    car.setCarTypeNo(params.get("carTypeNo").toString());
                    car.setCarTypeName(params.get("carTypeName").toString());
                    if (params.get("carSelfWeight") != null) {
                        car.setCarSelfWeight(new BigDecimal(params.get("carSelfWeight").toString()));
                    }
                    if (params.get("carCarrierWeight") != null) {
                        car.setCarCarrierWeight(new BigDecimal(params.get("carCarrierWeight").toString()));
                    }
//                        car.setMnemonicCode(params.get("mnemonicCode").toString());
//                        car.setCustomerSupplierName(params.get("customerSupplierName").toString());
//                        car.setMemo(params.get("memo").toString());
                    car.setCreateManNo("admin");
                    car.setCreateManName("admins");
                    car.setCreateTime(new Date());

                    // 将sso id写入车辆表，便于以后删除和重置密码
                    car.setSsoId(ssoMap.get("data").toString());

                    msg = meterBaseCarService.checkandadd(car);
                }
            } else {
                msg = "车辆已存在";
            }

            if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "PC新增车辆", notes = "PC新增车辆")
    @Transactional
    @PostMapping(value = "/addByCarNo")
    public RESTfulResult addByCarNo(@RequestBody HashMap params) {
        MeterBaseCar car = new MeterBaseCar();
        try {
            String msg = "";
            // 检查车辆是否存在
            HashMap query = new HashMap();
            query.put("carNo", params.get("carNo").toString());
            query.put("validFlag", "0");

            List<MeterBaseCar> list = meterBaseCarService.query(query);
            if (list.size() == 0) {
                // sso注册
                params.put("password", "jg123456");
                SSOUtil ssoUtil = new SSOUtil();
                HashMap ssoMap = ssoUtil.ssoRegister(params);

                // sso注册成功时，增加车辆表
                if (ssoMap.get("code").equals("1")) {
                    return failed(null, ssoMap.get("msg").toString());
                } else {
                    // sso注册成功时，增加车辆表
                    // 将车辆类型，载重信息加入实体
                    car.setCarNo(params.get("carNo").toString());
                    car.setCarTypeNo(params.get("carTypeNo").toString());
                    car.setCarTypeName(params.get("carTypeName").toString());
//                        car.setMnemonicCode(params.get("mnemonicCode").toString());
//                        car.setCustomerSupplierName(params.get("customerSupplierName").toString());
//                        car.setMemo(params.get("memo").toString());
                    car.setCreateManNo("admin");
                    car.setCreateManName("admins");
                    car.setCreateTime(new Date());
                    // 将sso id写入车辆表，便于以后删除和重置密码
                    car.setSsoId(ssoMap.get("data").toString());

                    msg = meterBaseCarService.checkandadd(car);
                }
            } else {
                msg = "车辆已存在";
            }

            if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success(car);
    }

    @ApiOperation(value = "PC新增司机", notes = "PC新增司机")
    @Transactional
    @PostMapping(value = "/adddriver")
    public RESTfulResult addDriver(@RequestBody HashMap params) {
        try {
            String msg = "";
            // 拆分司机list，新增司机表
            List<MeterBaseDriver> driverList = JSONObject.parseArray(params.get("driverList").toString(), MeterBaseDriver.class);
            // 循环新增司机
            for (MeterBaseDriver driver : driverList) {
                // 检查司机是否存在
                HashMap query = new HashMap();
                query.put("carNo", params.get("carNo").toString());
                query.put("telNum", driver.getTelNum());
                query.put("validFlag", "0");

                List<MeterBaseDriver> list = meterBaseDriverService.query(query);
                // 司机表已存在时，跳过
                if (list.size() == 0) {
                    // 将司机信息加入实体
                    // 主键改为日期主键
                    driver.setId(params.get("carNo").toString() + driver.getTelNum());
                    driver.setCarId(params.get("carNo").toString());
                    driver.setValidFlag("0");
                    driver.setCreateManNo("admin");
                    driver.setCreateManName("admins");
                    driver.setCreateTime(new Date());
                    meterBaseDriverService.checkandadd(driver);
                }
                if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    break;
                }
            }
            if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }


    @ApiOperation(value = "批量删除", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterbasecar:delete")
    @PutMapping(value = "/deleteBatch")//String
    public RESTfulResult deleteBatch(@RequestBody List<MeterBaseCar> model) {
        try {
            List<String> list = new ArrayList<>();
            for(MeterBaseCar models : model){
                list.add(models.getCarNo());
            }
            meterBaseDriverMapper.deleteCarById(list);
            meterBaseCarMapper.deleteCarById(list);
            return success();
        }
        catch (Exception e){
            e.printStackTrace();
            return failed(null,"操作异常，请确认");
        }
    }

    @ApiOperation(value = "根据车辆直接废除", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterbasecar:delete")
    @PostMapping(value = "/deleteByCarNo")//String
    public RESTfulResult deleteByCarNo(@RequestBody Map carNo) {
        try {
            List<String> list = new ArrayList<>();
            list.add(carNo.get("carNo").toString());
            meterBaseDriverMapper.deleteCarById(list);
            meterBaseCarMapper.deleteCarById(list);
            return success();
        }
        catch (Exception e){
            e.printStackTrace();
            return failed(null,"操作异常，请确认");
        }
    }


    @ApiOperation(value = "批量车辆导入", notes = "批量车辆导入")

    @PostMapping(value = "/batchAddCar")
    public RESTfulResult batchAddCar(@RequestBody List<HashMap> model) {
        RESTfulResult rm = failed();
        try {
            rm = meterBaseCarService.batchAddCar(model);
            return rm;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
    }

    @ApiOperation(value = "获取计量结果", notes = "客商来获取详细计量信息")
    //@RequiresPermissions("meterbasecar:view")
    @PostMapping(value = "/getCarActual")
    public RESTfulResult getCarActual(@RequestBody CommonPage<MeterBaseCar> oci) {
        try {
            RESTfulResult rm = meterBaseCarService.getCarActual(oci);
            return rm;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MarkerMetException(500, "操作异常！！");
        }
    }

    @ApiOperation(value = "根据车号是否是特殊单位信息", notes = "根据车号是否是特殊单位信息")
    //@RequiresPermissions("meterbasecar:view")
    @PostMapping(value = "/getUnitByCar")
    public RESTfulResult getUnitByCar(@RequestBody Map params) {
        try {
            String carNo = params.get("carNo") == null ? "" : params.get("carNo").toString();
            RESTfulResult rm = meterBaseCarService.getUnitByCar(carNo);
            return rm;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MarkerMetException(500, "操作异常！！");
        }
    }

    @ApiOperation(value = "主键ID重新生成", notes = "主键ID重新生成")
    //@RequiresPermissions("meterbasecar:view")
    @PostMapping(value = "/reNewID")
    public RESTfulResult newId() {
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("validFlag", "0");
            List<MeterBaseCar> carList = meterBaseCarMapper.selectByParameters(map);
            int count = 0;
            if(carList.size() >= 1) {
                int i = 0;

                for(MeterBaseCar car: carList) {
                    i++;
                    DecimalFormat decimalFormat = new DecimalFormat("00000");
                    String numFormat= decimalFormat .format(i);
                    car.setPkNo("20220517"+numFormat);

                    int j = meterBaseCarMapper.reNewID(car);
                    if(j >= 1) {
                        count ++;
                    }
                }
            }
            RESTfulResult rm = success();
            rm.setData(count);
            return rm;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MarkerMetException(500, "操作异常！！");
        }
    }

}
