package com.yh.saas.plugin.yiliangyiyun.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsea.svc.base.base.entity.CommonCompany;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.entity.CommonStaffRole;
import com.winsea.svc.base.base.service.ICommonCompanyService;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.base.util.ClientTypeChecker;
import com.winsea.svc.base.base.util.MessagePusherUtils;
import com.winsea.svc.base.security.entity.Account;
import com.winsea.svc.base.security.exception.AuthErrorCodeEnums;
import com.winsea.svc.base.security.exception.AuthException;
import com.winsea.svc.base.security.service.IAccountService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.base.security.vo.command.AuthUserCommand;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.winsea.svc.base.workflow.entity.WorkflowHistoricTask;
import com.winsea.svc.base.workflow.entity.WorkflowStep;
import com.winsea.svc.notice.entity.NoticeTaskInfo;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.plugin.yiliangyiyun.constant.ImageCensorConsts;
import com.yh.saas.plugin.yiliangyiyun.entity.CommonUser;
import com.yh.saas.plugin.yiliangyiyun.entity.UnimallMessage;
import com.yh.saas.plugin.yiliangyiyun.entity.view.UserDefinedBean;
import com.yh.saas.plugin.yiliangyiyun.exception.ServiceException;
import com.yh.saas.plugin.yiliangyiyun.service.ICommonUserService;
import com.yh.saas.plugin.yiliangyiyun.service.INewWorkflowService;
import com.yh.saas.plugin.yiliangyiyun.util.Base64Util;
import com.yh.saas.plugin.yiliangyiyun.util.FileUtil;
import com.yh.saas.plugin.yiliangyiyun.util.HttpUtil;
import com.yh.saas.plugin.yiliangyiyun.util.WebSocket;
import com.yh.saas.toolkit.workflow.service.IWorkflowHistoryService;
import org.activiti.engine.impl.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.alibaba.fastjson.JSON;
import java.net.URLEncoder;
/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Gongdc
 * @since 2021-07-12
 */
@RestController
@RequestMapping("/commonUser")
public class CommonUserController {

    private static final String DEFAULT_COMPANY_MANAGER_USRENAME = "admin";
    @Autowired
    private ICommonUserService commonUserService;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private IAccountService userService;

    @Autowired
    private ICommonStaffService staffService;
    @Autowired
    private IWorkflowHistoryService workflowHistoryService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private ICommonCompanyService companyService;
    @Autowired
    private WebSocket webSocket;


    /**
     * 图像审核识别Demo
     * @param imagePath
     * @param accessToken
     * @return UserDefinedBean
     * @throws Exception
     */
    @PostMapping("/getUserDefinedBean")
    public static UserDefinedBean getUserDefinedBean(String imagePath, String accessToken) throws Exception{
        byte[] imgData = FileUtil.readFileByBytes(imagePath);
        String imgStr = Base64Util.encode(imgData);
        String param = "image=" + URLEncoder.encode(imgStr,"UTF-8");
//		String jsonParam = "{\"top_num\":5,\"image\":\"图片的base64\"}";
        // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
        String result = HttpUtil.post(ImageCensorConsts.ANTI_USER_DEFINED_URL, accessToken, param);
        UserDefinedBean userDefinedBean = JSON.parseObject(result, UserDefinedBean.class);
        return userDefinedBean;
    }

