package com.mortals.xhx.module.workman.service.impl;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.common.Rest;
import com.mortals.framework.util.SecurityUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.common.pdu.UploadDeviceReq;
import com.mortals.xhx.feign.device.IDeviceMessageFeign;
import com.mortals.xhx.module.gocome.model.GocomeRecordEntity;
import com.mortals.xhx.module.gocome.service.GocomeRecordService;
import com.mortals.xhx.module.room.model.RoomDeviceQuery;
import com.mortals.xhx.module.room.model.RoomEntity;
import com.mortals.xhx.module.room.model.RoomQuery;
import com.mortals.xhx.module.room.service.RoomDeviceService;
import com.mortals.xhx.module.room.service.RoomService;
import com.mortals.xhx.module.workman.model.WorkmanQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.workman.dao.WorkmanDao;
import com.mortals.xhx.module.workman.model.WorkmanEntity;
import com.mortals.xhx.module.workman.service.WorkmanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * WorkmanService
 * 工作人员 service实现
 *
 * @author zxfei
 * @date 2023-05-22
 */
@Service("workmanService")
@Slf4j
public class WorkmanServiceImpl extends AbstractCRUDServiceImpl<WorkmanDao, WorkmanEntity, Long> implements WorkmanService {

    @Autowired
    private GocomeRecordService gocomeRecordService;
     @Autowired
    private RoomService roomService;
     @Autowired
     private RoomDeviceService roomDeviceService;
    @Autowired
    private IDeviceMessageFeign messageFeign;


    @Override
    protected void saveBefore(WorkmanEntity entity, Context context) throws AppException {
        super.saveBefore(entity, context);
        if (StringUtils.isNotEmpty(entity.getLoginPwd())) {
            try {
                entity.setLoginPwd(SecurityUtil.md5DoubleEncoding(entity.getLoginPwd()));
            } catch (Exception e) {
                throw new AppException("密码转换异常");
            }
        } else {
            entity.setLoginPwd(null);
        }

        WorkmanEntity workmanEntity = this.selectOne(new WorkmanQuery().loginName(entity.getLoginName()));
        if(!ObjectUtils.isEmpty(workmanEntity)){
            throw new AppException("当前登录用户名已存在！");
        }
    }

    @Override
    protected void saveAfter(WorkmanEntity entity, Context context) throws AppException {
        super.saveAfter(entity, context);
        if(!ObjectUtils.isEmpty(entity.getRoomId())){
            RoomQuery roomQuery = new RoomQuery();
            roomQuery.setId(entity.getRoomId());
            roomQuery.setCountPersonIncrement(1L);
            roomService.update(roomQuery,context);
        }

        UploadDeviceReq uploadDeviceReq = new UploadDeviceReq();
        RoomEntity roomEntity = roomService.get(entity.getRoomId(), context);
        if(!ObjectUtils.isEmpty(roomEntity)){
            uploadDeviceReq.setDeviceCodeList( roomDeviceService.find(new RoomDeviceQuery().roomId(roomEntity.getId())).stream().map(i->i.getDeviceCode()).collect(Collectors.toList()));
            uploadDeviceReq.setAction("refreshWorkman");
            log.info("downMsg:{}", JSON.toJSONString(uploadDeviceReq));
            messageFeign.downMsg(uploadDeviceReq);
        }else{
            log.info("roomId:{}",entity.getRoomId());
        }
    }



    @Override
    protected void updateAfter(WorkmanEntity entity, Context context) throws AppException {
        super.updateAfter(entity, context);
        UploadDeviceReq uploadDeviceReq = new UploadDeviceReq();
        RoomEntity roomEntity = roomService.get(entity.getRoomId(), context);
        if(!ObjectUtils.isEmpty(roomEntity)){
            uploadDeviceReq.setDeviceCodeList( roomDeviceService.find(new RoomDeviceQuery().roomId(roomEntity.getId())).stream().map(i->i.getDeviceCode()).collect(Collectors.toList()));
            uploadDeviceReq.setAction("refreshWorkman");

          log.info("downMsg:{}", JSON.toJSONString(uploadDeviceReq));
            messageFeign.downMsg(uploadDeviceReq);
        }else{
            log.info("roomId:{}",entity.getRoomId());
        }
    }

