package com.lz.modules.equipment.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.common.emun.EquipmentState;
import com.lz.common.exception.ZSException;
import com.lz.common.utils.ISelect;
import com.lz.common.utils.PageUtils;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.equipment.dao.*;
import com.lz.modules.equipment.entity.*;
import com.lz.modules.equipment.entity.model.FindByNameModel;
import com.lz.modules.equipment.entity.model.FindEquipmentsByNameModel;
import com.lz.modules.equipment.service.IEquipmentInfoService;
import com.lz.modules.sys.entity.SysUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author quyixiao
 * @since 2020-07-24
 */

@Service
@Slf4j
public class EquipmentInfoServiceImpl extends ServiceImpl<EquipmentInfoMapper, EquipmentInfo> implements IEquipmentInfoService {


    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;
    @Autowired
    private EquipmentFlowRecordMapper equipmentFlowRecordMapper;

    @Autowired
	private EquipmentTypeMapper equipmentTypeMapper;

    @Autowired
	private EquipmentBrandMapper equipmentBrandMapper;
    @Autowired
	private StaffService staffService;
    @Autowired
	private SpecialApplyInfoMapper specialApplyInfoMapper;
    @Autowired
	private EquipmentSpecsMapper equipmentSpecsMapper;
    @Autowired
	private TCountMapper tCountMapper;




	@Override
	public EquipmentInfo selectEquipmentInfoById(Long id){
		return equipmentInfoMapper.selectEquipmentInfoById(id);
	}



	@Override
	public Long insertEquipmentInfo(EquipmentInfo equipmentInfo){
		return equipmentInfoMapper.insertEquipmentInfo(equipmentInfo);
	}



	@Override
	public int updateEquipmentInfoById(EquipmentInfo equipmentInfo){
		return equipmentInfoMapper.updateEquipmentInfoById(equipmentInfo);
	}

    @Override
    public int updateCoverEquipmentInfoById(EquipmentInfo equipmentInfo) {
        return equipmentInfoMapper.updateCoverEquipmentInfoById(equipmentInfo);
    }


    @Override
    public int deleteEquipmentInfoById(Long id) {
        return equipmentInfoMapper.deleteEquipmentInfoById(id);
    }




    @Override
	public int addEquipment(EquipmentInfo info) {
		info.setGmtInbound(new Date());
		info.setEquipmentState(EquipmentState.NORMAL.getCode());
		//addRecord(info);
		return equipmentInfoMapper.insert(info);
	}

	@Override
	public void changeEquipmentInfo(EquipmentDto dto, SysUserEntity infoDto) {
		log.info("编辑传入内容{}", dto);
		EquipmentType equipmentType = equipmentTypeMapper.selectEquipmentTypeById(dto.getTypeId());
		EquipmentBrand equipmentBrand = equipmentBrandMapper.selectEquipmentBrandById(dto.getBrandId());
		EquipmentSpecs equipmentSpecs = equipmentSpecsMapper.selectEquipmentSpecsById(dto.getSpecId());
		if(equipmentType==null){
			throw new ZSException("设备类型错误，不存在或被删除");
		}
		if(equipmentBrand==null){
			throw new ZSException("设备品牌错误，不存在或被删除");
		}
		if(equipmentSpecs==null){
			throw new ZSException("设备规格错误，不存在或被删除");
		}

		EquipmentInfo info = equipmentInfoMapper.selectEquipmentInfoById(dto.getId());
		if(info==null){
			EquipmentInfo insert = new  EquipmentInfo();
			insert.setType(equipmentType.getType());
			insert.setBrandName(equipmentBrand.getBrand());
			insert.setSpecType(equipmentSpecs.getSpecs());
			insert.setEquipmentState(dto.getState());
			BeanUtils.copyProperties(dto,insert);
			if(dto.isEmployee()){
				StaffEntity employeesInfo = staffService.selectStaffById(dto.getUserId());
				if(employeesInfo==null){
					throw new ZSException("申领人不存在");
				}
				insert.setUser(employeesInfo.getName());
				insert.setUserId(employeesInfo.getId());
			}else {
				SpecialApplyInfo specialApplyInfo = specialApplyInfoMapper.selectSpecialApplyInfoById(dto.getUserId());
				if(specialApplyInfo==null){
					throw new ZSException("申领方不存在");
				}
				insert.setUser(specialApplyInfo.getTypeDesc());
				insert.setSaiId(specialApplyInfo.getId());
			}
			equipmentInfoMapper.insert(insert);
			addRecord(insert,infoDto);

		}else {
			Integer state = dto.getState();
			if(dto.isEmployee()){
				StaffEntity employeesInfo = staffService.selectStaffById(dto.getUserId());
				if(employeesInfo==null){
					throw new ZSException("申领人不存在");
				}
				info.setUser(employeesInfo.getName());
				info.setUserId(employeesInfo.getId());
			}else {
				SpecialApplyInfo specialApplyInfo = specialApplyInfoMapper.selectSpecialApplyInfoById(dto.getUserId());
				if(specialApplyInfo==null){
					throw new ZSException("申领方不存在");
				}
				info.setUser(specialApplyInfo.getTypeDesc());
				info.setSaiId(specialApplyInfo.getId());
			}
			//根据是否员工重置其他id
			if(dto.isEmployee()){
				info.setSaiId(null);
			}else {
				info.setUserId(null);
			}
			info.setType(equipmentType.getType());
			info.setBrandName(equipmentBrand.getBrand());
			info.setSpecType(equipmentSpecs.getSpecs());
			info.setQr(dto.getQr());
			info.setCode(dto.getCode());
			info.setMark(dto.getMark());
			EquipmentState byCode = EquipmentState.findByCode(state);
			switch (byCode){
				case SALE:
					if(dto.getSaleAmount()==null){
						throw new ZSException("请填写出售金额");
					}
					info.setEquipmentState(state);
					info.setSaleAmount(dto.getSaleAmount());
					equipmentInfoMapper.updateCoverEquipmentInfoById(info);
					//出库增加日志操作
					addRecord(info,infoDto);
					break;
				case FAULT:
					if(StringUtil.isBlank(dto.getMark())){
						throw new ZSException("请备注故障原因");
					}
					info.setEquipmentState(state);
					equipmentInfoMapper.updateCoverEquipmentInfoById(info);
					addRecord(info,infoDto);
					break;
				case TRANSFER:
					info.setEquipmentState(state);
					info.setUser(EquipmentState.TRANSFER.getName());
					equipmentInfoMapper.updateCoverEquipmentInfoById(info);
					//出库增加日志操作
					addRecord(info,infoDto);
					break;
				case APPLY:
					if(StringUtil.isBlank(info.getUser())){
						throw new ZSException("请选择申领人");
					}
					info.setEquipmentState(state);
					equipmentInfoMapper.updateCoverEquipmentInfoById(info);
					//出库增加日志操作
					addRecord(info,infoDto);
					break;
				case NORMAL:
					info.setEquipmentState(state);
					equipmentInfoMapper.updateCoverEquipmentInfoById(info);
					//入库增加日志操作
					addRecord(info,infoDto);
					break;

				default:
					break;
			}
		}

	}