    /**
     * 查询历史
     *
     * @param businessKey
     * @return
     */
    @GetMapping("/getHis")
    public List<WorkflowHistoricTask> getHis(String businessKey, String workflowId) throws ServiceException {
        List<WorkflowHistoricTask> workflowHistoricTasks = workflowHistoryService.getInstanceHistories(businessKey);
        Workflow workflow = workflowService.getWorkflowDetail(workflowId);
        if (CollectionUtil.isNotEmpty(workflowHistoricTasks) && workflow != null) {
            Collections.reverse(workflowHistoricTasks);
//            List<WorkflowHistoricTask> workflowHistoricTaskList = new ArrayList<>();
//            int p = workflowHistoricTasks.size() - 1;
//            for (int i = 0; i < workflowHistoricTasks.size(); i++) {
//                workflowHistoricTaskList.add(workflowHistoricTasks.get(p));
//                p = p - 1;
//            }
//            workflowHistoricTasks = new ArrayList<>();
//            workflowHistoricTasks = workflowHistoricTaskList;
            List<WorkflowStep> workflowSteps = workflow.getSteps();
            WorkflowHistoricTask workflowHistoricTask = workflowHistoricTasks.get(workflowHistoricTasks.size() - 1);
            int a = 0;
            for (int i = 0; i < workflowSteps.size(); i++) {
                if ((workflowSteps.get(i).getAuditRoles().equals(AuthSecurityUtils.getStaffById(workflowHistoricTask.getOperatorId()).getMajorRoleId()))
                        || (!StringUtils.isEmpty(workflowSteps.get(i).getAuditUsers()) && workflowSteps.get(i).getAuditUsers().equals(workflowHistoricTask.getOperatorId()))) {
                    break;
                } else {
                    a = a + 1;
                    continue;
                }


            }
            if (a < workflowSteps.size()) {
                for (int i = a + 1; i < workflowSteps.size(); i++) {
                    WorkflowHistoricTask workflowHistoricTask1 = new WorkflowHistoricTask();
                    workflowHistoricTask1.setOperatorMajorRoleName(workflowSteps.get(i).getDesc());
                    workflowHistoricTasks.add(workflowHistoricTask1);
                }

            }

        } else {
            List<WorkflowStep> workflowSteps = workflow.getSteps();
            for (int i = 0; i < workflowSteps.size(); i++) {
                WorkflowHistoricTask workflowHistoricTask1 = new WorkflowHistoricTask();
                workflowHistoricTask1.setOperatorMajorRoleName(workflowSteps.get(i).getDesc());
                workflowHistoricTasks.add(workflowHistoricTask1);
            }
        }
        return workflowHistoricTasks;
    }

    /**
     * 注册
     *
     * @param commonUser
     * @return
     */
    @PostMapping("/register")
    public String register(@RequestBody CommonUser commonUser) throws ServiceException {
        return commonUserService.register(commonUser);
    }

    /**
     * 重置密码
     *
     * @param commonUser
     * @return
     */
    @PostMapping("/resetPassword")
    public String resetPassword(@RequestBody CommonUser commonUser) throws ServiceException {
        return commonUserService.resetPassword(commonUser);
    }


    /**
     * 修改用户信息
     *
     * @param commonUser
     * @return
     */
    @PostMapping("/editUserInfo")
    public String editUserInfo(@RequestBody CommonUser commonUser) throws ServiceException {
        return commonUserService.editUserInfo(commonUser);
    }

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     * @throws ServiceException
     */
    @GetMapping("/sendVerifyCode")
    public String sendVerifyCode(String phone) throws ServiceException {
        return commonUserService.sendVerifyCode(phone);
    }

    /**
     * 登录
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @GetMapping("/login")
    public CommonUser login(CommonUser commonUser) throws ServiceException {
        return commonUserService.login(commonUser);
    }

    /**
     * 快捷登录
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @GetMapping("/loginVerifyCode")
    public CommonUser loginVerifyCode(CommonUser commonUser) throws ServiceException {
        return commonUserService.loginVerifyCode(commonUser);
    }

    /**
     * 校验验证码
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @GetMapping("/checkVerifyCode")
    public CommonUser checkVerifyCode(CommonUser commonUser) throws ServiceException {
        return commonUserService.checkVerifyCode(commonUser);
    }


    /**
     * 快速登录
     *
     * @return 登录信息
     */
    @PostMapping("/api/loginQuickly")
    public Account loginQuickly(@RequestBody AuthUserCommand.LoginQuickly loginQuicklyCommand) {
        return commonUserService.login(createLoginUser(loginQuicklyCommand), loginQuicklyCommand.getVeriCode());
    }


