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

import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.baseinfo.combaseinfo.model.ComBaseInfo;
import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.combaseinfo.service.IComBaseInfoService;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkcaractualfirst.model.MeterWorkCarActualFirst;
import com.steerinfo.meterwork.meterworkstoragecalibration.model.MeterWorkStorageCalibration;
import com.steerinfo.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;

    @Override
    protected IBaseMapper<ComBaseInfo, String> getMapper() {
        return comBaseInfoMapper;
    }


    @Override
    public RESTfulResult executeSqlDataWf(String sql) {
        RESTfulResult rm = new RESTfulResult();
        try {
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("sql", sql);
            List<HashMap> list = comBaseInfoMapper.executeSqlData(obj);
            if (list == null || list.isEmpty()) {
                rm.setCode("200");
                rm.setData(null);
            } else {
                rm.setCode("200");
                rm.setData(list);
            }
        } catch (Exception e) {
            rm.setCode("500");
            rm.setMessage("查询异常：" + e.getMessage());
        }
        return rm;
    }

    /**
     * 客户端数据更新
     *
     * @param model
     * @return
     */
    @Override
    public String doUpdateWf(ComBaseInfo model) {
        String str = "";
        try {
            if (StringUtils.isEmpty(model.getUpdateManName()) || StringUtils.isEmpty(model.getUpdateManNo())) {
                return "修改人及修改人编码不允许为空！";
            }
            model.setUpdateTime(new Date());
            comBaseInfoMapper.updateByPrimaryKeySelective(model);
        } catch (MarkerMetException e) {
            throw e;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return str;
    }

    @Override
    public List<ComBaseInfo> measurementLeaderNo(HashMap<String, Object> params) {
        //计量员班长配置、状态有效
        params.put("pBaseCode", "001055");
        params.put("validFlag", "1");
        List<ComBaseInfo> models = comBaseInfoMapper.measurementLeaderNo(params);
        return models;
    }

    @Override
    public String checkManLevel(HashMap<String, Object> map) {
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        //计量数据管理员
        HashMap<String, Object> meteringAdministratorMap = new HashMap<>();
        meteringAdministratorMap.put("pBaseCode", "001058");
        List<String> meteringAdministratorModels = comBaseInfoMapper.matterNoByBaseCode(meteringAdministratorMap);
        //计量班长
        HashMap<String, Object> gaugerMonitorMap = new HashMap<>();
        gaugerMonitorMap.put("pBaseCode", "001057");
        List<String> gaugerMonitorModels = comBaseInfoMapper.matterNoByBaseCode(gaugerMonitorMap);
        //计量员
        HashMap<String, Object> gaugerMap = new HashMap<>();
        gaugerMap.put("pBaseCode", "001056");
        List<String> gaugerModels = comBaseInfoMapper.matterNoByBaseCode(gaugerMap);

        if(meteringAdministratorModels.size() >= 1) {
            for (String str: meteringAdministratorModels) {
                if(str.equals(userId)) {
                    return "1";
                }
            }
        }
        if(gaugerMonitorModels.size() >= 1){
            for (String str: gaugerMonitorModels) {
                if(str.equals(userId)) {
                    return "2";
                }
            }
        }
        if(gaugerModels.size() >= 1) {
            for (String str : gaugerModels) {
                if (str.equals(userId)) {
                    return "3";
                }
            }
        }
        return "4";
    }

    @Transactional
    @Override
    public String checkandadd(ComBaseInfo model) {
        try {
            ComBaseInfo com1 = comBaseInfoMapper.selectByPrimaryKey(model.getpBaseCode());
            if (null != com1) {
                String st = com1.getIsCreateSubclaseFlag();
                if (st.equals("1")) {
                    return "该父类不允许添加子类或该类已经创建为父类";
                }
            }
            if (model.getBaseCode() != null && !model.getBaseCode().equals("")) {
                if (model.getBaseName() != null && !model.getBaseName().equals("")) {
                    if (model.getIsEditFlag() != null && !model.getIsEditFlag().equals("") && model.getIsEditFlag().length() == 1) {
                        if (model.getpBaseCode() != null && !model.getpBaseCode().equals("")) {
                            ComBaseInfo com2 = comBaseInfoMapper.selectByPrimaryKey(model.getBaseCode());
                            if (null != com2) {
                                return "数据编码不允许重复！";
                            }
                            ComBaseInfo com3 = comBaseInfoMapper.selectByPrimaryKey(model.getpBaseCode());
                            if (com3 == null) {
                                return "该父类不存在";
                            }
                            if (!model.getBaseCode().substring(0, model.getpBaseCode().length()).equals(model.getpBaseCode())) {
                                return "快速检索码与数据编码不匹配";
                            }
                            model.setCreateTime(new Date());
                            model.setValidFlag("1");
                            comBaseInfoMapper.insertSelective(model);
                        } else {
                            return "请输入检索码";
                        }
                    } else {
                        return "请确认是否可编辑";
                    }
                } else {
                    return "请输入数据名称";
                }
            } else {
                return "请输入数据编码";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public String checkAndUpdate(String id, ComBaseInfo model) throws Exception {
        try {
            ComBaseInfo com1 = comBaseInfoMapper.selectByPrimaryKey(model.getpBaseCode());
            if (null != com1) {
                String st = com1.getIsCreateSubclaseFlag();
                if (st.equals("1")) {
                    return "修改后的检索码不允许添加子类";
                }
            }
            if (model.getBaseCode() != null && !model.getBaseCode().equals("")) {
                if (model.getBaseName() != null && !model.getBaseName().equals("")) {
                    if (model.getIsEditFlag() != null && !model.getIsEditFlag().equals("") && model.getIsEditFlag().length() == 1) {
                        if (model.getpBaseCode() != null && !model.getpBaseCode().equals("")) {
                            if (!model.getBaseCode().equals(id)) {
                                return "数据编码不允许修改";
                            }
                            ComBaseInfo com2 = comBaseInfoMapper.selectByPrimaryKey(id);
                            if (com2 == null && com2.getBaseName().equals(model.getBaseName())) {
                                return "修改后的数据名称已存在";
                            }
                            if (com2.getIsEditFlag().equals("1")) {
                                return "该数据不可编辑";
                            }
                            ComBaseInfo com3 = comBaseInfoMapper.selectByPrimaryKey(model.getpBaseCode());
                            if (com3 == null) {
                                return "该父类不存在";
                            }
                            model.setUpdateTime(new Date());
                            comBaseInfoMapper.updateByPrimaryKey(model);
                        } else {
                            return "请输入检索码";
                        }
                    } else {
                        return "请确认是否可编辑";
                    }
                } else {
                    return "请输入数据名称";
                }
            } else {
                return "请输入数据编码";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }

    public String Recovery(List<ComBaseInfo> models) throws Exception {
        try {
            if (models == null || models.size() < 1) {
                return "请传入参数!";
            }
            for (ComBaseInfo model : models) {
                model.setBaseCode(model.getBaseCode());
                model.setValidFlag("1");
                model.setUpdateManName(model.getUpdateManName());
                model.setUpdateManNo(model.getUpdateManNo());
                model.setUpdateTime(new Date());
                comBaseInfoMapper.updateByPrimaryKey(model);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }


    public String abolish(List<ComBaseInfo> models) throws Exception {
        try {
            if (models == null || models.size() < 1) {
                return "请传入参数!";
            }
            for (ComBaseInfo model : models) {
                HashMap<String, Object> obj = new HashMap<>();
                obj.put("pBaseCode", model.getBaseCode());
                //获取子类
                List<ComBaseInfo> list = comBaseInfoMapper.selectByParameters(obj);
                for (ComBaseInfo list1 : list) {
                    list1.setBaseCode(model.getBaseCode());
                    list1.setValidFlag("0");//无效
                    list1.setUpdateManName(model.getUpdateManName());
                    list1.setUpdateManNo(model.getUpdateManNo());
                    list1.setUpdateTime(new Date());
                    comBaseInfoMapper.updateByPrimaryKey(list1);
                }
                model.setBaseCode(model.getBaseCode());
                model.setValidFlag("0");
                model.setUpdateManName(model.getUpdateManName());
                model.setUpdateManNo(model.getUpdateManNo());
                model.setUpdateTime(new Date());
                comBaseInfoMapper.updateByPrimaryKey(model);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }


    public List<ComBaseInfo> selectSpoType() {
        List<ComBaseInfo> spotype = comBaseInfoMapper.selectSpoType();
        return spotype;
    }

    public List<ComBaseInfo> selectVideoType() {
        List<ComBaseInfo> videotype = comBaseInfoMapper.selectVideoType();
        return videotype;
    }

    public List<ComBaseInfo> selectVideoMark(String baseName, String baseCode) {
        try {
            if (baseCode == null && "".equals(baseCode)) {
                throw new MarkerMetException(500, "参数为空");
            }
            ComBaseInfo videotype = comBaseInfoMapper.selectByPrimaryKey(baseCode);
            if (videotype == null) {
                throw new MarkerMetException(500, "该类型不存在!!");
            }
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("pBaseCode", videotype.getBaseCode());
            List<ComBaseInfo> videomark = comBaseInfoMapper.selectByParameters(obj);
            return videomark;
        } catch (MarkerMetException e) {
            throw e;
        }

    }

    @Override
    public List<ComBaseInfo> queryAll(Map<String, Object> parameters) {
        return comBaseInfoMapper.selectLikeByParameters(parameters);
    }

}

