package bus.controller.biz;

import com.orcas.common.enums.YesOrNo;
import com.orcas.common.enums.sso.UserSateResponse;
import com.orcas.common.model.ValueLabelObject;
import com.orcas.common.sso.model.*;
import com.orcas.common.usercenter.model.*;
import com.orcas.dictionary.common.dto.JsonAreaDto;
import com.orcas.fileclient.common.entity.FileEntity;
import com.orcas.fileclient.service.FileStoreClient;
import com.orcas.iso.config.common.user.CurrentUserHolder;
import com.orcas.iso.service.MenuClient;
import com.orcas.iso.service.SsoClient;
import com.orcas.iso.service.UserClient;
import bus.model.dto.CommonLoginDto;
import bus.service.CommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.qzwisdom.qzframework.core.tool.base.controller.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
* @Program: bus
* @Description: 描述
* @Author: zy
* @Date: 2025-03-06 22:43:31
**/
@RestController
@RequestMapping("/common")
@Api(tags = "公共接口")
public class CommonController  implements BaseController {
    @Value("${orcas.productNo}")
    private String productNo;
    @Value("${orcas.microNo}")
    private String microNo;
    @Autowired
    private SsoClient ssoClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private MenuClient menuClient;
    @Autowired
    private FileStoreClient fileStoreClient;

    @Autowired
    private CommonService commonService;


    @ApiOperation("登录")
    @PostMapping("/doLogin")
    @CrossOrigin
    public Object doLogin(HttpServletRequest request, HttpServletResponse response,
                                @RequestBody CommonLoginDto userLoginRequest){
        //注意加了审计注解的方法需要手动捕获异常
        try{
            SsoUserAuthDto ssoUserAuthDto = commonService.doLogin(request,response,userLoginRequest);
            return ssoUserAuthDto;
        }catch (Exception e){
            return e.getMessage();
        }
    }
    @ApiOperation("登出")
    @GetMapping("/doLoginOut")
    @CrossOrigin
    public String doLoginOut(HttpServletRequest request, HttpServletResponse response){
       try{
            Boolean flag = ssoClient.doLogout(request,response);
            if(flag){
                return "退出成功";
            }else{
                return "退出失败";
            }
       }catch (Exception e){
            return e.getMessage();
       }
    }

    @ApiOperation("注册")
    @PostMapping("/registerUser")
    @CrossOrigin
    public Object registerUser(HttpServletRequest request, HttpServletResponse response,
                                @RequestBody RegisterRequest registerRequest){
        registerRequest.setAccountName(registerRequest.getUserPhone());
        SsoUserResponse ssoUserResponse = ssoClient.registerUser(registerRequest);
        if(UserSateResponse.USER_STATE_02.getCode().equals(ssoUserResponse.getUserSate())){
            return "手机号已存在";
        }
        return ssoUserResponse;
    }

    @ApiOperation("获取当前人员在本应用的菜单资源")
    @GetMapping("/getTenantMenu")
    public List<MenuTreeNode> getTenantMenu(String gotoMicroNo){
        MenuTreeRequest menuTreeRequest = new MenuTreeRequest();
        menuTreeRequest.setUnitOrganizeId(CurrentUserHolder.get().getUnitOrganizeId());
        menuTreeRequest.setUsername(CurrentUserHolder.get().getUserName());
        menuTreeRequest.setProductNo(productNo);
        menuTreeRequest.setGotoMicroNo(microNo);
        menuTreeRequest.setIsAdmin(CurrentUserHolder.get().getIsAdmin());
        menuTreeRequest.setStaffId(CurrentUserHolder.get().getStaffId());
        menuTreeRequest.setAccountName(CurrentUserHolder.get().getAccountName());
        List<MenuTreeNode> menuTreeNodes = menuClient.getRoleMenuList(menuTreeRequest);
        return menuTreeNodes;
    }

