package com.steerinfo.baseinfo.meterbasecar.service.impl;

import com.steerinfo.baseinfo.meterbasedriver.mapper.MeterBaseDriverMapper;
import com.steerinfo.baseinfo.meterbasedriver.model.MeterBaseDriver;
import com.steerinfo.baseinfo.meterbasespecialunit.mapper.MeterBaseSpecialUnitMapper;
import com.steerinfo.baseinfo.meterbasespecialunit.model.MeterBaseSpecialUnit;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.baseinfo.meterbasecar.model.MeterBaseCar;
import com.steerinfo.baseinfo.meterbasecar.mapper.MeterBaseCarMapper;
import com.steerinfo.baseinfo.meterbasecar.service.IMeterBaseCarService;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.meterwork.meterworkcaractual.mapper.MeterWorkCarActualMapper;
import com.steerinfo.meterwork.meterworkcaractual.model.MeterWorkCarActual;
import com.steerinfo.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

/**
 * MeterBaseCar服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2022-01-10 10:09
 * 类描述
 * 修订历史：
 * 日期：2022-01-10
 * 作者：generator
 * 参考：
 * 描述：MeterBaseCar服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "meterBaseCarService")
public class MeterBaseCarServiceImpl extends BaseServiceImpl<MeterBaseCar, String> implements IMeterBaseCarService {

    @Resource
    private MeterBaseCarMapper meterBaseCarMapper;

    @Resource
    private MeterWorkCarActualMapper meterWorkCarActualMapper;

    @Resource
    private MeterBaseSpecialUnitMapper meterBaseSpecialUnitMapper;

    @Resource
    private MeterBaseDriverMapper meterBaseDriverMapper;

    @Override
    protected IBaseMapper<MeterBaseCar, String> getMapper() {
        return meterBaseCarMapper;
    }

    @Override
    public String checkandadd(MeterBaseCar model)
    {
        String msg=check(model);
        if (StringUtils.isNotEmpty(msg)){
            return msg;
        }
//        HashMap<String, Object> obj = new HashMap<>();
//        obj.put("cusSupCarNo", model.getCusSupCarNo());
//        List<MeterBaseCusSupCar> com =meterBaseCusSupCarMapper.selectByParameters(obj);
//        if(!com.isEmpty()){
//            return "该车号已存在！";
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        String afl = sdf.format(new Date());
//        String no = meterBaseCarMapper.GetNewID(afl);
//        model.setPkNo(afl + no);

        String no =  PublicMethod.IdCreate(3);
        model.setPkNo(no);
        meterBaseCarMapper.insert(model);
        return "";
    }

    @Override
    public String Recovery(List<MeterBaseCar> models)
    {
        try {
            if (models == null || models.size() < 1) {
                return "请传入参数!";
            }
            for (MeterBaseCar model:models) {
                model.setValidFlag("0");
                model.setUpdateManName(model.getUpdateManName());
                model.setUpdateManNo(model.getUpdateManNo());
                model.setUpdateTime(new Date());
                meterBaseCarMapper.updateByPrimaryKey(model);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }

    @Override
    public String abolish(List<MeterBaseCar> models)
    {
        try {
            if (models == null || models.size() < 1) {
                return "请传入参数!";
            }
            for (MeterBaseCar model:models) {
                model.setValidFlag("1");
                model.setUpdateManName(model.getUpdateManName());
                model.setUpdateManNo(model.getUpdateManNo());
                model.setUpdateTime(new Date());
                meterBaseCarMapper.updateByPrimaryKey(model);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }

    @Override
    public String checkandupdate(String id,MeterBaseCar model)
    {
        String msg=check(model);
        if (StringUtils.isNotEmpty(msg)){
            return msg;
        }
//        HashMap<String, Object> obj = new HashMap<>();
//        obj.put("cusSupCarNo", model.getCusSupCarNo());
//        obj.put("pkNo", id);
//        List<MeterBaseCusSupCar> com =meterBaseCusSupCarMapper.selectForUpdate(obj);
//        if(!com.isEmpty()){
//            return "该车号已存在！";
//        }
        meterBaseCarMapper.updateByPrimaryKeySelective(model);
        return "";
    }

    @Override
    @Transactional
    public RESTfulResult batchAddCar(List<HashMap> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        rm.setCode("500");
        rm.setMessage("操作失败！！");
        try{
            UserPayload userPayload = UserPayload.getCurrUser();
            String userId = null;
            String userName = null;
            try {
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "admin";
                userName = "admins";
            }
            int count = 0;
            for(HashMap model: models) {
                if(model.get("carNo") == null || model.get("carNo").equals("")){
                    rm.setMessage("存在空车号");
                    return rm;
                }
                if(model.get("telNum") == null || model.get("telNum").equals("")){
                    rm.setMessage("司机电话号码不能为空！！");
                    return rm;
                }
                if(model.get("carTypeNo") == null || model.get("carTypeNo").equals("")){
                    rm.setMessage("车辆类型编号不能为空！！");
                    return rm;
                }
                if(model.get("carTypeName") == null || model.get("carTypeName").equals("")){
                    rm.setMessage("车辆类型名称不能为空！！");
                    return rm;
                }
                /*if(model.get("idNum") == null || model.get("idNum").equals("")){
                    rm.setMessage("司机身份证不能为空！！");
                    return rm;
                }*/
            }
            for (HashMap model : models){
                //检查车辆是否有停役状态的车
                String carNo = model.get("carNo").toString().replaceAll("-", "");
                HashMap query = new HashMap();
                query.put("carNo", carNo);
                query.put("validFlag", "1");
                List<MeterBaseCar> list = query(query);
                if(list.size() >= 1) {
                    //查询到停役车辆信息，则将该车辆以及该车辆下面的司机信息还原成服役状态
                    for(MeterBaseCar carModel: list) {
                        carModel.setValidFlag("0");
                        meterBaseCarMapper.updateByPrimaryKey(carModel);
                        HashMap map = new HashMap();
                        query.put("carId", carNo);
                        List<MeterBaseDriver> driverModels = meterBaseDriverMapper.selectByParameters(map);
                        if(driverModels.size() >= 1) {
                            for (MeterBaseDriver driver: driverModels) {
                                driver.setValidFlag("0");
                                meterBaseDriverMapper.updateByPrimaryKey(driver);
                            }
                        }
                    }
                }
                    //没有查询到服役的车辆信息，注册并插入车辆信息和司机信息
                    // sso注册
                    if(model.get("password").toString().equals("")) {
                        model.remove("password");
                        model.put("password", "a1234567");
                    }
                    SSOUtil ssoUtil = new SSOUtil();
                    HashMap ssoMap = ssoUtil.ssoRegister(model);
                    // sso注册成功时，增加车辆表
                    if (ssoMap.get("code").equals("1") && !"账号已被注册".equals(ssoMap.get("msg").toString())) {
                        rm.setMessage(ssoMap.get("msg").toString());
                    } else {
                        // sso注册成功时，增加车辆表
                        MeterBaseCar car = new MeterBaseCar();
                        car.setCarNo(carNo);
                        if(model.get("mnemonicCode") != null) {
                            car.setMnemonicCode(StringUtils.isNotEmpty(model.get("mnemonicCode").toString()) ?
                                    model.get("mnemonicCode").toString() : "");
                        }
                        if(model.get("vehicleType") != null) {
                            car.setVehicleType(StringUtils.isNotEmpty(model.get("vehicleType").toString()) ?
                                    model.get("vehicleType").toString() : "");
                        }
                        if(model.get("belongUnitTypeName") != null) {
                            if(StringUtils.isNotEmpty(model.get("belongUnitTypeName").toString())) {
                                car.setBelongUnitTypeName(model.get("belongUnitTypeName").toString());
                            }
                        }
                        if(model.get("usetDepartmentment") != null) {
                            if(StringUtils.isNotEmpty(model.get("usetDepartmentment").toString())) {
                                car.setUsetDepartment(model.get("usetDepartmentment").toString());
                                HashMap<String, Object> specialUnitMap = new HashMap<>();
                                specialUnitMap.put("unitName", car.getUsetDepartment());
                                List<MeterBaseSpecialUnit> specialUnitList = meterBaseSpecialUnitMapper.selectByParameters(specialUnitMap);
                                //根据使用部门查询出特殊单位编号，未查询到赋值为其他公司编号："888888"
                                if(specialUnitList.size() >= 1) {
                                    car.setUsetDepartmentNo(specialUnitList.get(0).getUnitNo());
                                }else {
                                    car.setUsetDepartmentNo("888888");
                                }

                            }
                        }
                        if(model.get("vehicleIdentifyNo") != null) {
                            if(StringUtils.isNotEmpty(model.get("vehicleIdentifyNo").toString())) {
                                car.setVehicleIdentifyNo(model.get("vehicleIdentifyNo").toString());
                            }
                        }
                        if(model.get("fillingDepartment") != null) {
                            if(StringUtils.isNotEmpty(model.get("fillingDepartment").toString())) {
                                car.setFillingDepartment(model.get("fillingDepartment").toString());
                            }
                        }
                        if(model.get("fillingUser") != null) {
                            if(StringUtils.isNotEmpty(model.get("fillingUser").toString())) {
                                car.setFillingUser(model.get("fillingUser").toString());
                            }
                        }
                        if(model.get("isInsurance") != null) {
                            if(StringUtils.isNotEmpty(model.get("isInsurance").toString())) {
                                car.setIsInsurance(model.get("isInsurance").toString());
                            }
                        }
                        if(model.get("otherInsurance") != null) {
                            if(StringUtils.isNotEmpty(model.get("otherInsurance").toString())) {
                                car.setOtherInsurance(model.get("otherInsurance").toString());
                            }
                        }
                        if(model.get("customerSupplierName") != null) {
                            if(StringUtils.isNotEmpty(model.get("customerSupplierName").toString())) {
                                car.setCustomerSupplierName(model.get("customerSupplierName").toString());
                            }
                        }
                        if(model.get("carTypeNo") != null) {
                            if(StringUtils.isNotEmpty(model.get("carTypeNo").toString())) {
                                car.setCarTypeNo(model.get("carTypeNo").toString());
                            }
                        }
                        if(model.get("carTypeName") != null) {
                            if(StringUtils.isNotEmpty(model.get("carTypeName").toString())) {
                                car.setCarTypeName(model.get("carTypeName").toString());
                            }
                        }
                        if(model.get("carCarrierWeight") != null) {
                            if(StringUtils.isNotEmpty(model.get("carCarrierWeight").toString())) {
                                car.setCarCarrierWeight(new BigDecimal(model.get("carCarrierWeight").toString()));
                            }
                        }
                        if(model.get("carSelfWeight") != null) {
                            if(StringUtils.isNotEmpty(model.get("carSelfWeight").toString())) {
                                car.setCarSelfWeight(new BigDecimal(model.get("carSelfWeight").toString()));
                            }
                        }
                        car.setValidFlag("0");
                        // 将sso id写入车辆表，便于以后删除和重置密码
                        if(ssoMap.get("data") != null && StringUtils.isNotEmpty(ssoMap.get("data").toString())) {
                            car.setSsoId(ssoMap.get("data").toString());
                        }
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("carNo", carNo);
                        List<MeterBaseCar> carModels = meterBaseCarMapper.selectByParameters(map);
                        if(carModels.size() >= 1) {
                            car.setPkNo(carModels.get(0).getPkNo());
                            car.setUpdateManNo(userId);
                            car.setUpdateManName(userName);
                            car.setUpdateTime(new Date());
                            meterBaseCarMapper.updateByPrimaryKeySelective(car);
                        }else {
//                            String no=meterBaseCarMapper.GetNewID(new SimpleDateFormat("yyyyMMdd").format(new Date()));
//                            car.setId(new SimpleDateFormat("yyyyMMdd").format(new Date())+no);
                            car.setCreateManNo(userId);
                            car.setCreateManName(userName);
                            car.setCreateTime(new Date());
                            String no =  PublicMethod.IdCreate(3);
                            car.setId(no);
                            car.setPkNo(no);
                            meterBaseCarMapper.insertSelective(car);
                        }
                        if (car.getSsoId() != null && car.getCarTypeNo().equals("001004003")) {
                            // SSO重置密码
                            ssoUtil.ssoResetPwd(car.getSsoId(), "123456", "");
                        }
                }
                //将司机信息写入司机表
                MeterBaseDriver driver = new MeterBaseDriver();
                driver.setDriverNo(carNo + model.get("telNum").toString());
                driver.setDriverName(model.get("driverName").toString());
                if(model.get("idNum") != null) {
                    if(StringUtils.isNotEmpty(model.get("idNum").toString())) {
                        driver.setIdNum(model.get("idNum").toString());
                    }
                }
                if(model.get("telNum") != null) {
                    if(StringUtils.isNotEmpty(model.get("telNum").toString())) {
                        driver.setTelNum(model.get("telNum").toString());
                    }
                }
                driver.setCarId(carNo);
                driver.setValidFlag("0");
                MeterBaseDriver findCar = meterBaseDriverMapper.selectByPrimaryKey(driver.getDriverNo());
                if(findCar == null) {
                    driver.setCreateManNo(userId);
                    driver.setCreateManName(userName);
                    driver.setCreateTime(new Date());
                    meterBaseDriverMapper.insertSelective(driver);
                }else {
                    driver.setUpdateManNo(userId);
                    driver.setUpdateManName(userName);
                    driver.setCreateTime(new Date());
                    meterBaseDriverMapper.updateByPrimaryKeySelective(driver);
                }
                count ++;
            }
            rm.setSucceed();
            rm.setCode("200");
            rm.setData(count);
            rm.setMessage("操作成功,总共" + count + "条数据插入成功！！！");
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常，请确认");
            return rm;
        }
        return rm;
    }

    @Override
    public List<MeterBaseCar> queryForNoPage(HashMap<String, Object> parmas) {
        if(parmas.isEmpty()){
            parmas.put("flag", "0");
        }
        List<MeterBaseCar> list = meterBaseCarMapper.selectByParametersNoPage(parmas);
        return list;
    }

    @Override
    public RESTfulResult getUnitByCar(String CarNo) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("carNo", CarNo);
            List<MeterBaseCar> carModels = meterBaseCarMapper.selectByParameters(map);
            if(carModels.size() >= 1) {
                MeterBaseCar carModel = carModels.get(0);
                String unitNo = carModel.getUsetDepartmentNo() == null ? "": carModel.getUsetDepartmentNo();
                if(StringUtils.isNotEmpty(unitNo)){
                    HashMap<String, Object> unitMap = new HashMap<>();
                    unitMap.put("unitNo", unitNo);
                    List<MeterBaseSpecialUnit> unitList = meterBaseSpecialUnitMapper.selectByParameters(unitMap);
                    if(unitList.size() >= 1) {
                        carModel.setIsSpecialunit(unitList.get(0).getUnitNo().equals("888888") ? "0": "1");
                    }else{
                        carModel.setIsSpecialunit("0");
                    }
                    meterBaseCarMapper.updateByPrimaryKeySelective(carModel);
                }else {
                    carModel.setIsSpecialunit("0");
                    meterBaseCarMapper.updateByPrimaryKeySelective(carModel);
                }
                rm.setSucceed();
                rm.setCode("200");
                rm.setMessage("操作成功！！");
                rm.setData(carModel);
            }else{
                rm.setMessage("未查询到相应车辆信息！！");
            }
        } catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！！>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional
    public RESTfulResult updateCar(MeterBaseCar model) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("carNo", model.getCarNo());
            List<MeterBaseCar> carList = meterBaseCarMapper.selectByParameters(obj);
            if(carList.size() >= 1) {
                model.setPkNo(carList.get(0).getPkNo());
                if(model.getUsetDepartmentNo() != null && StringUtils.isNotEmpty(model.getUsetDepartmentNo())) {
                    //111111：对应内部倒运;888888：对应外进外发
                    if(model.getUsetDepartmentNo().equals("111111")) {
                        model.setUsetDepartmentNo("888888");
                        model.setCarTypeNo("001004003");
                        model.setCarTypeName("内部");
                    }
                }
                meterBaseCarMapper.updateByPrimaryKeySelective(model);
                rm.setSucceed(true);
                rm.setData(model);
                rm.setMessage("操作成功");
            }else {
                rm.setMessage(model.getCarNo() + "车号信息不存在");
            }
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常，" + e.getMessage());
        }
        return rm;
    }

    private String check(MeterBaseCar model)
    {
        if (model == null){
            return "参数不能为空！！";
        }
        if (StringUtils.isEmpty(model.getCarNo())){
            return "车号不能为空！！";
        }

        if(StringUtils.isEmpty(model.getPkNo())){
            model.setCreateTime(new Date());
            model.setValidFlag("0");//服役
        }else {
            model.setUpdateTime(new Date());
        }
        return "";
    }

    @Override
    public RESTfulResult getCarActual(CommonPage<MeterBaseCar> oci) {
        RESTfulResult rm = new RESTfulResult();
        try {
            rm.setCode("200");
            if (oci.getParam() != null) {
                int iStart = oci.getPageSize() > 0 ? oci.getPageSize() : 9999;
                Map<String, Object> map = FieldsCollector.beanToMap(oci.getParam());
                PageHelper.startPage(oci.getPageNum(), iStart);
                List<MeterWorkCarActual> rows = meterWorkCarActualMapper.getCarActual(map);
                PageList pageInfo = new PageList(rows);
                rm.setData(pageInfo);
            }
        } catch (Exception ex) {
            rm.setCode("500");
            rm.setMessage("查询失败：" + ex.getMessage());
        }
        return rm;
    }


}


