package com.mortals.xhx.module.workman.web;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.module.basic.model.BasicStatusQuery;
import com.mortals.xhx.module.basic.service.BasicStatusService;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.room.model.RoomEntity;
import com.mortals.xhx.module.room.model.RoomQuery;
import com.mortals.xhx.module.room.service.RoomService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.module.workman.model.WorkmanEntity;
import com.mortals.xhx.module.workman.service.WorkmanService;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.mortals.framework.ap.SysConstains.*;

/**
 * 工作人员
 *
 * @author zxfei
 * @date 2023-05-22
 */
@RestController
@RequestMapping("workman")
@Slf4j
public class WorkmanController extends BaseCRUDJsonBodyMappingController<WorkmanService, WorkmanEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private BasicStatusService statusService;


    public WorkmanController() {
        super.setModuleDesc("工作人员");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "sex", paramService.getParamBySecondOrganize("Workman", "sex"));
        this.addDict(model, "roomId", roomService.find(new RoomQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getRoomName(), (o, n) -> n)));
        this.addDict(model, "workStatus", statusService.find(new BasicStatusQuery()).stream().collect(Collectors.toMap(x -> x.getStatusName(), y -> y.getStatusName(), (o, n) -> n)));

        super.init(model, context);
    }

    @Override
    protected void doListBefore(WorkmanEntity query, Map<String, Object> model, Context context) throws AppException {
        super.doListBefore(query, model, context);

        if (!ObjectUtils.isEmpty(query.getDeviceCode())) {
            //根据设备编码 查询房间room
            RoomEntity roomEntity = roomService.selectOne(new RoomQuery().deviceCode(query.getDeviceCode()));
            if (!ObjectUtils.isEmpty(roomEntity)) {
                query.setRoomId(roomEntity.getId());
            }
        }

    }

    /**
     * 工作人员更新状态
     */
    @PostMapping(value = "change/status")
    @UnAuth
    public Rest<Void> changeStatus(@RequestBody WorkmanEntity workmanEntity) {
        String busiDesc = this.getModuleDesc() + "更新状态";
        Rest<Void> rest = Rest.ok(busiDesc + " 【成功】");
        try {
            this.service.changeStatus(workmanEntity, getContext());
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("工作人员更新状态消息", e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }


    /**
     * 工作人员登录
     */
    @PostMapping(value = "doLogin")
    @UnAuth
    public String doLogin(@RequestBody WorkmanEntity query) {
        log.info("doLogin==>{}", JSON.toJSONString(query));
        JSONObject ret = new JSONObject();
        try {
            String ip = super.getRequestIP(request);
            WorkmanEntity workmanEntity = this.service.doLogin(query.getLoginName(), query.getLoginPwd(), ip);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, "工作人员登录成功！");
            ret.put(KEY_RESULT_DATA, workmanEntity);
            recordSysLog(request, getCurUser(), "工作人员登录成功!");
            return ret.toJSONString();
        } catch (Exception e) {
            log.error("工作人员登录错误", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    @RequestMapping(value = "change/password", method = RequestMethod.POST)
    @UnAuth
    public String changePassword(@RequestBody WorkmanEntity query) {
        JSONObject ret = new JSONObject();
        try {
            boolean bool = service.updateUserPwd(query.getLoginName(), query.getNewPwd());
            if (bool) {
                ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
                ret.put(KEY_RESULT_MSG, "密码修改成功！");
            } else {
                throw new AppException("账户密码修改失败！");
            }

        } catch (Exception e) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return ret.toJSONString();
    }


    @RequestMapping(value = "person/change/password", method = RequestMethod.POST)
    @UnAuth
    public String personChangePassword(@RequestBody WorkmanEntity query) {
        JSONObject ret = new JSONObject();
        try {
            boolean bool = service.updateUserPwd(query.getLoginName(), query.getOldPwd(), query.getNewPwd());
            if (bool) {
                ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
                ret.put(KEY_RESULT_MSG, "密码修改成功！");
            } else {
                throw new AppException("账户密码修改失败！");
            }

        } catch (Exception e) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return ret.toJSONString();
    }


    @Override
    protected void deleteBefore(Long[] ids, Context context) throws AppException {
        super.deleteBefore(ids, context);
        List<WorkmanEntity> workmanEntities = this.service.get(ids, context);
        for (WorkmanEntity workmanEntity : workmanEntities) {
            RoomQuery roomQuery = new RoomQuery();
            roomQuery.setId(workmanEntity.getRoomId());
            RoomEntity roomEntity = roomService.selectOne(roomQuery, context);
            if(!ObjectUtils.isEmpty(roomEntity)){
                roomEntity.setCountPerson(roomEntity.getCountPerson()-1);
                roomService.update(roomEntity);
            }
        }
    }
}