package com.sw.mes.yb.api;

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.factory.init.entity.Classname;
import com.sw.mes.base.factory.init.entity.Classno;
import com.sw.mes.base.factory.init.service.ClassnameService;
import com.sw.mes.base.factory.init.service.ClassnoService;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.core.api.auth.AuthFeignClient;
import com.sw.mes.core.dto.auth.UserClassDto;
import com.sw.mes.core.dto.auth.UserDto;
import com.sw.mes.core.response.MobileResponse;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.DateUtil;


import com.sw.mes.core.utils.HttpUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 工控机、移动端登录接口
 */
@RestController
@Slf4j
@RequestMapping("/mes")
public class TelnetController {

    @Autowired
    private AuthFeignClient authFeignClient;

    @Autowired
    private EquipmentService equipmentService;

//    @Autowired
//    private EquipmentStateService equipmentStateService;

    @Autowired
    private ClassnoService classnoService;

    @Autowired
    private ClassnameService classnameService;

//    @Autowired
//    private SlingLogService slingLogService;


    /**
     * 登录-主要用于IPC登录
     * ipcLog={"username":"","password":""}
     * 或ipcLog={"cardno":""}
     * @param ipcLog
     * @return
     */
    @RequestMapping(value = "/request/login", method = RequestMethod.POST)
    public @ResponseBody String ipcLogin(String ipcLog) {

        MobileResponse map = new MobileResponse();

        JSONObject jsonObject = JSONObject.parseObject(ipcLog);

        if(jsonObject != null){
            map = login(jsonObject);
        }

        return JSONObject.toJSONString(map);
    }

    /**
     * 用户名密码登录
     * @param username
     * @param password
     * @return
     */
    @ApiOperation(value = "用户名密码登陆")
    @RequestMapping(value = "/loginWithUsername", method = RequestMethod.POST)
    public @ResponseBody Result loginWithName(String username, String password) {

        try {
            Map<String, Object> map = loginByUsernameMethod(username, password);
            return ResultGenerator.success(map);
        } catch (Exception e) {
            return ResultGenerator.fail("登陆异常：" + e.getMessage());
        }
    }

    @ApiOperation(value = "登陆获取权限code")
    @RequestMapping(value = "/getPermissionByLoginName", method = RequestMethod.POST)
    public @ResponseBody Result getPermissionByLoginName(String username, String password) {

        try {
            Map<String, Object> map = authFeignClient.getPermissionByLoginName(username, password).getData();
            return ResultGenerator.success(map);
        } catch (Exception e) {
            return ResultGenerator.fail("异常：" + e.getMessage());
        }
    }

    /**
     * 卡号登录
     * @param cardno
     * @return
     */
    @ApiOperation(value = "卡号登陆")
    @RequestMapping(value = "/loginWithCardno", method = RequestMethod.POST)
    public @ResponseBody String loginWithCardNo(String cardno) {

        MobileResponse map = loginByCardNo(cardno);

        return JSONObject.toJSONString(map);
    }

    /**
     * json方式登陆
     * {"username":"","password":""}
     * 或{"cardno":""}
     * @param request
     * @return
     */
    @ApiOperation(value = "JSON方式登陆")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody String mobileLogin(HttpServletRequest request) {

        JSONObject jsonObject = HttpUtil.getRequestJson(request);

        MobileResponse map = login(jsonObject);

        return JSONObject.toJSONString(map);
    }

    @ApiOperation(value = "获取当前时间")
    @GetMapping(value = "/getTime")
    public @ResponseBody Result getCurrentTime() {

        return ResultGenerator.success(new Date());
    }

    @ApiOperation(value = "获取系统时间")
    @GetMapping(value = "/getNowServiceDate")
    public @ResponseBody Result getNowServiceDate() {
        return ResultGenerator.success(DateUtil.formatDate(new Date(), DateUtil.longFormat));
    }

    @ApiOperation(value = "获取班次信息")
    @GetMapping(value = "/getClassNo")
    public @ResponseBody Result getClassNo() {

        List<Classno> classnos = classnoService.findAll();

        return ResultGenerator.success(classnos);
    }

