package com.bonus.boot.manager.basic.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bonus.boot.manager.basic.dao.PersonnelLibraryDao;
import com.bonus.boot.manager.basic.entity.PersonnelLibraryBean;
import com.bonus.boot.manager.basic.entity.ZNode;
import com.bonus.boot.manager.basic.service.PersonnelLibraryService;
import com.bonus.boot.manager.manager.annotation.LogAnnotation;
import com.bonus.boot.manager.manager.controller.HttpClientUtils;
import com.bonus.boot.manager.manager.entity.AddressConfiguration;
import com.bonus.boot.manager.manager.entity.R;
import com.bonus.boot.manager.manager.entity.UnifyBean;
import com.bonus.boot.manager.manager.model.SysUser;
import com.bonus.boot.manager.manager.service.UserService;
import com.bonus.boot.manager.manager.utils.AjaxRes;
import com.bonus.boot.manager.manager.utils.GlobalConst;
import com.bonus.boot.manager.task.UnifyTask;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.bonus.boot.manager.manager.controller.UserController.login;
import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * 包名称：com.bonus.boot.manager.basic.controller
 * 类名称：PersonnelLibraryController
 * 类描述：体检人员库
 * 创建人：@author tqzhang
 * 创建时间：2023年05月31日 17:10
 */


@RestController
@RequestMapping("personnelLibrary")
public class PersonnelLibraryController {
    @Resource
    private PersonnelLibraryService service;

    @Autowired
    private UserService userService;

    @Resource
    private PersonnelLibraryDao daoDao;


    @LogAnnotation
    @PostMapping("getMsgContent")
    @ApiOperation(value = "体检人员库-列表")
    public R getList(PersonnelLibraryBean o) {
        List<PersonnelLibraryBean> list = service.getList(o);
        return list.size() > 0 ? R.okTable(list, list.size()) : R.failTable("暂无数据");
    }