    /**
     * 创建登录用户
     *
     * @param authUser 登录信息
     * @return 登录用户
     */
    private Account createLoginUser(AuthUserCommand authUser) {
        Account user = new Account();

        String userAccount = authUser.getUsername();
        if (StringUtils.isEmpty(userAccount)) {
            // 用户名为空则使用手机号作为登录名
            if (!StringUtils.isEmpty(authUser.getMobilePhone())) {
                userAccount = authUser.getMobilePhone();
            }
            // 用户名为空并且手机号也为空则使用默认用户名
            else {
                userAccount = DEFAULT_COMPANY_MANAGER_USRENAME;
            }
        }

        String compId = null;
        // 如果是岸基则使用域名获取公司ID
        if (!ClientTypeChecker.isVesselTerminal()) {
            if (!StringUtils.isEmpty(authUser.getCompanyName())) {
                CommonCompany commonCompany = companyService.findCompNameInfo(authUser.getCompanyName());
                if (null == commonCompany) {
                    throw new AuthException(AuthErrorCodeEnums.COMP_NAME_NULL);
                }
                compId = commonCompany.getCompId();
            } else {
                compId = companyService.getCompanyIdByDomainName(authUser.getCompanyId(), authUser.getDomainName(),
                        request.getServerName());

                if (StringUtils.isEmpty(compId)) {
//                    compId = userService.findPhoneCompId(authUser.getMobilePhone());
                    CommonUser commonUser = commonUserService.selectOne((new EntityWrapper()).eq("phone",authUser.getMobilePhone())
                    .eq("delete_flag","0"));
                    CommonStaff commonStaff = staffService.selectById(commonUser.getId());
                    compId = commonStaff.getCompId();
                }
            }
        }
        // 如果是船端则获取船舶信息表中第一条数据的公司ID作为登录用公司ID
        else {
//            compId = companyService.selectById(vesselService.selectOne(null).getCompId()).getCompId();
        }

        user.setLoginName(userAccount);
        user.setUserMobilePhone(authUser.getMobilePhone());
        user.setLoginPassword(authUser.getPassword());
        user.setAccountType(
                null != authUser.getUserKind() ? Account.AccountType.valueOf(authUser.getUserKind()) : null);
        user.setCompId(compId);
        return user;
    }


    /**
     * 查询任务
     *
     * @param noticeTask 查询条件
     * @return 返回分页查询结果
     */
    @GetMapping("/query/findHisPageNoticeTasks")
    public Page<NoticeTaskInfo> findHisPageNoticeTasks(NoticeTaskInfo noticeTask) {
        return commonUserService.findHisPageNoticeTasks(noticeTask);
    }

    /**
     * 查验app 账号
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @PostMapping("/api/checkApp")
    public String checkApp(@RequestBody CommonUser commonUser) throws ServiceException {
        return commonUserService.checkApp(commonUser);
    }

    /**
     * Session检测
     *
     * @return
     * @throws ServiceException
     */
    @GetMapping("/api/checkSession")
    public String checkSession() throws ServiceException {
        return commonUserService.checkSession();
    }

    /**
     * 公司
     *
     * @return
     */
    @GetMapping("/getComp")
    public List<CommonCompany> getComp() {
        return commonUserService.getComp();
    }

    /**
     * 公司
     *
     * @return
     */
    @GetMapping("/getCompOwn")
    public List<CommonCompany> getCompOwn(String phone) {
        return commonUserService.getCompOwn(phone);
    }

    /**
     * 首页公司下拉列表
     *
     * @return
     */
    @GetMapping("/getCompList")
    public List<String> getCompList(String userMobilePhone) {
        return commonUserService.getCompList(userMobilePhone);
    }

    /**
     * 次要职务
     *
     * @return
     * @throws ServiceException
     */
    @PostMapping("/api/saveRole")
    public String saveRole(@RequestBody CommonStaffRole commonStaffRole) {
        return commonUserService.saveRole(commonStaffRole);
    }

    @PostMapping({"/api/changeInfo"})
    public void changeInfo(@RequestBody CommonStaff staff) {
        commonUserService.changeInfo(staff);
    }


    @PostMapping("/test")
    public void test() {
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("msg", "1234567");
//        MessagePusherUtils.sendPrivateMessage(AuthSecurityUtils.getCurrentUserId(),JSONObject.toJSONString(jsonObject));
        UnimallMessage messageDO = new UnimallMessage();
        messageDO.setAdminId(AuthSecurityUtils.getCurrentUserId());
        messageDO.setCustomer(AuthSecurityUtils.getCurrentUserInfo().getLoginName());
        messageDO.setOperation("XX");
        messageDO.setResult("XX");
        messageDO.setGmtUpdate(new Date());
        messageDO.setGmtCreate(new Date());
        messageDO.setTaskId(IdGenerator.generateUUID());
        messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
        messageDO.setPath("XXXXX");
        webSocket.sendOneMessage(messageDO);
    }
}