    @ApiOperation("获取每个产品的门户资源菜单树")
    @GetMapping("/getAllPortalMenus")
    public List<ProductPortalMenu> getAllPortalMenus(){
        MenuTreeRequest menuTreeRequest = new MenuTreeRequest();
        menuTreeRequest.setUnitOrganizeId(CurrentUserHolder.get().getUnitOrganizeId());
        menuTreeRequest.setUsername(CurrentUserHolder.get().getUserName());
        menuTreeRequest.setIsAdmin(CurrentUserHolder.get().getIsAdmin());
        menuTreeRequest.setStaffId(CurrentUserHolder.get().getStaffId());
        menuTreeRequest.setAccountName(CurrentUserHolder.get().getAccountName());
        List<ProductPortalMenu> productPortalMenuList = menuClient.getAllPortalMenus(menuTreeRequest);
        return productPortalMenuList;
    }


    @ApiOperation("修改密码")
    @PostMapping("/updatePassword")
    public Object updatePwd(@RequestBody UpdatePasswordRequest request){
        try{
            SsoUserAuthDto ssoUserAuthDto = ssoClient.updatePassword(request);
            return ssoUserAuthDto;
        }catch (Exception e){
            return e.getMessage();
        }
    }

    @ApiOperation("新增租户组织")
    @PostMapping("/addUnitOrganize")
    public TenantRequest addUnitOrganize(HttpServletRequest request,@RequestBody TenantRequest tenantRequest) {
        tenantRequest.setSsoUserId(CurrentUserHolder.get().getUserId());
        tenantRequest.setAccountName(CurrentUserHolder.get().getAccountName());
        tenantRequest.setUserName(CurrentUserHolder.get().getUserName());
        tenantRequest.setUserPhone(CurrentUserHolder.get().getUserPhone());
        TenantRequest returnTenanRequest = userClient.createTenant(tenantRequest);
        // 新增成功后 切换组织并刷新redis缓存
        userClient.updateSelectedTenant(request,tenantRequest.getUniformCreditCode());
        return returnTenanRequest;
    }

    @ApiOperation("获取租户组织列表")
    @PostMapping("/getUnitOrganize")
    public List<TenantSimpleDto> getUnitOrganize() {
        List<TenantSimpleDto> tenantSimpleDtoList = userClient.getTenantList(CurrentUserHolder.get().getAccountName());
        if(!CollectionUtils.isEmpty(tenantSimpleDtoList)){
        	for(TenantSimpleDto dto : tenantSimpleDtoList){
        		if(dto.getUniformCreditCode().equals(CurrentUserHolder.get().getUniformCreditCode())){
					dto.setIsSelected(YesOrNo.YES.getValue());
					break;
				}
			}
		}
        return tenantSimpleDtoList;
    }

	@ApiOperation("选择租户组织")
	@GetMapping("/updateSelectedTenant")
	public String updateSelectedTenant(HttpServletRequest request,@RequestParam String uniformCreditCode) {
		userClient.updateSelectedTenant(request,uniformCreditCode);
		return "设置成功";
	}



    @ApiOperation("获取数据字典")
    @PostMapping("/getDataDict")
    public List<ValueLabelObject> getDataDict(@RequestBody String dictCode) {
        List<ValueLabelObject> valueLabelObjectList = commonService.getDataDict(dictCode);
        return valueLabelObjectList;
    }

    @ApiOperation("获取当前用户")
    @GetMapping("/getCurrentUser")
    public ExtInfo getCurrentUser() {
        ExtInfo extInfo = CurrentUserHolder.get();
        String accountName = CurrentUserHolder.get().getAccountName();
        List<TenantSimpleDto> tenantSimpleDtoList = userClient.getTenantList(accountName);
        extInfo.setTenantSimpleDtoList(tenantSimpleDtoList);
        return extInfo;
    }

    @ApiOperation("行政区域及其子类")
    @PostMapping("/getAreaDict")
    public List<JsonAreaDto> getAreaDict() {
        List<JsonAreaDto> jsonAreaDtoList = commonService.getAreaDict();
        return jsonAreaDtoList;
    }

    @ApiOperation("文件上传")
    @PostMapping("/addFile")
    public FileEntity addFile(@RequestBody MultipartFile file) {
        FileEntity fileEntity = null;
        try {
            fileEntity = fileStoreClient.upload(file.getBytes(),file.getOriginalFilename(),productNo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileEntity;
    }
}
