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

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.DutyPersonDto;
import com.yeejoin.amos.boot.module.common.api.dto.DutyPersonShiftDto;
import com.yeejoin.amos.boot.module.common.api.entity.DutyPersonShift;
import com.yeejoin.amos.boot.module.common.api.entity.DutyShift;
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.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.service.IDutyPersonService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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

/**
 * @author DELL
 */
@Service
public class DutyPersonServiceImpl extends DutyCommonServiceImpl implements IDutyPersonService{

    @Autowired
    EquipFeignClient equipFeign;

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

    @Override
    public DutyPersonDto save(DutyPersonDto dutyPersonDto) {
        // BUG 2807 更新人员车辆排版值班的保存逻辑 如果没有填写数据则保存空数据 。 同步修改 查询 导出相关逻辑 by kongfm 2021-09-14
        //1.保存行数据
        String groupCode = this.getGroupCode();
        String userId = dutyPersonDto.getUserId();
        List<DynamicFormInstance> instances = dynamicFormInstanceService
                .list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getFieldCode, "userId")
                        .eq(DynamicFormInstance::getFieldValue, userId)
                        .eq(DynamicFormInstance::getGroupCode, this.getGroupCode()));
        Long instanceId = null;
        // 如果人员有区域id 则创建区域字段
        if(StringUtils.isNotEmpty(dutyPersonDto.getDutyAreaId())) {
            // 根据建筑id 查找建筑
            ResponseModel<Map<String, Object>> response = null;
            try {
                response = equipFeign.getFormInstanceById(Long.parseLong(dutyPersonDto.getDutyAreaId()));
            } catch (NumberFormatException e) {
                throw new BadRequest("值班区域id异常！");
            }
            Map<String, Object> result = response.getResult();
            dutyPersonDto.setDutyArea(result.get("name").toString());
        }

        Map<String, Object> map = Bean.BeantoMap(dutyPersonDto);

        if (!instances.isEmpty()) {
            // 0.定位instanceId，准备进行更新操作
            instanceId = instances.get(0).getInstanceId(); // 已经有了走更新方法
            //1.查询已有数据
            List<DynamicFormInstance> hasInstances = dynamicFormInstanceService.list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getInstanceId, instanceId));
            //2.list 转 map
            Map<Object, DynamicFormInstance> instanceMap = Bean.listToMap(hasInstances, "fieldCode", DynamicFormInstance.class);
            //3.查询列数据，已列为主
            List<DynamicFormColumn> columns = dynamicFormColumnService.list(new LambdaQueryWrapper<DynamicFormColumn>().eq(DynamicFormColumn::getGroupCode, groupCode));
            //4.已列为主 填充动态表单数据
            List<DynamicFormInstance> entrys = new ArrayList<>();
            for (DynamicFormColumn column : columns) {
                DynamicFormInstance formInstance = instanceMap.get(column.getFieldCode());
                if (!ObjectUtils.isEmpty(formInstance)) {
                    //有的更新
                    formInstance.setFieldValue(map.get(column.getFieldCode()) != null ? map.get(column.getFieldCode()).toString() : "");
                } else {
                    //没有的新增
                    formInstance = new DynamicFormInstance();
                    buildFormInstanceData(instanceId, map, column, formInstance);
                }
                entrys.add(formInstance);
            }
            if(!entrys.isEmpty()){
                dynamicFormInstanceService.saveOrUpdateBatch(entrys);
            }

        } else {
            instanceId =  dynamicFormInstanceService.commonSave(groupCode,map);
        }
        // 如果当前保存没有保存调班记录 需要默认保存一个月的空数据

        if(dutyPersonDto.getDutyShift() != null && dutyPersonDto.getDutyShift().size() == 0) {
            Calendar startDate = Calendar.getInstance();
            startDate.setTime(DateUtils.longStr2Date(dutyPersonDto.getStartTime()));
            int dates = startDate.getActualMaximum(Calendar.DAY_OF_MONTH);
            startDate.set(Calendar.DAY_OF_MONTH, 1);
            List<DutyPersonShift> dutyShift = new ArrayList<>(dates);
            for (int i = 0 ; i < dates ; i ++) {
                DutyPersonShift temp = new DutyPersonShift();
                temp.setAppKey(RequestContext.getAppKey());
                temp.setDutyDate(startDate.getTime());
                temp.setIsDelete(false);
                temp.setInstanceId(instanceId);
                dutyShift.add(temp);
                startDate.add(Calendar.DAY_OF_YEAR,1);
            }
            dutyPersonShiftService.saveOrUpdateBatch(dutyShift);
        }
        //2.保存值班信息
        insertPersonShift(instanceId, dutyPersonDto);
        //3.返回保存后的数据
        return dutyPersonDto;



    }

    @Override
    public DutyPersonDto update(Long instanceId, DutyPersonDto dutyPersonDto) {
        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(dutyPersonDto);
        //4.已列为主 填充动态表单数据
        List<DynamicFormInstance> entrys = new ArrayList<>();
        for (DynamicFormColumn column : columns) {
            DynamicFormInstance formInstance = instanceMap.get(column.getFieldCode());
            if (!ObjectUtils.isEmpty(formInstance)) {
                //有的更新
                formInstance.setFieldValue(map.get(column.getFieldCode()) != null ? map.get(column.getFieldCode()).toString() : "");
            } else {
                //没有的新增
                formInstance = new DynamicFormInstance();
                buildFormInstanceData(instanceId, map, column, formInstance);
            }
            entrys.add(formInstance);
        }
        if(!entrys.isEmpty()){
            dynamicFormInstanceService.saveOrUpdateBatch(entrys);
        }
        //5.更新值班信息人日期数据
        insertPersonShift(instanceId, dutyPersonDto);
        return dutyPersonDto;
    }

    private void insertPersonShift(Long instanceId, DutyPersonDto dutyPersonDto) {
        Set<DutyPersonShift> personShiftList = dutyPersonDto.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 List<DutyPersonDto> findByDutyAreaId(Long dutyAreaId) {
        Date now = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(now);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY,0);
        c.set(Calendar.MINUTE,0);
        c.set(Calendar.SECOND,0);
        String beginDate = DateUtils.date2LongStr(c.getTime());
        c.setTime(now);
        c.add(Calendar.MONTH, 1);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.add(Calendar.DATE, -1);
        c.set(Calendar.HOUR_OF_DAY,23);
        c.set(Calendar.MINUTE,59);
        c.set(Calendar.SECOND,59);
        String endDate = DateUtils.date2LongStr(c.getTime());
        List<DutyPersonDto> temp = new ArrayList<>();
        dutyPersonShiftService.list(new LambdaQueryWrapper<DutyPersonShift>()
                        .ge(beginDate != null, DutyPersonShift::getDutyDate, beginDate)
                        .le(endDate != null, DutyPersonShift::getDutyDate, endDate).groupBy(DutyPersonShift::getInstanceId))
                .stream().forEach(e -> {
                    //1.查询已有数据
                    List<DynamicFormInstance> instances = dynamicFormInstanceService.list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getInstanceId, e.getInstanceId()).eq(DynamicFormInstance::getGroupCode,this.getGroupCode()));
                    if(instances.size() > 0) {
                        DutyPersonDto dto = new DutyPersonDto();
                        boolean add = false;
                        for(DynamicFormInstance t : instances) {
                            if("userId".equals(t.getFieldCode())) {
                                dto.setUserId(t.getFieldValue());
                            } else if("userName".equals(t.getFieldCode())) {
                                dto.setUserName(t.getFieldValue());
                            } else if("deptId".equals(t.getFieldCode())) {
                                dto.setDeptId(t.getFieldValue());
                            } else if("deptName".equals(t.getFieldCode())) {
                                dto.setDeptName(t.getFieldValue());
                            } else if("postType".equals(t.getFieldCode())) {
                                dto.setPostType(t.getFieldValue());
                            } else if("postTypeName".equals(t.getFieldCode())) {
                                dto.setPostTypeName(t.getFieldValue());
                            } else if("dutyArea".equals(t.getFieldCode())) {
                                dto.setDutyArea(t.getFieldValue());
                            } else if("dutyAreaId".equals(t.getFieldCode())) {
                                if(dutyAreaId.toString().equals(t.getFieldValue())) {
                                    add = true;
                                }
                                dto.setDutyAreaId(t.getFieldValue());
                            }
                        }
                        if(add) {
                            temp.add(dto);
                        }
                    }
                });
        return temp;
    }
}
