package com.org.web.person.service;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.system.entity.SysRole;
import com.org.system.entity.SysUser;
import com.org.system.enums.YesOrNoState;
import com.org.system.service.SysDataDictionaryItemService;
import com.org.system.service.SysUserRoleService;
import com.org.system.service.SysUserService;
import com.org.utils.SecurityUtil;
import com.org.utils.exception.CustomException;
import com.org.web.hospital.domain.BcHospitalRecord;
import com.org.web.hospital.service.BcHospitalRecordService;
import com.org.web.person.domain.BcPersonFamily;
import com.org.web.person.domain.BcPersonSupport;
import com.org.web.person.mapper.BcPersonSupportMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BcPersonSupportService extends ServiceImpl<BcPersonSupportMapper, BcPersonSupport> {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    BcPersonFamilyService familyService;

    @Autowired
    BcHospitalRecordService hospitalRecordService;

    @Autowired
    SysDataDictionaryItemService sysDataDictionaryItemService;

    @Transactional(rollbackFor = Exception.class)
    public boolean executeSaveOrUpdate(BcPersonSupport person) {
        log.info("BcPersonSupportService - executeSaveOrUpdate person:{}", person);
        if (null == person.getId()) {
            return executeSave(person);
        } else {
            return executeUpdate(person);
        }
    }


    // 新增人员
    private boolean executeSave(BcPersonSupport person) {

        // 新建用户
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(person, sysUser);
        sysUser.setUserName(person.getIdCardNo());
        sysUser.setNickName(person.getName());
        sysUserService.saveOrUpdate(sysUser);

        // 保存用户角色信息
        sysUserRoleService.save(sysUser.getId(), CollectionUtil.newArrayList(person.getType() == 1 ? SysRole.SUPPORT_ROLE : SysRole.TEND_ROLE));

        // 新增人员信息
        person.setId(sysUser.getId()); // 人员的id为sysUser的id
        person.setCreateTime(new Date());
        person.setIsDelete(YesOrNoState.NO.getState());
        this.save(person);

        // 新增家庭成员子表数据
        familyService.executeSaveOrUpdate(person.getId(), person.getFamilyList());

        // 选择了床位和房间，则新增入院记录
        if (null != person.getRoomId() && null != person.getBedId()) {
            BcHospitalRecord record = new BcHospitalRecord();
            record.setPersonId(person.getId());
            record.setRoomId(person.getRoomId());
            record.setBedId(person.getBedId());
            hospitalRecordService.executeSaveOrUpdate(record);
        }

        return true;
    }

    private boolean executeUpdate(BcPersonSupport person) {
        person.setUpdateBy(SecurityUtil.getUserId());
        person.setUpdateTime(new Date());

        BcPersonSupport oldPerson = getById(person.getId());
        if (ObjectUtil.isNull(oldPerson)) {
            throw new CustomException("人员不存在");
        }

        // 修改用户
        SysUser sysUser = sysUserService.getById(person.getId());
        if (ObjectUtil.isNull(sysUser)) {
            throw new CustomException("未查询到用户信息");
        }

        sysUser.setUserName(person.getIdCardNo());
        sysUser.setNickName(person.getName());
        sysUser.setName(person.getName());
        sysUser.setIdCardNo(person.getIdCardNo());
        sysUser.setPhone(person.getPhone());
        sysUserService.saveOrUpdate(sysUser);

        // 编辑家庭成员子表数据
        familyService.executeSaveOrUpdate(person.getId(), person.getFamilyList());

        // 选择了床位和房间，则新增/编辑入院记录
        if (null != person.getRoomId() && null != person.getBedId()) {
            BcHospitalRecord lastRecord = hospitalRecordService.getRecordByPersonId(person.getId());
            if (null == lastRecord) lastRecord = new BcHospitalRecord();
            lastRecord.setPersonId(person.getId());
            lastRecord.setRoomId(person.getRoomId());
            lastRecord.setBedId(person.getBedId());
            hospitalRecordService.executeSaveOrUpdate(lastRecord);
        }

        return updateById(person);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean del(Long id) {
        log.info("BcPersonSupportService - del id:{}", id);

        BcPersonSupport person = getById(id);
        if (ObjectUtil.isNull(person)) {
            throw new CustomException("删除数据不存在");
        }
        person.setIsDelete(YesOrNoState.YES.getState());
        person.setDeleteBy(SecurityUtil.getUserId());
        person.setDeleteTime(new Date());

        // 删除用户
        sysUserService.del(CollectionUtil.newArrayList(person.getId()), "人员删除");

        // 删除家庭成员
        familyService.delByPersonId(person.getId());

        hospitalRecordService.delByPersonId(person.getId());

        return updateById(person);
    }

    /**
     * 详情
     */
    public BcPersonSupport get(Long id) {
        log.info("BcPersonSupportService - get id:{}", id);

        BcPersonSupport person = getById(id);

        // 查询家庭成员
        List<BcPersonFamily> familyList = familyService.listByPersonId(id);

        person.setFamilyList(familyList);

        // 查询房间床位
        BcHospitalRecord record = hospitalRecordService.getRecordByPersonId(id);
        if (null != record) {
            person.setRoomId(record.getRoomId());
            person.setBedId(record.getBedId());
        }

        return person;
    }

    /**
     * 列表查询
     */
    public List<BcPersonSupport> queryList(BcPersonSupport person) {
        log.info("BcPersonSupportService - queryList person:{}", person);

        List<BcPersonSupport> personList = baseMapper.queryList(person);
        for (BcPersonSupport personVO : personList) {
            // 查询居住房间
            BcHospitalRecord record = hospitalRecordService.getRecordByPersonId(personVO.getId());
            if (null != record) {
                personVO.setRoomBed(record.getBedName());
            }

            if (personVO.getType() == 1) {
                if (null != personVO.getVillage()) {
                    personVO.setVillageName(sysDataDictionaryItemService.findDictonaryBydictonaryCode("0040", personVO.getVillage()));
                }
                if (null != personVO.getSupportType()) {
                    personVO.setSupportTypeName(sysDataDictionaryItemService.findDictonaryBydictonaryCode("0020", personVO.getSupportType()));
                }
                if (null != personVO.getNursingLevel()) {
                    personVO.setNursingLevelName(sysDataDictionaryItemService.findDictonaryBydictonaryCode("0021", personVO.getNursingLevel()));
                }
            }
        }
        return personList;
    }

}
