package com.hssx.pcbms.controller;


import com.hssx.pcbms.constant.Constant;
import com.hssx.pcbms.entity.User;
import com.hssx.pcbms.entity.vo.UserVO;
import com.hssx.pcbms.service.UserService;
import com.hssx.pcbms.util.HttpRespMsg;
import com.hssx.pcbms.util.PageUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 吴涛涛
 * @since 2019-10-24
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册
     * 参数：phone 账号 password 密码 name 姓名 isPass:1 (注：创建管理员的账号时传，普通账号不传该字段)
     * code 验证码
     *
     * @return
     */
    @ApiOperation(value = "注册", notes = "注册方法")
    @RequestMapping("/regist")
    @ResponseBody
    public HttpRespMsg regist(User user, @RequestParam(required = false) String code) {
        HttpRespMsg msg = userService.regist(user, code);
        return msg;
    }

    /**
     * 登录
     * 参数：loginName 账号 password 密码
     *
     * @return
     */
    @ApiOperation(value = "登录", notes = "登录方法")
    @RequestMapping("/login")
    @ResponseBody
    public HttpRespMsg sysLogin(User user, HttpServletRequest request,
                                HttpServletResponse response) {
        HttpRespMsg msg = userService.login(user, request);
        return msg;
    }

    /**
     * 通讯录列表
     * @return
     */
    @ApiOperation(value = "用户列表", notes = "用户列表方法")
    @RequestMapping("/list")
    @ResponseBody
    public HttpRespMsg list(UserVO userVO, PageUtil page) {
        HttpRespMsg msg = userService.getList(userVO,page);
        return msg;
    }

    /**
     * 用户修改/审核接口
     * 参数：id:用户id（必传）
     * 要修改的参数：isPass 审核 0-不通过 1-通过，roleName 备注（角色）名称，deptId 部门id ,phone 修改手机号,file 头像文件
     *
     * @return
     */
    @ApiOperation(value = "用户修改", notes = "用户修改方法")
    @RequestMapping("/update")
    @ResponseBody
    public HttpRespMsg update(User user, @RequestParam(required = false) MultipartFile file) {
        HttpRespMsg msg = userService.updateUser(user, file);
        return msg;
    }

    /**
     * 忘记密码/修改密码接口
     * 参数：id:用户id（必传）password:密码，type :0-修改密码 1-忘记密码
     * type = 1 需要传手机号 phone:手机号,code:验证码
     *
     * @return
     */
    @ApiOperation(value = "忘记密码/修改密码接口", notes = "忘记密码/修改密码接口方法")
    @RequestMapping("/updateAndForgetPwd")
    @ResponseBody
    public HttpRespMsg updateAndForgetPwd(User user, Integer type, @RequestParam(required = false) String code) {
        HttpRespMsg msg = userService.updateAndForgetPwd(user, type, code);
        return msg;
    }

    /**
     * 用户分配权限
     * id:用户id permissionIds:权限对应的ids集合字符串（"1,2,3"）
     *
     * @return
     */
    @ApiOperation(value = "用户分配权限", notes = "角色分配权限方法")
    @RequestMapping("/handOutpermissions")
    @ResponseBody
    public HttpRespMsg handOutpermissions(User user, String permissionIds) {
        HttpRespMsg msg = new HttpRespMsg();
        msg = userService.handOutpermissions(user, permissionIds);
        return msg;
    }

    /**
     * 用户认证
     * loginUser 用户名，token 身份凭证
     *
     * @return
     */
    @ApiOperation(value = "用户认证", notes = "用户认证方法")
    @RequestMapping("/authentication")
    @ResponseBody
    public HttpRespMsg authentication(String loginUser, String token, HttpServletRequest request) throws ServiceException {
        HttpRespMsg msg = new HttpRespMsg();
        try {
//            String params ="";
            String appSessionId = request.getSession().getId();
            String wsdlUrl = "http://127.0.0.1/plat/services/SyncBaseService";
            String methodName = " getTicket";
            String sResult = "";
            if (wsdlUrl.indexOf("?wsdl") != -1) {
                wsdlUrl = wsdlUrl.replaceAll("\\?wsdl", "");
            }
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(wsdlUrl));
            call.setOperationName(methodName);
            log.debug("获取的系统同步数据");
            log.debug("token==>" + token + "appSessionId==>" + appSessionId + "");
            sResult = (String) call.invoke(new Object[]{token, Constant.APP_ID, appSessionId});
            log.debug("通过webService同步返回的参数为：" + sResult);
            Map<String, String> xmlAttribute = getXmlAttribute(sResult);
            if(!loginUser.equals(xmlAttribute.get("loginName"))){
                msg.setError("登录失败");
                return msg;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }
    /**
     * 调用同步部门接口
     *  token //应用标识
     * @return
     */
    @ApiOperation(value = "调用同步部门接口", notes = "调用同步部门接口方法")
    @RequestMapping("/getSyncDeptJson")
    @ResponseBody
    public HttpRespMsg getSyncDeptJson(String loginUser, String token, HttpServletRequest request) throws ServiceException {
        HttpRespMsg msg = new HttpRespMsg();
        try {
//            String params ="";
            String ivKey = "";//随机秘钥
            String timeStamp = "";//同步时间戳，如果为空则同步全部部门数据
            String appSessionId = request.getSession().getId();
            String wsdlUrl
                    = "http://127.0.0.1/plat/services/SyncBaseService";
            String methodName = " getSyncDeptJson";
            String sResult = "";
            if (wsdlUrl.indexOf("?wsdl") != -1) {
                wsdlUrl = wsdlUrl.replaceAll("\\?wsdl", "");
            }
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(wsdlUrl));
            call.setOperationName(methodName);
            log.debug("获取的系统同步数据");
            log.debug("ivKey==>" + ivKey + "timeStamp==>" + timeStamp + "");
            sResult = (String) call.invoke(new Object[]{Constant.APP_ID, ivKey,timeStamp});
            log.debug("通过webService同步返回的参数为：" + sResult);
            Map<String, String> xmlAttribute = getXmlAttribute(sResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }
    /**
     * 调用同步用户接口
     *  token //应用标识
     * @return
     */
    @ApiOperation(value = "调用同步用户接口", notes = "调用同步用户接口方法")
    @RequestMapping("/getSyncUserJson")
    @ResponseBody
    public HttpRespMsg getSyncUserJson(String loginUser, String token, HttpServletRequest request) throws ServiceException {
        HttpRespMsg msg = new HttpRespMsg();
        try {
//            String params ="";
            String ivKey = "";//随机秘钥
            String timeStamp = "";//同步时间戳，如果为空则同步全部部门数据
            String appSessionId = request.getSession().getId();
            String wsdlUrl
                    = "http://127.0.0.1/plat/services/SyncBaseService";
            String methodName = " getSyncUserJson";
            String sResult = "";
            if (wsdlUrl.indexOf("?wsdl") != -1) {
                wsdlUrl = wsdlUrl.replaceAll("\\?wsdl", "");
            }
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(wsdlUrl));
            call.setOperationName(methodName);
            log.debug("获取的系统同步数据");
            log.debug("ivKey==>" + ivKey + "timeStamp==>" + timeStamp + "");
            sResult = (String) call.invoke(new Object[]{Constant.APP_ID, ivKey,timeStamp});
            log.debug("通过webService同步返回的参数为：" + sResult);
            Map<String, String> xmlAttribute = getXmlAttribute(sResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * dom4j解析Xml
     *
     * @param xml
     */
    public static Map<String, String> getXmlAttribute(String xml) {
        Map<String, String> map = new HashMap<>();
        Document doc = null;
        // 将字符串转为XML
        try {
            doc = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 获取根节点
        Element recordEle = doc.getRootElement();
        System.out.println("根节点：" + recordEle.getName());
        //拿取根节点下的子节点的内容
        String ticketStr = recordEle.elementTextTrim("ticketId");
        map.put("ticketId", ticketStr);
        String loginName = recordEle.elementTextTrim("loginName");
        map.put("loginName", loginName);
        String guid = recordEle.elementTextTrim("guid");
        map.put("guid", guid);
        String pwd = recordEle.elementTextTrim("pwd");
        map.put("pwd", pwd);
        return map;
    }

    public static void main(String[] args) {
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>" +
                "<SsoTicket>" +
                "<ticketId>" + "a8a950:14715319393:-8000" + "</ticketId>" +
                "<loginName>test</loginName>" +
                "<guid>9001</guid>" +
                "<pwd>96E79218965EB72C92A549DD5A330112</pwd>" +
                "</SsoTicket>";
        Map<String, String> xmlAttribute = getXmlAttribute(xml);
        for (Map.Entry<String, String> entry : xmlAttribute.entrySet()) {
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            System.out.println(mapKey + ":" + mapValue);
        }
    }
}

