package com.yeejoin.amos.boot.module.elevator.flc.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.elevator.api.dto.AlertFormRecordDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertFormRecord;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.elevator.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.elevator.api.enums.SourcesInfoEnum;
import com.yeejoin.amos.boot.module.elevator.api.mapper.AlertFormRecordMapper;
import com.yeejoin.amos.boot.module.elevator.api.service.IAlertFormRecordService;
import com.yeejoin.amos.boot.module.elevator.biz.service.impl.AlertCalledServiceImpl;
import com.yeejoin.amos.boot.module.elevator.biz.service.impl.AlertFormValueServiceImpl;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-11-02
 */
@Service
public class AlertFormRecordServiceImpl extends BaseService<AlertFormRecordDto, AlertFormRecord, AlertFormRecordMapper> implements IAlertFormRecordService {

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    private AlertFormRecordMapper alertFormRecordMapper;
    @Autowired
    private AlertFormValueServiceImpl iAlertFormValueService;
    @Autowired
    private AlertCalledServiceImpl alertCalledServiceImpl;

    /**
     * 驼峰转下划线
     *
     * @param str
     * @return
     */
    public static String convertToUnderline(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append("_").append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 用户单位信息redis获取
     **/
    public ReginParams getReginParams() {
        return JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
    }

    /**
     * 保存警情修改记录
     *
     * @return
     */
    @Override
    @Transactional
    public ResponseModel saveAlertFormRecord(AlertFormRecordDto  data) {
        try {
            AlertFormRecord oldRecord = new AlertFormRecord();
            AlertFormRecord record = new AlertFormRecord();
            BeanUtils.copyProperties(data, record);
            AgencyUserModel userModel = this.getReginParams().getUserModel();
            record.setEditTime(new Date());
            record.setRecUserRealName(userModel.getRealName());
            record.setSourcesInfo(Objects.requireNonNull(SourcesInfoEnum.getEnum(Integer.valueOf(record.getSourcesInfo()))).getName());
            alertFormRecordMapper.insert(record);
            Long alertCalled = record.getAlertCalledId();
            // 警情编辑时候更新警情动态表单数据
            if (SourcesInfoEnum.Edit.getName().equals(record.getSourcesInfo())){
                // 更新警情基本信息
                if (!record.getName().equals(oldRecord.getName())){
                    LambdaUpdateWrapper<AlertCalled> wrapper = new LambdaUpdateWrapper<>();
                    wrapper.eq(AlertCalled::getSequenceNbr, alertCalled);
                    wrapper.set(AlertCalled::getEmergencyPerson, record.getName());
                    alertCalledServiceImpl.update(wrapper);
                }
                LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AlertFormValue::getAlertCalledId, alertCalled);
                List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
                HashMap<String, Object> listMap = new HashMap<>();
                list.forEach(x -> listMap.put(x.getFieldCode(), x.getFieldValue()));
                for (Field field : record.getClass().getDeclaredFields()) {
                    // 设置为可访问，以访问私有属性
                    field.setAccessible(true);
                    String fieldName = convertToUnderline(field.getName());
                    Object value = field.get(record);
                    //“是否有光照” 转 文字存储
                    if ("is_light".equals(fieldName)){
                        value = (value.equals(1) ? "是" : "否");
                    }
                    try {
                        //表tz_alert_form_value中的字典名称desc和表tz_alert_form_record中列名称description冲突，做特殊处理
                        if (listMap.containsKey(fieldName) || (listMap.containsKey("desc") && fieldName.equals("description"))) {
                            LambdaUpdateWrapper<AlertFormValue> wrapper = new LambdaUpdateWrapper<>();
                            wrapper.eq(AlertFormValue::getAlertCalledId, alertCalled);
                            wrapper.eq(AlertFormValue::getFieldCode, fieldName.equals("description") ? "desc" : fieldName);
                            wrapper.set(AlertFormValue::getFieldValue, value);
                            iAlertFormValueService.update(wrapper);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            redisUtils.del(RedisKey.TZS_ALERTCALLED_ID + alertCalled);
            return ResponseHelper.buildResponse("保存警情记录成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("保存警情记录失败");
        }
    }

    /**
     * 根据警情id查询所有修改记录
     *
     * @param alertCalledId 警情id
     * @return 记录
     */
    @Override
    public List<AlertFormRecord> allAlertFormRecordByCalledId(Long alertCalledId) {
        List<AlertFormRecord> list = alertFormRecordMapper.getRecordByCalledId(alertCalledId);
        //匹配字典值
        if (!list.isEmpty()){
            String code = list.get(0).getAlertTypeCode();
            AlertStageEnums dict = AlertStageEnums.getEnumById(code);
            list.stream().map(x->x.setAlertTypeCode(dict.getValue())).collect(Collectors.toList());
        }
        return list;
    }
}