    @ApiOperation(value = "获取班组信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "process", value = "工序", dataType = "String", paramType = "query"),
    })
    @GetMapping(value = "/getClassName")
    public @ResponseBody Result getClassName(String process) {

        List<Classname> classnames = new ArrayList<>();

        if (StringUtils.isNotBlank(process)) {
            classnames = classnameService.findByGongxu(process);
        }
        if (classnames == null || classnames.size() == 0) {
            classnames = classnameService.findAll();
        }

        return ResultGenerator.success(classnames);
    }

    private MobileResponse loginByUsername(String username, String password) {
        Map<String, Object> map;
        try {
            map = authFeignClient.loginByUsername(username, password).getData();
        } catch (Exception e) {
            return MobileResponse.fail(e.getMessage());
        }
        return MobileResponse.success(map);
    }

    private Map<String, Object> loginByUsernameMethod(String username, String password) throws Exception {
        try {
            return authFeignClient.loginByUsername(username, password).getData();
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    private MobileResponse loginByCardNo(String cardNo) {
        Map<String, Object> map;
        try {
            map = authFeignClient.loginByCardNo(cardNo).getData();
        } catch (Exception e) {
            return MobileResponse.fail(e.getMessage());
        }
        return MobileResponse.success(map);
    }

    /**
     *
     * @param jsonObject
     * @return
     */
    public MobileResponse login(JSONObject jsonObject){

        if(jsonObject == null) {
            return MobileResponse.warn("登录数据为空！");
        }

        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");

        String cardno = jsonObject.getString("cardno");

        //批量登录标识
        String isbatch = jsonObject.getString("isbatch");
        //设备编号
        String deviceName = jsonObject.getString("devicename");

        Map<String, Object> map = new HashMap<>();

        try {
            if(StringUtils.isNotBlank(cardno)) {
                map = loginByCardNoNew(cardno);
            } else if(StringUtils.isNotBlank(username) && password != null){
                map = loginByUsernameNew(username, password);
            } else {
                return MobileResponse.fail("登陆信息异常！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MobileResponse.fail(e.getMessage());
        }

//        String loginmode = jsonObject.getString("loginmode");
//        //log.info("登陆模式="+loginmode);
//        //吊料登陆操作记录
//        if(StringUtils.isNotBlank(loginmode)&&loginmode.equalsIgnoreCase("zhuangliao")){
//            //log.info("吊料登陆设备编号="+deviceName);
//            Equipment equipment = equipmentService.findByCode(deviceName);
//            if(equipment!=null){
//                BatchInfo batchInfo = batchInfoService.findLotNoByDeviceNoDescOne(deviceName);
//                if(batchInfo!=null){
//                    if(StringUtils.isNotBlank(batchInfo.getLotNo())){
//                        List<SlingLog> checkSlingLogList = slingLogService.findByLotNo(batchInfo.getLotNo());
//                        if(checkSlingLogList==null||checkSlingLogList.size()==0){
//                            String userName = (String) map.get("realname");
//                            SlingLog slingLog = new SlingLog();
//                            slingLog.setId(null);
//                            slingLog.setCreateTime(new Date());
//                            slingLog.setUserName(userName);
//                            slingLog.setLotNo(batchInfo.getLotNo());
//                            slingLog.setDeviceNo(deviceName);
//                            slingLog.setSeries(deviceName.substring(0,1));
//                            slingLog.setDeviceType(equipment.getDeviceName());
//                            slingLogService.saveOrUpdate(slingLog);
//                        }
//                    }
//                }
//            }
//        }

//        if ((StringUtils.isNotBlank(isbatch) && isbatch.equalsIgnoreCase("1")) ||
//                (StringUtils.isNotBlank(loginmode) && loginmode.equalsIgnoreCase("produce"))) {
//            if (!map.isEmpty()) {
//                String userName = (String) map.get("realname");
//                if (StringUtils.isNotBlank(userName)) {
//                    Equipment equipment = equipmentService.findByCode(deviceName);
//                    if (equipment != null && StringUtils.isNotBlank(equipment.getStation())) {
//                        equipmentStateService.updateLoginUser(userName, equipment.getStation());
//                    }
//                }
//            }
//        }

        return MobileResponse.success(map);
    }

    public Map<String, Object> loginByUsernameNew(String username, String password) throws Exception {
        Map<String, Object> map;
        try {
            map= authFeignClient.loginByUsername(username, password).getData();
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return map;
    }

    private Map<String, Object> loginByCardNoNew(String cardNo) throws Exception {
        Map<String, Object> map;
        try {
            map = authFeignClient.loginByCardNo(cardNo).getData();
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return map;
    }

    @ApiOperation(value = "通过登录名获取班组/班次")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "登录姓名", dataType = "String", paramType = "query"),
    })
    @GetMapping(value = "/findClassInfoByLoginName")
    public @ResponseBody
    Result findClassInfoByLoginName(String loginName) {
        Result<UserClassDto> classInfo = authFeignClient.findClassInfoByLoginName(loginName);
        if (classInfo != null && classInfo.getData() != null) {
            return ResultGenerator.success(classInfo.getData());
        }
        return ResultGenerator.fail("用户表未维护对应班组或班次信息!");
    }

}