    @Override
    protected void removeBefore(Long[] ids, Context context) throws AppException {
        WorkmanQuery workmanQuery = new WorkmanQuery();
        workmanQuery.setIdList(Arrays.asList(ids));
        this.find(workmanQuery,context).forEach(entity->{
            UploadDeviceReq uploadDeviceReq = new UploadDeviceReq();
            RoomEntity roomEntity = roomService.get(entity.getRoomId(), context);
            if(!ObjectUtils.isEmpty(roomEntity)){
                uploadDeviceReq.setDeviceCodeList( roomDeviceService.find(new RoomDeviceQuery().roomId(roomEntity.getId())).stream().map(i->i.getDeviceCode()).collect(Collectors.toList()));
                uploadDeviceReq.setAction("refreshWorkman");
                log.info("downMsg:{}", JSON.toJSONString(uploadDeviceReq));
                messageFeign.downMsg(uploadDeviceReq);
            }
        });

        super.removeBefore(ids, context);
    }

    @Override
    public WorkmanEntity doLogin(String loginName, String password, String loginIp) throws AppException {

        WorkmanQuery workmanQuery = new WorkmanQuery();
        workmanQuery.setLoginName(loginName);
        WorkmanEntity workmanEntity = this.selectOne(workmanQuery);
        if (workmanEntity == null || !workmanEntity.getLoginName().equals(loginName)) {
            throw new AppException("用户名不存在！");
        }
        try {
            if (!workmanEntity.getLoginPwd().equals(SecurityUtil.md5DoubleEncoding(password))) {
                throw new AppException("登录密码错误！");
            }
        } catch (Exception e) {
            throw new AppException("密码验认出错！", e);
        }
        return workmanEntity;
    }

    @Override
    public boolean updateUserPwd(String loginName, String oldPwd, String newPwd) throws AppException {
        WorkmanQuery workmanQuery = new WorkmanQuery();
        workmanQuery.setLoginName(loginName);
        WorkmanEntity sysUser = this.selectOne(workmanQuery);
        if (sysUser == null || !sysUser.getLoginName().equals(loginName)) {
            throw new AppException("帐号错误！");
        }
        try {
            if (!sysUser.getLoginPwd().equals(SecurityUtil.md5DoubleEncoding(oldPwd))) {
                throw new AppException("原始密码错误！");
            }
        } catch (Exception e) {
            throw new AppException("密码验认出错！", e);
        }
        try {
            sysUser.setLoginPwd(SecurityUtil.md5DoubleEncoding(newPwd));
        } catch (Exception e) {
            throw new AppException("密码转换异常！", e);
        }
        dao.update(sysUser);
        return true;
    }

    /**
     * @param loginName
     * @param newPwd
     * @return
     * @throws AppException
     */
    @Override
    public boolean updateUserPwd(String loginName, String newPwd) throws AppException {
        WorkmanQuery workmanQuery = new WorkmanQuery();
        workmanQuery.setLoginName(loginName);
        WorkmanEntity sysUser = this.selectOne(workmanQuery);
        if (sysUser == null || !sysUser.getLoginName().equals(loginName)) {
            throw new AppException("帐号错误！");
        }
        try {
            sysUser.setLoginPwd(SecurityUtil.md5DoubleEncoding(newPwd));
        } catch (Exception e) {
            throw new AppException("密码转换异常！", e);
        }
        dao.update(sysUser);
        return true;
    }


    @Override
    public Rest<String> changeStatus(WorkmanEntity workmanEntity, Context context) {
        if (ObjectUtils.isEmpty(workmanEntity.getId())) {
            return Rest.fail("工作人员ID不能为空！");
        }
        if (ObjectUtils.isEmpty(workmanEntity.getWorkStatus())) {
            return Rest.fail("工作人员状态不能为空！");
        }
        //查询当前状态
        WorkmanEntity newWorkman = this.get(workmanEntity.getId(), context);
        if(workmanEntity.getWorkStatus().equals(newWorkman.getWorkStatus())){
            return Rest.fail("工作人员修改状态不能一致！");
        }

        this.update(workmanEntity, context);
        GocomeRecordEntity recordEntity = new GocomeRecordEntity();
        recordEntity.initAttrValue();
        recordEntity.setBeforeStatus(newWorkman.getWorkStatus());
        recordEntity.setAfterStatus(workmanEntity.getWorkStatus());
        recordEntity.setPhone(newWorkman.getPhone());
        recordEntity.setDeptName(newWorkman.getDeptName());
        recordEntity.setRoomId(newWorkman.getRoomId());
        recordEntity.setRoomName(newWorkman.getRoomName());
        recordEntity.setUserName(newWorkman.getName());
        recordEntity.setCreateTime(new Date());
        recordEntity.setCreateUserId(this.getContextUserId(context));
        gocomeRecordService.save(recordEntity, context);

        return Rest.ok();
    }


    public static void main(String[] args) throws Exception {
        System.out.println(SecurityUtil.md5DoubleEncoding("11"));

    }
}