    @Override
    public EquipmentInfo selectEquipmentInfoByCode(String code) {
        return equipmentInfoMapper.selectEquipmentInfoByCode(code);
    }

    @Override
	public PageUtils selectByCondition(EquipmentInfoReq req) {
		if (req.getCount() == null) {
			TCount count = tCountMapper.selectMaxCount();
			req.setCount(count.getNum());
		}

        if (req.getTypeId() != null) {
			EquipmentType equipmentType = equipmentTypeMapper.selectEquipmentTypeById(req.getTypeId());
			req.setType(equipmentType.getType());
        }
        if(req.getBrandId() !=null){
        	EquipmentBrand equipmentBrand = equipmentBrandMapper.selectEquipmentBrandById(req.getBrandId());
        	req.setBrandName(equipmentBrand.getBrand());
		}
		PageUtils pageUtils = PageUtils.startPage(req.getPage(), req.getRows()).doSelect(
				page -> equipmentInfoMapper.selectByCondition(page, req)
		);
        return pageUtils;
        /*return PageUtils.startPage(req.getPage(), req.getRows()).doSelect(new ISelect() {
            @Override
            public List doSelect(Page page) {
                return equipmentInfoMapper.selectByCondition(page, req);
            }
        });*/
    }

    //记录日志
	private void addRecord(EquipmentInfo info,SysUserEntity infoDto){
		EquipmentFlowRecord record = new EquipmentFlowRecord();
		BeanUtils.copyProperties(info,record);
		record.setEquipmentId(info.getId());
		record.setChangeType(info.getEquipmentState());
		//record.setOriginalUser();
		record.setRecordUserId(infoDto.getUserId());
		record.setRecordUser(infoDto.getRealName());
		equipmentFlowRecordMapper.insertEquipmentFlowRecord(record);
	}

	@Override
	public List<EquipmentInfo> selectByStaffIdOrDepId(IPage page, FindEquipmentsByNameModel nameModel){
		return equipmentInfoMapper.selectByStaffIdOrDepId(page, nameModel);
	}

	@Override
	public EquipmentInfo selectEquipmentInfoByCount(Integer count){
		return equipmentInfoMapper.selectEquipmentInfoByCount(count);
	}

    @Override
    public int selectCountAllByState(Integer num) {

		return equipmentInfoMapper.selectCountAllByState(num);
    }

	@Override
	public int selectCountByState(Integer num, int state) {
		return equipmentInfoMapper.selectCountByState(num,state);
	}

	@Override
	public int selectCountByDepartmentIds(Integer num, List<String> asList) {

		return equipmentInfoMapper.selectCountByDepartmentIds(num,asList);
	}

	@Override
	public int selectCountByNotFind(Integer num) {
		return equipmentInfoMapper.selectCountByNotFind(num);
	}

	@Override
	public int selectCountAllDepartment(int num) {
		return equipmentInfoMapper.selectCountAllDepartment(num);
	}

	@Override
	public int updateCoverEquipmentInfoByTypeId(Long id, String type){
		return equipmentInfoMapper.updateCoverEquipmentInfoByTypeId(id, type);
	}

	@Override
	public int updateCoverEquipmentInfoByBrandId(Long id, String brand){
		return equipmentInfoMapper.updateCoverEquipmentInfoByBrandId(id, brand);
	}

	@Override
	public int updateCoverEquipmentInfoBySpecsId(Long id, String specs){
		return equipmentInfoMapper.updateCoverEquipmentInfoBySpecsId(id, specs);
	}
}
