package com.yeejoin.amos.boot.module.common.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dto.DutyCarDto;
import com.yeejoin.amos.boot.module.common.api.entity.DutyPersonShift;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.Firefighters;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.mapper.FirefightersMapper;
import com.yeejoin.amos.boot.module.common.api.service.IDutyCarService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author DELL
 */
@Service
public class DutyCarServiceImpl extends DutyCommonServiceImpl implements IDutyCarService {

    @Autowired
    DynamicFormInstanceServiceImpl dynamicFormInstanceService;

    @Autowired
    FirefightersMapper firefightersMapper;

    @Autowired
    EquipFeignClient equipFeignClient;

    String driverPostTypeCode = "5";

    @Override
    public String getGroupCode() {
        return "dutyCar";
    }

    @Override
    public DutyCarDto save(DutyCarDto dutyCarDto) {
        //1.保存行数据
        String groupCode = this.getGroupCode();
        Map<String, Object> map = Bean.BeantoMap(dutyCarDto);
        Long instanceId = dynamicFormInstanceService.commonSave(groupCode,map);
        //2.保存值班信息
        insertPersonShift(instanceId, dutyCarDto);
        //3.返回保存后的数据
        return dutyCarDto;
    }

    @Override
    public DutyCarDto update(Long instanceId, DutyCarDto dutyCarDto) {
        String groupCode = this.getGroupCode();
        //1.查询已有数据
        List<DynamicFormInstance> instances = dynamicFormInstanceService.list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getInstanceId, instanceId));
        //2.list 转 map
        Map<Object, DynamicFormInstance> instanceMap = Bean.listToMap(instances, "fieldCode", DynamicFormInstance.class);
        //3.查询列数据，已列为主
        List<DynamicFormColumn> columns = dynamicFormColumnService.list(new LambdaQueryWrapper<DynamicFormColumn>().eq(DynamicFormColumn::getGroupCode, groupCode));
        //页面数据转Map
        Map<String, Object> map = Bean.BeantoMap(dutyCarDto);
        //4.已列为主 填充动态表单数据
        List<DynamicFormInstance> entrys = new ArrayList<>();
        updateFormValue(entrys, map, instanceId, columns, instanceMap);
        if (!entrys.isEmpty()) {
            dynamicFormInstanceService.saveOrUpdateBatch(entrys);
        }
        //5.更新值班信息人日期数据
        insertPersonShift(instanceId, dutyCarDto);
        return dutyCarDto;
    }

    private void insertPersonShift(Long instanceId, DutyCarDto dutyCarDto) {
        Set<DutyPersonShift> personShiftList = dutyCarDto.getDutyShift().stream().map(dto -> {
            DutyPersonShift dutyPersonShift = new DutyPersonShift();
            dto.setInstanceId(instanceId);
            Bean.copyExistPropertis(dto, dutyPersonShift);
            dutyPersonShift.setAppKey(RequestContext.getAppKey());
            return dutyPersonShift;
        }).collect(Collectors.toSet());
        if (!personShiftList.isEmpty()) {
            dutyPersonShiftService.saveOrUpdateBatch(personShiftList);
        }
    }

    private void buildFormInstanceData(Long instanceId, Map<String, Object> map, DynamicFormColumn column, DynamicFormInstance formInstance) {
        fillFormInstanceData(instanceId, map, column, formInstance, sequence.nextId());
    }

    @Override
    public JSONObject isFireCarDriver() {
        JSONObject result = new JSONObject();
        result.put("isDriver", false);
        result.put("carStatus", "");
        result.put("carId", "");

        String loginUserId = RequestContext.getExeUserId();
        // 根据登陆人id查询对应消防人员
        Firefighters firefighters =
                firefightersMapper.selectOne(new LambdaQueryWrapper<Firefighters>().eq(Firefighters::getSystemAccount,
                loginUserId));
        if (ValidationUtil.isEmpty(firefighters)) {
            return result;
        }
        // 消防人员id
        Long fighterId = firefighters.getSequenceNbr();

        // 当前值班班次id
        List<Long> shiftIdList = getDutyShiftIdList();
        if (ValidationUtil.isEmpty(shiftIdList)) {
            return result;
        }
        // 当前值班人员-车辆信息
        List<Map<String, Object>> personList = dayDutyPersonList(DateUtils.getDateNowShortStr(), shiftIdList.get(0),
                driverPostTypeCode);
        if (ValidationUtil.isEmpty(personList)) {
            return result;
        }

        personList = personList.stream().filter(m -> fighterId.equals(m.get("userId"))).collect(Collectors.toList());
        if (ValidationUtil.isEmpty(personList)) {
            return result;
        }

        result.put("isDriver", true);
        result.put("carId", personList.get(0).get("carId"));

        ResponseModel<Map<String, Object>> resultModel =
                equipFeignClient.queryCarSimpleInfoById((Long) personList.get(0).get("carId"));
        Map<String, Object> carInfo = resultModel.getResult();
        result.put("carStatus", carInfo.get("carStatus"));
        return result;
    }
}