    @RequestMapping(value = "addInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "体检人员库-新增")
    public AjaxRes addInfo(@RequestBody PersonnelLibraryBean bean) throws Exception {
        AjaxRes ar = new AjaxRes();
        int cb = service.addInfo(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if (cb > 0) {
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
            if (cb == 3) {
                ar.setFailMsg("人员已存在");
            }
            if (cb == 4) {
                ar.setFailMsg("人员年龄不符合标准");
            }
            if (cb == 5) {
                ar.setFailMsg("手机号已存在");
            }
            if (cb == 6) {
                ar.setFailMsg("姓名已存在");
            }

            int ks = 0;
            UnifyTask unifyTask = new UnifyTask();
            if (cb != 3 && cb != 5){
                String token = login();
                String isActive = addUser(bean.getPersonName(), bean.getPhone(),token);
                if(isActive.equals("1")){
                    ks = 1;
                    ar.setFailMsg(GlobalConst.INIT_SUCCEED);
                }else{
                    for (int i = 0; i < 3; i++) {
                        isActive = addUser(bean.getPersonName(), bean.getPhone(),token);
                        if(isActive.equals("1")){
                            ks = 1;
                            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
                            break;
                        }
                    }
                }
                //三次都未推送成功 修改推送状态
                if(ks!=1){
                    userService.updateUnify(Long.valueOf(bean.getHospId()));
                    ar.setFailMsg(GlobalConst.INIT_SUCCEED);
                }
            }else {
                ar.setFailMsg(GlobalConst.DATA_FAIL);
            }
        }
        return ar;
    }

    @RequestMapping(value = "updateInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "体检人员库-修改")
    public AjaxRes updateInfo(@RequestBody PersonnelLibraryBean bean) throws Exception {
        AjaxRes ar = new AjaxRes();
        int cb = service.updateInfo(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if (cb > 0) {
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
            if (cb == 3) {
                ar.setFailMsg("人员已存在");
            }
            if (cb == 5) {
                ar.setFailMsg("手机号已存在");
            }

            int ks = 0;
            if (cb != 3 && cb != 5){
                String token = login();
                String isActive = addUser(bean.getPersonName(), bean.getPhone(),token);
                if(isActive.equals("1")){
                    ks = 1;
                    ar.setFailMsg(GlobalConst.INIT_SUCCEED);
                }else{
                    for (int i = 0; i < 3; i++) {
                        isActive = addUser(bean.getPersonName(), bean.getPhone(),token);
                        if(isActive.equals("1")){
                            ks = 1;
                            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
                            break;
                        }
                    }
                }

                //三次都未推送成功 修改推送状态
                if(ks!=1){
                    userService.updateUnify(Long.valueOf(bean.getId()));
                    ar.setFailMsg(GlobalConst.INIT_SUCCEED);
                }
            }else {
                ar.setFailMsg(GlobalConst.DATA_FAIL);
            }

        }
        return ar;
    }

    @RequestMapping(value = "getListById", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "体检人员库-查询人员信息")
    public AjaxRes getListById(String id) {
        AjaxRes ar = new AjaxRes();
        PersonnelLibraryBean PersonnelLibraryBean = service.getListById(id);
        Map<String, Object> map = new HashMap<>();
        if (PersonnelLibraryBean != null) {
            map.put("PersonnelLibraryBean", PersonnelLibraryBean);
        }
        ar.setSucceed(map, GlobalConst.DATA_SUCCEED);
        return ar;
    }


    @LogAnnotation
    @PostMapping("delById")
    @ApiOperation(value = "体检人员库-删除")
    public AjaxRes delById(PersonnelLibraryBean bean) {
    AjaxRes ar = new AjaxRes();
    try {
        Long userId = Long.valueOf(bean.getId());
        SysUser userDto = daoDao.getEyId(userId);

        // 尝试删除操作
        String token = login();
        String isActive = deldctUnifyUser(userDto.getUsername(), userDto.getPhone(), token, "移动端");

        // 循环重试机制
        int ks = 0;
        while (!isActive.equals("1") && ks < 3) {
            isActive = deldctUnifyUser(userDto.getUsername(), userDto.getPhone(), token, "移动端");
            ks++;
        }
        // 如果尝试了3次仍然失败，则返回失败信息
        if (ks == 3) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        } else {
            int result = service.delById(bean);
            if (result == 1) {
                ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
            } else {
                ar.setFailMsg(GlobalConst.DATA_FAIL);
            }
        }
    } catch (Exception e) {
        // 异常处理
        ar.setFailMsg("Delete operation failed due to an internal error.");
    }
    return ar;
}


    @LogAnnotation
    @PostMapping("resetPassword")
    @ApiOperation(value = "体检人员库-删除")
    public AjaxRes resetPassword(PersonnelLibraryBean bean) {
        AjaxRes ar = new AjaxRes();
        int result = service.resetPassword(bean);
        if (result == 1) {
            ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
        } else {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    @LogAnnotation
    @PostMapping("getDepartmentTree")
    @ApiOperation(value = "体检人员库-获取部门树")
    public AjaxRes getDepartmentTree() {
        AjaxRes ar = new AjaxRes();
        try {
            List<ZNode> list = service.getDepartmentTree();
            ar.setSucceed(list);
        } catch (Exception e) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    /**
     * 新增用户
     *
     * @param userName 用户名
     * @param phone   手机号
     * @param token  token
     * @return 是否成功
     * @throws Exception 异常
     */
    public String addUser(String userName, String phone, String token) throws Exception {
        String isActive = "";
        List<UnifyBean> list = new ArrayList<>();
        UnifyBean userVo = new UnifyBean();
        userVo.setUserName(userName);
        userVo.setPhone(phone);
        userVo.setSystemName("健康体检");
        String permissionQuery = userService.getPermissionQuery(userVo);
        userVo.setAuth(permissionQuery);
        userVo.setIsBlacklist("0");
        userVo.setAccountStatus("1");
        list.add(userVo);
        String s = JSON.toJSONString(list);
        String encrypt = AESCBCUtils.encrypt(s, AESCBCUtils.sKey);
        String params = "{'params':'" + encrypt + "'}";
        JSONObject object = JSON.parseObject(params);
        String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/putUser", object, token);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        System.err.println("新增code="+code);
        if("200".equals(code)){
            JSONArray data = jsonObject.getJSONArray("data");
            System.err.println("新增data="+data);
            if(data.size() == 0){
                isActive = "1";
            }else{
                isActive = "0";
            }
        }else{
            isActive = "0";
        }
        return isActive;
    }

    private String deldctUnifyUser(String userName, String phone, String token, String auth) throws Exception {
        String isActive = "";
        List<UnifyBean> list = new ArrayList<>();
        UnifyBean userVo = new UnifyBean();
        userVo.setUserName(userName);
        userVo.setPhone(phone);
        userVo.setSystemName("健康体检");
        userVo.setAuth(auth);
        list.add(userVo);
        String s = JSON.toJSONString(list);
        String encrypt = AESCBCUtils.encrypt(s, AESCBCUtils.sKey);
        String params = "{'params':'" + encrypt + "'}";
        JSONObject object = JSON.parseObject(params);
//		String result = HttpClientUtils.doHttpPost("http://112.29.103.165:1616/ynuw/sys/api/delUser", object, token);
        String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/delUser", object, token);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        System.err.println("删除code="+code);
        if(code.equals("200")){
            JSONArray data = jsonObject.getJSONArray("data");
            System.err.println("删除data="+data);
            if(data.size() == 0){
                isActive = "1";
            }else{
                isActive = "0";
            }
        }else{
            isActive = "0";
        }
        return isActive;
    }

}
