/*
 * Copyright 2017-2020 吴学文 and java110 team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.java110.user.cmd.property;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.user.UserDto;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.property.PropertyUserPo;
import com.java110.user.dao.property.IPropertyUserV1ServiceDao;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户绑定工种和设备信息
 * 服务编码：property.userBind
 * 请求路径：/app/property.userBind
 */
@Java110Cmd(serviceCode = "property.userBind")
public class UserBindCmd extends Cmd {

    private static Logger logger = LoggerFactory.getLogger(UserBindCmd.class);

    @Autowired
    private IPropertyUserV1ServiceDao propertyUserV1ServiceDao;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMO;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "userId", "未包含用户ID");
        Assert.hasKeyAndValue(reqJson, "workType", "未包含工种");
        String workType = reqJson.getString("workType");
        Assert.isTrue("CLEANING".equals(workType) || "SECURITY".equals(workType) || "ENGINEERING".equals(workType),
                "工种必须为: CLEANING(保洁)/SECURITY(保安)/ENGINEERING(工程维修)");
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        // 验证用户存在
        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        List<UserDto> userDtos = userV1InnerServiceSMO.queryUsers(userDto);
        Assert.listOnlyOne(userDtos, "用户不存在");

        // 检查是否已绑定
        PropertyUserPo queryPo = new PropertyUserPo();
        queryPo.setUserId(reqJson.getString("userId"));
        Map params = new java.util.HashMap<>();
        params.put("userId", reqJson.getString("userId"));
        List<Map> existUsers = propertyUserV1ServiceDao.queryPropertyUsers(params);

        PropertyUserPo po = new PropertyUserPo();
        po.setUserId(reqJson.getString("userId"));
        po.setName(userDtos.get(0).getName());
        po.setTel(userDtos.get(0).getTel());
        po.setWorkType(reqJson.getString("workType"));
        po.setRole(reqJson.containsKey("role") ? reqJson.getString("role") : "STAFF");
        po.setStatus("ON");
        po.setDeviceId(reqJson.containsKey("deviceId") ? reqJson.getString("deviceId") : null);

        if (existUsers != null && !existUsers.isEmpty()) {
            propertyUserV1ServiceDao.updatePropertyUser(po);
        } else {
            propertyUserV1ServiceDao.savePropertyUser(po);
        }

        context.setResponseEntity(ResultVo.success());
    }
}
